NetworkIndexMixin
¶
flowchart TD
pypsa.Network[NetworkIndexMixin]
pypsa.network.abstract._NetworkABC[_NetworkABC]
pypsa.network.abstract._NetworkABC --> pypsa.Network
click pypsa.Network href "" "pypsa.Network"
click pypsa.network.abstract._NetworkABC href "" "pypsa.network.abstract._NetworkABC"
Mixin class for network index methods.
Class inherits to pypsa.Network. All attributes and methods can be used within any Network instance.
-
API Reference
Networks
Network
Network
Methods:
-
set_snapshots–Set the snapshots/time steps and reindex all time-dependent data.
-
set_investment_periods–Set the investment periods of the network.
-
set_scenarios–Set scenarios for the network to create a stochastic network.
-
set_risk_preference–Set risk aversion preferences for stochastic optimization using CVaR formulation.
-
get_scenario–Return a network for a single scenario from a stochastic network.
-
get_network–Return a single network from a NetworkCollection.
-
slice_network–Return a sliced copy of the network.
Attributes:
-
snapshots(Index | MultiIndex) –Snapshots dimension of the network.
-
timesteps(Index) –Timestep level of snapshots dimension.
-
periods(Index) –Periods level of snapshots dimension.
-
has_periods(bool) –Check if network has investment periods assigned to snapshots dimension.
-
investment_periods(Index) –Periods level of snapshots dimension.
-
has_investment_periods(bool) –Check if network has investment periods assigned to snapshots dimension.
-
snapshot_weightings(DataFrame) –Weightings applied to each snapshots during the optimization.
-
nyears(float | Series) –Return the modeled time horizon in years based on objective weightings.
-
investment_period_weightings(DataFrame) –Weightings applied to each investment period during the optimization (LOPF).
-
scenarios(Index) –Get the scenarios index for the network.
-
scenario_weightings(DataFrame) –Get the scenario weightings for the network.
-
has_scenarios(bool) –Boolean indicating if the network has scenarios defined.
-
risk_preference(dict[str, float] | None) –Get the risk preference parameters for the network.
-
has_risk_preference(bool) –Boolean indicating if the network has risk preferences defined.
-
is_collection(bool) –Check if this is a collection of networks or a single network.
pypsa.Network.snapshots
property
writable
¶
snapshots: Index | MultiIndex
Snapshots dimension of the network.
If snapshots are a pandas.MultiIndex, the first level are investment periods and the second level are timesteps. If snapshots are single indexed, the only level is timesteps.
Returns:
-
Index or MultiIndex–Snapshots of the network, either as a single index or a multi-index.
See Also
Notes
Note that Snapshots are a dimension, while timesteps and and periods are only levels of the snapshots dimension, similar to coords in xarray. This is because timesteps and periods are not necessarily unique or complete across snapshots.
Examples:
>>> n.snapshots
DatetimeIndex(['2015-01-01 00:00:00', '2015-01-01 01:00:00',
'2015-01-01 02:00:00', '2015-01-01 03:00:00',
...
dtype='datetime64[ns]', name='snapshot', freq=None)
- User Guide Core Design Design
pypsa.Network.timesteps
property
writable
¶
timesteps: Index
Timestep level of snapshots dimension.
If snapshots is single indexed, timesteps and snapshots yield the same result. Otherwise only the timestep level will be returned.
Returns:
-
Index–Timesteps of the network.
See Also
Examples:
>>> n = pypsa.Network()
>>> n.set_snapshots(pd.date_range("2015-01-01", freq="h", periods=3))
For a Network without investment periods, the timesteps are identical to the snapshots:
>>> n.timesteps
DatetimeIndex(['2015-01-01 00:00:00', '2015-01-01 01:00:00',
'2015-01-01 02:00:00'],
dtype='datetime64[ns]', name='snapshot', freq='h')
>>> n.snapshots
DatetimeIndex(['2015-01-01 00:00:00', '2015-01-01 01:00:00',
'2015-01-01 02:00:00'],
dtype='datetime64[ns]', name='snapshot', freq='h')
For a Network with investment periods, the timesteps are are the unqiue set of timesteps in across all investment periods:
>>> n.investment_periods = [1, 2]
>>> n.timesteps
DatetimeIndex(['2015-01-01 00:00:00', '2015-01-01 01:00:00',
'2015-01-01 02:00:00'],
dtype='datetime64[ns]', name='timestep', freq=None)
>>> n.snapshots
MultiIndex([(1, '2015-01-01 00:00:00'),
(1, '2015-01-01 01:00:00'),
(1, '2015-01-01 02:00:00'),
(2, '2015-01-01 00:00:00'),
(2, '2015-01-01 01:00:00'),
(2, '2015-01-01 02:00:00')],
name='snapshot')
pypsa.Network.periods
property
writable
¶
periods: Index
Periods level of snapshots dimension.
If snapshots is single indexed, periods will always be empty, since there no investment periods without timesteps are defined. Otherwise only the period level will be returned.
Returns:
-
Index–Periods of the network.
Examples:
>>> n = pypsa.Network()
>>> n.add("Bus", "bus")
>>> n.snapshots = pd.date_range("2015-01-01", freq="h", periods=3)
>>> n.snapshots
DatetimeIndex(['2015-01-01 00:00:00', '2015-01-01 01:00:00',
'2015-01-01 02:00:00'],
dtype='datetime64[ns]', name='snapshot', freq='h')
Add investment periods:
>>> n.periods = [1, 2]
>>> n.periods
Index([1, 2], dtype='int64', name='period')
Which will also cast snapshots to a MultiIndex:
>>> n.snapshots
MultiIndex([(1, '2015-01-01 00:00:00'),
(1, '2015-01-01 01:00:00'),
(1, '2015-01-01 02:00:00'),
(2, '2015-01-01 00:00:00'),
(2, '2015-01-01 01:00:00'),
(2, '2015-01-01 02:00:00')],
name='snapshot')
pypsa.Network.has_periods
property
¶
has_periods: bool
Check if network has investment periods assigned to snapshots dimension.
Returns:
-
bool–True if network has investment periods, otherwise False.
See Also
Examples:
>>> n = pypsa.Network()
>>> n.add("Bus", "bus")
>>> n.snapshots = pd.date_range("2015-01-01", freq="h", periods=3)
>>> n.has_periods
False
Add investment periods:
>>> n.periods = [1, 2]
>>> n.has_periods
True
pypsa.Network.investment_periods
property
writable
¶
investment_periods: Index
Periods level of snapshots dimension.
If snapshots is single indexed, periods will always be empty, since there no investment periods without timesteps are defined. Otherwise only the period level will be returned.
Note
Alias for pypsa.Network.periods.
Returns:
-
Index–Investment periods of the network.
Examples:
>>> n = pypsa.Network()
>>> n.add("Bus", "bus")
>>> n.snapshots = pd.date_range("2015-01-01", freq="h", periods=3)
>>> n.snapshots
DatetimeIndex(['2015-01-01 00:00:00', '2015-01-01 01:00:00',
'2015-01-01 02:00:00'],
dtype='datetime64[ns]', name='snapshot', freq='h')
Add investment periods:
>>> n.investment_periods = [1, 2]
>>> n.investment_periods
Index([1, 2], dtype='int64', name='period')
Which will also cast snapshots to a MultiIndex:
>>> n.snapshots
MultiIndex([(1, '2015-01-01 00:00:00'),
(1, '2015-01-01 01:00:00'),
(1, '2015-01-01 02:00:00'),
(2, '2015-01-01 00:00:00'),
(2, '2015-01-01 01:00:00'),
(2, '2015-01-01 02:00:00')],
name='snapshot')
- User Guide Core Design Design Investment Periods
pypsa.Network.has_investment_periods
property
¶
has_investment_periods: bool
Check if network has investment periods assigned to snapshots dimension.
Note
Alias for pypsa.Network.has_periods.
Returns:
-
bool–True if network has investment periods, otherwise False.
See Also
Examples:
>>> n = pypsa.Network()
>>> n.add("Bus", "bus")
>>> n.snapshots = pd.date_range("2015-01-01", freq="h", periods=3)
>>> n.has_investment_periods
False
Add investment periods:
>>> n.periods = [1, 2]
>>> n.has_investment_periods
True
pypsa.Network.snapshot_weightings
property
writable
¶
snapshot_weightings: DataFrame
Weightings applied to each snapshots during the optimization.
-
Objective weightings are factors on the operational cost in the objective function.
-
Store weightings define the elapsed hours for the charge, discharge standing loss and spillage of storage units and stores in order to determine the state of charge.
-
Generator weightings are factors for the contribution of generators to global constraints, e.g. emission limits, and energy balances.
Examples:
>>> n = pypsa.Network()
>>> n.add("Bus", "bus")
>>> n.snapshots = pd.date_range("2015-01-01", freq="h", periods=3)
>>> n.snapshot_weightings
objective stores generators
snapshot
2015-01-01 00:00:00 1.0 1.0 1.0
2015-01-01 01:00:00 1.0 1.0 1.0
2015-01-01 02:00:00 1.0 1.0 1.0
Change the snapshot weightings:
>>> n.snapshot_weightings.objective = [5, 7, 9]
>>> n.snapshot_weightings
objective stores generators
snapshot
2015-01-01 00:00:00 5 1.0 1.0
2015-01-01 01:00:00 7 1.0 1.0
2015-01-01 02:00:00 9 1.0 1.0
- User Guide Core Design Design Investment Periods
pypsa.Network.nyears
property
¶
nyears: float | Series
Return the modeled time horizon in years based on objective weightings.
Returns:
-
float | Series–The modeled time horizon in years. Returns a Series indexed by investment period when the network has investment periods.
Examples:
>>> import pypsa
>>> n = pypsa.Network()
>>> n.set_snapshots(range(24)) # 24 hourly snapshots
>>> n.nyears # 1/365
np.float64(0.00273...)
>>> n.snapshot_weightings.loc[:, :] = 365 # weight each hour as one day
>>> n.nyears
np.float64(1.0)
pypsa.Network.investment_period_weightings
property
writable
¶
investment_period_weightings: DataFrame
Weightings applied to each investment period during the optimization (LOPF).
Objective weightings are multiplied with all cost coefficients in the objective function of the respective investment period (e.g. to include a social discount rate). Years weightings denote the elapsed time until the subsequent investment period (e.g. used for global constraints CO2 emissions).
Examples:
Create a network with investment periods:
>>> n = pypsa.Network()
>>> n.add("Bus", "bus")
>>> n.snapshots = pd.date_range("2015-01-01", freq="h", periods=2)
>>> n.investment_periods = [1, 2]
>>> n.investment_period_weightings
objective years
period
1 1.0 1.0
2 1.0 1.0
Change the investment period weightings:
>>> n.investment_period_weightings.objective = [5, 7]
>>> n.investment_period_weightings.years = [1, 2]
>>> n.investment_period_weightings
objective years
period
1 5 1
2 7 2
- User Guide Core Design Design Investment Periods
pypsa.Network.scenarios
property
writable
¶
scenarios: Index
Get the scenarios index for the network.
Returns:
-
Index–The scenarios index for the network.
pypsa.Network.scenario_weightings
property
¶
scenario_weightings: DataFrame
Get the scenario weightings for the network.
Returns:
-
DataFrame–The scenario weightings as a DataFrame with 'weight' column.
pypsa.Network.has_scenarios
property
¶
has_scenarios: bool
Boolean indicating if the network has scenarios defined.
pypsa.Network.risk_preference
property
¶
risk_preference: dict[str, float] | None
Get the risk preference parameters for the network.
Returns:
-
dict[str, float] | None–Dictionary containing 'alpha' and 'omega' parameters if risk preferences are set, None otherwise.
pypsa.Network.has_risk_preference
property
¶
has_risk_preference: bool
Boolean indicating if the network has risk preferences defined.
pypsa.Network.is_collection
property
¶
is_collection: bool
Check if this is a collection of networks or a single network.
Returns:
-
bool–True, since this is a NetworkCollection.
See Also
pypsa.Network.set_snapshots
¶
set_snapshots(snapshots: Sequence, default_snapshot_weightings: float = 1.0, weightings_from_timedelta: bool = False) -> None
Set the snapshots/time steps and reindex all time-dependent data.
Snapshot weightings, typically representing the hourly length of each snapshot,
is filled with the default_snapshot_weighintgs value, or uses the timedelta
of the snapshots if weightings_from_timedelta flag is True, and snapshots are
of type pd.DatetimeIndex.
This will reindex all components time-dependent DataFrames
(pypsa.Network.dynamic). NaNs are filled with the default value for
that quantity.
Parameters:
-
snapshots((list, Index or MultiIndex)) –All time steps.
-
default_snapshot_weightings(float, default:1.0) –The default weight for each snapshot. Defaults to 1.0.
-
weightings_from_timedelta(bool, default:False) –Wheter to use the timedelta of
snapshotsassnapshot_weightingsifsnapshotsis of typepd.DatetimeIndex. Defaults to False.
Examples:
>>> n = pypsa.Network()
>>> n.set_snapshots(pd.date_range("2015-01-01", freq="h", periods=3))
>>> n.snapshots
DatetimeIndex(['2015-01-01 00:00:00', '2015-01-01 01:00:00',
'2015-01-01 02:00:00'],
dtype='datetime64[ns]', name='snapshot', freq='h')
pypsa.Network.set_investment_periods
¶
set_investment_periods(periods: Sequence) -> None
Set the investment periods of the network.
If the network snapshots are a pandas.MultiIndex, the investment periods have to be a subset of the first level. If snapshots are a single index, they and all time-series are repeated for all periods. This changes the network snapshots to be a MultiIndex (inplace operation) with the first level being the investment periods and the second level the snapshots.
Parameters:
-
periods(list) –List of periods to be selected/initialized.
Examples:
>>> n = pypsa.Network()
>>> n.set_snapshots(pd.date_range("2015-01-01", freq="h", periods=3))
>>> n.snapshots
DatetimeIndex(['2015-01-01 00:00:00', '2015-01-01 01:00:00',
'2015-01-01 02:00:00'],
dtype='datetime64[ns]', name='snapshot', freq='h')
>>> n.investment_periods = [1, 2]
>>> n.snapshots
MultiIndex([(1, '2015-01-01 00:00:00'),
(1, '2015-01-01 01:00:00'),
(1, '2015-01-01 02:00:00'),
(2, '2015-01-01 00:00:00'),
(2, '2015-01-01 01:00:00'),
(2, '2015-01-01 02:00:00')],
name='snapshot')
pypsa.Network.set_scenarios
¶
set_scenarios(scenarios: dict | Sequence | Series | DataFrame | None = None, **kwargs: Any) -> None
Set scenarios for the network to create a stochastic network.
Parameters:
-
scenarios((dict, Sequence, Series), default:None) –Scenarios to set for the network.
-
**kwargs(Any, default:{}) –Alternative way to set scenarios via keyword arguments. E.g.
n.set_scenarios(low=0.5, high=0.5).
pypsa.Network.set_risk_preference
¶
set_risk_preference(alpha: float, omega: float) -> None
Set risk aversion preferences for stochastic optimization using CVaR formulation.
Parameters:
-
alpha(float) –Confidence level in (0, 1). CVaR averages losses over the worst (1 - alpha) probability mass (the tail). For worst 10% tail, set alpha = 0.9 so that 1 - alpha = 0.1. Typical choices are alpha in {0.90, 0.95, 0.99}. Higher alpha focuses on rarer, more extreme tails; lower alpha considers a broader tail.
-
omega(float) –Risk preference parameter (risk aversion weight). Must be between 0 and 1. - omega = 0: Risk-neutral optimization - omega > 0: Risk-averse optimization (more focus on the tail risk) - omega = 1: Maximum risk aversion (optimize for the tail risk only) Higher values indicate more risk aversion.
Examples:
>>> n = pypsa.Network()
>>> n.set_scenarios({"low": 0.3, "medium": 0.4, "high": 0.3})
>>> n.set_risk_preference(alpha=0.95, omega=0.1) # 5% tail CVaR (1 - 0.05)
>>> n.risk_preference
{'alpha': 0.95, 'omega': 0.1}
Notes
This method must be called after set_scenarios() as CVaR formulation
requires stochastic scenarios to be defined. The CVaR formulation will
add auxiliary variables and constraints to the optimization model during
the model building phase.
pypsa.Network.get_scenario
¶
get_scenario(scenario: str) -> Network
Return a network for a single scenario from a stochastic network.
Parameters:
-
scenario(str) –Name of the scenario to extract.
Returns:
-
n(Network) –A new network instance containing only the selected scenario.
Examples:
>>> n_stochastic
Stochastic PyPSA Network 'Stochastic-Network'
---------------------------------------------
Components:
- Bus: 3
- Carrier: 18
- Generator: 12
- Load: 3
Snapshots: 2920
Scenarios: 3
>>> n_high = n_stochastic.get_scenario("high")
>>> n_high
PyPSA Network 'Stochastic-Network - Scenario 'high''
----------------------------------------------------
Components:
- Bus: 1
- Carrier: 6
- Generator: 4
- Load: 1
Snapshots: 2920
pypsa.Network.get_network
¶
get_network(collection: str) -> None | Network
Return a single network from a NetworkCollection.
Parameters:
-
collection(str) –Name of the network to be selected from the collection.
Returns:
-
n(Network) –Reference to the selected network from the collection.
Examples:
>>> nc
NetworkCollection
-----------------
Networks: 2
Index name: 'network'
Entries: ['AC-DC-Meshed', 'AC-DC-Meshed-Shuffled-Load']
>>> selected = nc.get_network("AC-DC-Meshed")
>>> selected
PyPSA Network 'AC-DC-Meshed'
----------------------------
Components:
- Bus: 9
- Carrier: 6
- Generator: 6
- GlobalConstraint: 1
- Line: 7
- Link: 4
- Load: 6
- SubNetwork: 3
Snapshots: 10
A network collection does not copy the selected network, but returns a reference to it:
>>> n1 = pypsa.Network(name="Network1")
>>> n2 = pypsa.Network(name="Network2")
>>> nc = pypsa.NetworkCollection([n1, n2])
>>> nc.get_network("Network1") is n1
True
pypsa.Network.slice_network
¶
slice_network(buses: str | Sequence[str] | Index | slice | None = None, snapshots: int | Sequence | Index | slice | None = None) -> Network
Return a sliced copy of the network.
Parameters:
-
buses(slice, list, or str, or tuple, default:None) –Used to slice a network by buses. Any valid indexer for pandas.DataFrame.loc is allowed (refer to pandas.DataFrame.loc).
-
snapshots(int, slice, list or boolean array, default:None) –Used to slice a network by snapshots. Any valid indexer for pandas.Index is allowed (refer to pandas.Index.getitem). If None, all snapshots are used.
Returns:
-
n(Network) –A new network instance containing only the selected buses with attached components and/or the selected snapshots.
Examples:
Slice network to a single bus and its connected components:
>>> n_manchester = n.slice_network(buses="Manchester")
>>> n_manchester
PyPSA Network 'AC-DC-Meshed'
----------------------------
Components:
- Bus: 1
- Carrier: 6
- Generator: 2
- GlobalConstraint: 1
- Load: 1
Snapshots: 10
>>> n_manchester.buses.index.tolist()
['Manchester']
Slice network to multiple buses:
>>> n_subset = n.slice_network(buses=["Manchester", "Frankfurt"])
>>> n_subset
PyPSA Network 'AC-DC-Meshed'
----------------------------
Components:
- Bus: 2
- Carrier: 6
- Generator: 4
- GlobalConstraint: 1
- Load: 2
Snapshots: 10
>>> sorted(n_subset.buses.index.tolist())
['Frankfurt', 'Manchester']
Slice network by DC carrier:
>>> n_hv = n.slice_network(buses=n.buses.carrier == "DC")
>>> n_hv
PyPSA Network 'AC-DC-Meshed'
----------------------------
Components:
- Bus: 3
- Carrier: 6
- GlobalConstraint: 1
- Line: 3
Snapshots: 10
Slice network to first 3 snapshots:
>>> n_snap = n.slice_network(snapshots=slice(None, 3))
>>> n_snap
PyPSA Network 'AC-DC-Meshed'
----------------------------
Components:
- Bus: 9
- Carrier: 6
- Generator: 6
- GlobalConstraint: 1
- Line: 7
- Link: 4
- Load: 6
Snapshots: 3
Slice both buses and snapshots:
>>> n_both = n.slice_network(buses="Manchester", snapshots=slice(None, 2))
>>> n_both
PyPSA Network 'AC-DC-Meshed'
----------------------------
Components:
- Bus: 1
- Carrier: 6
- Generator: 2
- GlobalConstraint: 1
- Load: 1
Snapshots: 2