Network container for all buses, one-ports and branches.
Parameters:
import_name (string, Path) – Path to netCDF file, HDF5 .h5 store or folder of CSV files from which to
import network data. The string could be a URL.
name (string, default "") – Network name.
ignore_standard_types (boolean, default False) – If True, do not read in PyPSA standard types into standard types
DataFrames.
override_components (pandas.DataFrame) – If you want to override the standard PyPSA components in
pypsa.components.components, pass it a DataFrame with index of component
name and columns of list_name and description, following the format of
pypsa.components.components. See git repository examples/new_components/.
override_component_attrs (pypsa.descriptors.Dict of pandas.DataFrame) – If you want to override pypsa.component_attrs, follow its format.
See git repository examples/new_components/.
branch_components (iterable sublist of branch_components) – Buses connected by any of the selected branches are adjacent
(default: branch_components (network) or passive_branch_components (sub_network))
busorder (pd.Index subset of network.buses.index) – Basis to use for the matrix representation of the adjacency matrix
(default: buses.index (network) or buses_i() (sub_network))
weights (pd.Series or None (default)) – If given must provide a weight for each branch, multi-indexed
on branch_component name and branch name.
For the default case investment_period=None, it is not taken
into account whether the branch components are active (based on
build_year and lifetime). If the investment_period is specified,
the network topology is determined on the basis of the active
branches.
export_standard_types (boolean, default False) – If True, then standard types are exported too (upon reimporting you
should then set “ignore_standard_types” when initialising the network).
Both static and series attributes of components are exported, but only
if they have non-default values.
If path does not already exist, it is created.
Parameters:
path (string) – Name of hdf5 file to which to export (if it exists, it is overwritten)
export_standard_types (boolean, default False) – If True, then standard types are exported too (upon reimporting you
should then set “ignore_standard_types” when initialising the network).
**kwargs – Extra arguments for pd.HDFStore to specify f.i. compression
(default: complevel=4)
Both static and series attributes of components are exported, but only
if they have non-default values.
If path does not already exist, it is created.
If no path is passed, no file is exported, but the xarray.Dataset
is still returned.
Be aware that this cannot export boolean attributes on the Network
class, e.g. network.my_bool = False is not supported by netCDF.
Parameters:
path (string|None) – Name of netCDF file to which to export (if it exists, it is overwritten);
if None is passed, no file is exported.
export_standard_types (boolean, default False) – If True, then standard types are exported too (upon reimporting you
should then set “ignore_standard_types” when initialising the network).
compression (dict|None) – Compression level to use for all features which are being prepared.
The compression is handled via xarray.Dataset.to_netcdf(…). For details see:
https://docs.xarray.dev/en/stable/generated/xarray.Dataset.to_netcdf.html
An example compression directive is {'zlib':True,'complevel':4}.
The default is None which disables compression.
float32 (boolean, default False) – If True, typecasts values to float32.
Return a Dataframe for a time-varying component attribute with values for
all non-time-varying components filled in with the default values for the
attribute.
branch_components ([str]) – Components to use as branches. The default are
passive_branch_components in the case of a SubNetwork and
branch_components in the case of a Network.
inf_weight (bool|float) – How to treat infinite weights (default: False). True keeps the infinite
weight. False skips edges with infinite weight. If a float is given it
is used instead.
Importing from pandapower is still in beta;
not all pandapower components are supported.
Unsupported features include:
- three-winding transformers
- switches
- in_service status and
- tap positions of transformers
Parameters:
net (pandapower network) –
extra_line_data (boolean, default: False) – if True, the line data for all parameters is imported instead of only the type
use_pandapower_index (boolean, default: False) – if True, use integer numbers which is the pandapower index standard
if False, use any net.name as index (e.g. ‘Bus 1’ (str) or 1 (int))
branch_components (iterable sublist of branch_components) – Buses connected by any of the selected branches are adjacent
(default: branch_components (network) or passive_branch_components (sub_network))
busorder (pd.Index subset of network.buses.index) – Basis to use for the matrix representation of the adjacency matrix
(default: buses.index (network) or buses_i() (sub_network))
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).
Plot the network buses and lines interactively using plotly.
Parameters:
fig (dict, default None) – If not None, figure is built upon this fig.
bus_colors (dict/pandas.Series) – Colors for the buses, defaults to “cadetblue”. If bus_sizes is a
pandas.Series with a Multiindex, bus_colors defaults to the
n.carriers[‘color’] column.
bus_alpha (float) – Adds alpha channel to buses, defaults to 1.
bus_sizes (float/pandas.Series) – Sizes of bus points, defaults to 10.
bus_cmap (plt.cm.ColorMap/str) – If bus_colors are floats, this color map will assign the colors
bus_colorbar (dict) – Plotly colorbar, e.g. {‘title’ : ‘my colorbar’}
bus_text (pandas.Series) – Text for each bus, defaults to bus names
line_colors (str/pandas.Series) – Colors for the lines, defaults to ‘rosybrown’.
link_colors (str/pandas.Series) – Colors for the links, defaults to ‘darkseagreen’.
transfomer_colors (str/pandas.Series) – Colors for the transfomer, defaults to ‘orange’.
line_widths (dict/pandas.Series) – Widths of lines, defaults to 1.5
link_widths (dict/pandas.Series) – Widths of links, defaults to 1.5
transformer_widths (dict/pandas.Series) – Widths of transformer, defaults to 1.5
line_text (pandas.Series) – Text for lines, defaults to line names.
link_text (pandas.Series) – Text for links, defaults to link names.
tranformer_text (pandas.Series) – Text for transformers, defaults to transformer names.
layouter (networkx.drawing.layout function, default None) – Layouting function from networkx which
overrules coordinates given in n.buses[['x','y']]. See
list
of available options.
title (string) – Graph title
size (None|tuple) – Tuple specifying width and height of figure; e.g. (width, heigh).
branch_components (list of str) – Branch components to be plotted, defaults to Line and Link.
iplot (bool, default True) – Automatically do an interactive plot of the figure.
jitter (None|float) – Amount of random noise to add to bus positions to distinguish
overlapping buses
mapbox (bool, default False) – Switch to use Mapbox.
Define the mapbox layout style of the interactive plot. If this is set
to a mapbox layout, the argument mapbox_token must be a valid Mapbox
API access token.
mapbox_token (string) – Mapbox API access token. Obtain from https://www.mapbox.com.
Can also be included in mapbox_parameters as accesstoken=mapbox_token.
mapbox_parameters (dict) – Configuration parameters of the Mapbox layout.
E.g. {“bearing”: 5, “pitch”: 10, “zoom”: 1, “style”: ‘dark’}.
Computes linear power flow for a selection of branch outages.
Parameters:
snapshots (list-like|single snapshot) – A subset or an elements of network.snapshots on which to run
the power flow, defaults to network.snapshots
NB: currently this only works for a single snapshot
branch_outages (list-like) – A list of passive branches which are to be tested for outages.
If None, it’s take as all network.passive_branches_i()
Returns:
p0 – num_passive_branch x num_branch_outages DataFrame of new power flows
Add multiple components to the network, along with their attributes.
Make sure when adding static attributes as pandas Series that they are indexed
by names. Make sure when adding time-varying attributes as pandas DataFrames that
their index is a superset of network.snapshots and their columns are a
subset of names.
Any attributes which are not specified will be given the default
value from Components.
Parameters:
class_name (string) – Component class name in (“Bus”, “Generator”, “Load”, “StorageUnit”,
“Store”, “ShuntImpedance”, “Line”, “Transformer”, “Link”).
names (list-like or pandas.Index) – Component names
suffix (string, default '') – All components are named after names with this added suffix. It
is assumed that all Series and DataFrames are indexed by the original names.
kwargs – Component attributes, e.g. x=[0.1, 0.2], can be list, pandas.Series
of pandas.DataFrame for time-varying
Returns:
new_names – Names of new components (including suffix)
snapshots (list-like|single snapshot) – A subset or an elements of network.snapshots on which to run
the power flow, defaults to network.snapshots
skip_pre (bool, default False) – Skip the preliminary steps of computing topology, calculating dependent values and finding bus controls.
x_tol (float) – Tolerance for Newton-Raphson power flow.
use_seed (bool, default False) – Use a seed for the initial guess for the Newton-Raphson algorithm.
distribute_slack (bool, default False) – If True, distribute the slack power across generators proportional to generator dispatch by default
or according to the distribution scheme provided in slack_weights.
If False only the slack generator takes up the slack.
slack_weights (dict|str, default 'p_set') – Distribution scheme describing how to determine the fraction of the total slack power
(of each sub network individually) a bus of the subnetwork takes up.
Default is to distribute proportional to generator dispatch (‘p_set’).
Another option is to distribute proportional to (optimised) nominal capacity (‘p_nom’ or ‘p_nom_opt’).
Custom weights can be specified via a dictionary that has a key for each
subnetwork index (network.sub_networks.index) and a
pandas.Series/dict with buses or generators of the
corresponding subnetwork as index/keys.
When specifying custom weights with buses as index/keys the slack power of a bus is distributed
among its generators in proportion to their nominal capacity (p_nom) if given, otherwise evenly.
Returns:
Dictionary with keys ‘n_iter’, ‘converged’, ‘error’ and dataframe
values indicating number of iterations, convergence status, and
iteration error for each snapshot (rows) and sub_network (columns)
Plot the network buses and lines using matplotlib and cartopy.
Parameters:
margin (float, defaults to 0.05) – Margin at the sides as proportion of distance between max/min x, y
Will be ignored if boundaries are given.
ax (matplotlib ax, defaults to plt.gca()) – Axis to which to plot the network
geomap (bool/str, default True) – Switch to use Cartopy and draw geographical features.
If string is passed, it will be used as a resolution argument,
valid options are ‘10m’, ‘50m’ and ‘110m’.
projection (cartopy.crs.Projection, defaults to None) – Define the projection of your geomap, only valid if cartopy is
installed. If None (default) is passed the projection for cartopy
is set to cartopy.crs.PlateCarree
bus_colors (dict/pandas.Series) – Colors for the buses, defaults to “cadetblue”. If bus_sizes is a
pandas.Series with a Multiindex, bus_colors defaults to the
n.carriers[‘color’] column.
bus_alpha (float) – Adds alpha channel to buses, defaults to 1.
bus_sizes (dict/pandas.Series) – Sizes of bus points, defaults to 1e-2. If a multiindexed Series is passed,
the function will draw pies for each bus (first index level) with
segments of different color (second index level). Such a Series is ob-
tained by e.g. n.generators.groupby([‘bus’, ‘carrier’]).p_nom.sum()
bus_cmap (plt.cm.ColorMap/str) – If bus_colors are floats, this color map will assign the colors
bus_norm (plt.Normalize|matplotlib.colors.*Norm) – The norm applied to the bus_cmap.
bus_split_circles (bool, default False) – Draw half circles if bus_sizes is a pandas.Series with a Multiindex.
If set to true, the upper half circle per bus then includes all positive values
of the series, the lower half circle all negative values. Defaults to False.
line_colors (str/pandas.Series) – Colors for the lines, defaults to ‘rosybrown’.
link_colors (str/pandas.Series) – Colors for the links, defaults to ‘darkseagreen’.
transfomer_colors (str/pandas.Series) – Colors for the transfomer, defaults to ‘orange’.
line_alpha (str/pandas.Series) – Alpha for the lines, defaults to 1.
link_alpha (str/pandas.Series) – Alpha for the links, defaults to 1.
transfomer_alpha (str/pandas.Series) – Alpha for the transfomer, defaults to 1.
line_widths (dict/pandas.Series) – Widths of lines, defaults to 1.5
link_widths (dict/pandas.Series) – Widths of links, defaults to 1.5
transformer_widths (dict/pandas.Series) – Widths of transformer, defaults to 1.5
line_cmap (plt.cm.ColorMap/str|dict) – If line_colors are floats, this color map will assign the colors.
link_cmap (plt.cm.ColorMap/str|dict) – If link_colors are floats, this color map will assign the colors.
transformer_cmap (plt.cm.ColorMap/str|dict) – If transformer_colors are floats, this color map will assign the colors.
line_norm (plt.Normalize|matplotlib.colors.*Norm) – The norm applied to the line_cmap.
link_norm (plt.Normalize|matplotlib.colors.*Norm) – The norm applied to the link_cmap.
transformer_norm (matplotlib.colors.Normalize|matplotlib.colors.*Norm) – The norm applied to the transformer_cmap.
flow (snapshot/pandas.Series/function/string) – Flow to be displayed in the plot, defaults to None. If an element of
n.snapshots is given, the flow at this timestamp will be
displayed. If an aggregation function is given, is will be applied
to the total network flow via pandas.DataFrame.agg (accepts also
function names). Otherwise flows can be specified by passing a pandas
Series with MultiIndex including all necessary branch components.
Use the line_widths argument to additionally adjust the size of the
flow arrows.
Layouting function from networkx which
overrules coordinates given in n.buses[['x','y']]. See
list
of available options.
title (string) – Graph title
boundaries (list of four floats) – Boundaries of the plot in format [x1, x2, y1, y2]
branch_components (list of str) – Branch components to be plotted, defaults to Line and Link.
jitter (None|float) – Amount of random noise to add to bus positions to distinguish
overlapping buses
color_geomap (dict or bool) – Specify colors to paint land and sea areas in.
If True, it defaults to {‘ocean’: ‘lightblue’, ‘land’: ‘whitesmoke’}.
If no dictionary is provided, colors are white.
If False, no geographical features are plotted.
Returns:
bus_collection, branch_collection1, … – Collections for buses and branches.
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.
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 (:role:`Network.pnl`); NaNs are filled
with the default value for that quantity.
Parameters:
snapshots (list, pandas.Index, pd.MultiIndex or pd.DatetimeIndex) – All time steps.
default_snapshot_weightings (float) – The default weight for each snapshot. Defaults to 1.0.
weightings_from_timedelta (bool) – Wheter to use the timedelta of snapshots as snapshot_weightings if snapshots is of type pd.DatetimeIndex. Defaults to False.
Weightings applied to each snapshots during the optimization (LOPF).
Objective weightings multiply the operational cost in the
objective function.
Generator weightings multiply the impact of all generators
in global constraints, e.g. multiplier of GHG emmissions.
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.
branch_components (iterable sublist of branch_components) – Buses connected by any of the selected branches are adjacent
(default: branch_components (network) or passive_branch_components (sub_network))
busorder (pd.Index subset of network.buses.index) – Basis to use for the matrix representation of the adjacency matrix
(default: buses.index (network) or buses_i() (sub_network))
weights (pd.Series or None (default)) – If given must provide a weight for each branch, multi-indexed
on branch_component name and branch name.
skip_pre (bool, default False) – Skip the preliminary steps of computing topology, calculating dependent values,
finding bus controls and computing B and H.
branch_components ([str]) – Components to use as branches. The default are
passive_branch_components in the case of a SubNetwork and
branch_components in the case of a Network.
inf_weight (bool|float) – How to treat infinite weights (default: False). True keeps the infinite
weight. False skips edges with infinite weight. If a float is given it
is used instead.
branch_components (iterable sublist of branch_components) – Buses connected by any of the selected branches are adjacent
(default: branch_components (network) or passive_branch_components (sub_network))
busorder (pd.Index subset of network.buses.index) – Basis to use for the matrix representation of the adjacency matrix
(default: buses.index (network) or buses_i() (sub_network))
snapshots (list-like|single snapshot) – A subset or an elements of network.snapshots on which to run
the power flow, defaults to network.snapshots
skip_pre (bool, default False) – Skip the preliminary steps of computing topology, calculating dependent values and finding bus controls.
x_tol (float) – Tolerance for Newton-Raphson power flow.
use_seed (bool, default False) – Use a seed for the initial guess for the Newton-Raphson algorithm.
distribute_slack (bool, default False) – If True, distribute the slack power across generators proportional to generator dispatch by default
or according to the distribution scheme provided in slack_weights.
If False only the slack generator takes up the slack.
slack_weights (pandas.Series|str, default 'p_set') – Distribution scheme describing how to determine the fraction of the total slack power
a bus of the subnetwork takes up. Default is to distribute proportional to generator dispatch
(‘p_set’). Another option is to distribute proportional to (optimised) nominal capacity (‘p_nom’ or ‘p_nom_opt’).
Custom weights can be provided via a pandas.Series/dict
that has the buses or the generators of the subnetwork as index/keys.
When using custom weights with buses as index/keys the slack power of a bus is distributed
among its generators in proportion to their nominal capacity (p_nom) if given, otherwise evenly.
Returns:
Tuple of three pandas.Series indicating number of iterations,
remaining error, and convergence status for each snapshot
Get a boolean array with True values for elements of component c
which are active at a specific snapshot. If the network is in
multi_investment_period mode (given by n._multi_invest), these are
calculated from lifetime and the build year. Otherwise all values
are set to True.
Getter function to retrieve the per unit bounds of a given compoent for
given snapshots and possible subset of elements (e.g. non-extendables).
Depending on the attr you can further specify the bounds of the variable
you are looking at, e.g. p_store for storage units.
Return a Dataframe for a time-varying component attribute with values for
all non-time-varying components filled in with the default values for the
attribute.
Return an iterator over snapshots for a time-varying component attribute
with values for all non-time-varying components filled in with the default
values for the attribute.
export_standard_types (boolean, default False) – If True, then standard types are exported too (upon reimporting you
should then set “ignore_standard_types” when initialising the network).
Both static and series attributes of components are exported, but only
if they have non-default values.
If path does not already exist, it is created.
Parameters:
path (string) – Name of hdf5 file to which to export (if it exists, it is overwritten)
export_standard_types (boolean, default False) – If True, then standard types are exported too (upon reimporting you
should then set “ignore_standard_types” when initialising the network).
**kwargs – Extra arguments for pd.HDFStore to specify f.i. compression
(default: complevel=4)
Both static and series attributes of components are exported, but only
if they have non-default values.
If path does not already exist, it is created.
If no path is passed, no file is exported, but the xarray.Dataset
is still returned.
Be aware that this cannot export boolean attributes on the Network
class, e.g. network.my_bool = False is not supported by netCDF.
Parameters:
path (string|None) – Name of netCDF file to which to export (if it exists, it is overwritten);
if None is passed, no file is exported.
export_standard_types (boolean, default False) – If True, then standard types are exported too (upon reimporting you
should then set “ignore_standard_types” when initialising the network).
compression (dict|None) – Compression level to use for all features which are being prepared.
The compression is handled via xarray.Dataset.to_netcdf(…). For details see:
https://docs.xarray.dev/en/stable/generated/xarray.Dataset.to_netcdf.html
An example compression directive is {'zlib':True,'complevel':4}.
The default is None which disables compression.
float32 (boolean, default False) – If True, typecasts values to float32.
Importing from pandapower is still in beta;
not all pandapower components are supported.
Unsupported features include:
- three-winding transformers
- switches
- in_service status and
- tap positions of transformers
Parameters:
net (pandapower network) –
extra_line_data (boolean, default: False) – if True, the line data for all parameters is imported instead of only the type
use_pandapower_index (boolean, default: False) – if True, use integer numbers which is the pandapower index standard
if False, use any net.name as index (e.g. ‘Bus 1’ (str) or 1 (int))
branch_components (iterable sublist of branch_components) – Buses connected by any of the selected branches are adjacent
(default: branch_components (network) or passive_branch_components (sub_network))
busorder (pd.Index subset of network.buses.index) – Basis to use for the matrix representation of the adjacency matrix
(default: buses.index (network) or buses_i() (sub_network))
weights (pd.Series or None (default)) – If given must provide a weight for each branch, multi-indexed
on branch_component name and branch name.
branch_components ([str]) – Components to use as branches. The default are
passive_branch_components in the case of a SubNetwork and
branch_components in the case of a Network.
inf_weight (bool|float) – How to treat infinite weights (default: False). True keeps the infinite
weight. False skips edges with infinite weight. If a float is given it
is used instead.
branch_components (iterable sublist of branch_components) – Buses connected by any of the selected branches are adjacent
(default: branch_components (network) or passive_branch_components (sub_network))
busorder (pd.Index subset of network.buses.index) – Basis to use for the matrix representation of the adjacency matrix
(default: buses.index (network) or buses_i() (sub_network))
skip_pre (bool, default False) – Skip the preliminary steps of computing topology, calculating dependent values,
finding bus controls and computing B and H.
Find all cycles in the sub_network and record them in sub_network.C.
networkx collects the cycles with more than 2 edges; then the 2-edge
cycles from the MultiGraph must be collected separately (for cases
where there are multiple lines between the same pairs of buses).
Get the spanning tree of the graph, choose the node with the highest degree
as a central “tree slack” and then see for each branch which paths from the
slack to each node go through the branch.
snapshots (list-like|single snapshot) – A subset or an elements of network.snapshots on which to run
the power flow, defaults to network.snapshots
skip_pre (bool, default False) – Skip the preliminary steps of computing topology, calculating dependent values and finding bus controls.
x_tol (float) – Tolerance for Newton-Raphson power flow.
use_seed (bool, default False) – Use a seed for the initial guess for the Newton-Raphson algorithm.
distribute_slack (bool, default False) – If True, distribute the slack power across generators proportional to generator dispatch by default
or according to the distribution scheme provided in slack_weights.
If False only the slack generator takes up the slack.
slack_weights (dict|str, default 'p_set') – Distribution scheme describing how to determine the fraction of the total slack power
(of each sub network individually) a bus of the subnetwork takes up.
Default is to distribute proportional to generator dispatch (‘p_set’).
Another option is to distribute proportional to (optimised) nominal capacity (‘p_nom’ or ‘p_nom_opt’).
Custom weights can be specified via a dictionary that has a key for each
subnetwork index (network.sub_networks.index) and a
pandas.Series/dict with buses or generators of the
corresponding subnetwork as index/keys.
When specifying custom weights with buses as index/keys the slack power of a bus is distributed
among its generators in proportion to their nominal capacity (p_nom) if given, otherwise evenly.
Returns:
Dictionary with keys ‘n_iter’, ‘converged’, ‘error’ and dataframe
values indicating number of iterations, convergence status, and
iteration error for each snapshot (rows) and sub_network (columns)
snapshots (list-like|single snapshot) – A subset or an elements of network.snapshots on which to run
the power flow, defaults to network.snapshots
skip_pre (bool, default False) – Skip the preliminary steps of computing topology, calculating dependent values and finding bus controls.
x_tol (float) – Tolerance for Newton-Raphson power flow.
use_seed (bool, default False) – Use a seed for the initial guess for the Newton-Raphson algorithm.
distribute_slack (bool, default False) – If True, distribute the slack power across generators proportional to generator dispatch by default
or according to the distribution scheme provided in slack_weights.
If False only the slack generator takes up the slack.
slack_weights (pandas.Series|str, default 'p_set') – Distribution scheme describing how to determine the fraction of the total slack power
a bus of the subnetwork takes up. Default is to distribute proportional to generator dispatch
(‘p_set’). Another option is to distribute proportional to (optimised) nominal capacity (‘p_nom’ or ‘p_nom_opt’).
Custom weights can be provided via a pandas.Series/dict
that has the buses or the generators of the subnetwork as index/keys.
When using custom weights with buses as index/keys the slack power of a bus is distributed
among its generators in proportion to their nominal capacity (p_nom) if given, otherwise evenly.
Returns:
Tuple of three pandas.Series indicating number of iterations,
remaining error, and convergence status for each snapshot
Non-linear power flow for a sub-network consiting of a single bus.
Parameters:
snapshots (list-like|single snapshot) – A subset or an elements of network.snapshots on which to run
the power flow, defaults to network.snapshots
skip_pre (bool, default False) – Skip the preliminary steps of computing topology, calculating dependent values and finding bus controls.
distribute_slack (bool, default False) – If True, distribute the slack power across generators proportional to generator dispatch by default
or according to the distribution scheme provided in slack_weights.
If False only the slack generator takes up the slack.
slack_weights (pandas.Series|str, default 'p_set') – Distribution scheme describing how to determine the fraction of the total slack power
a bus of the subnetwork takes up. Default is to distribute proportional to generator dispatch
(‘p_set’). Another option is to distribute proportional to (optimised) nominal capacity (‘p_nom’ or ‘p_nom_opt’).
Custom weights can be provided via a pandas.Series/dict
that has the generators of the single bus as index/keys.
Run modelling-to-generate-alternatives (MGA) on network to find near-
optimal solutions.
Parameters:
n (pypsa.Network snapshots : list-like) – Set of snapshots to consider in the optimization. The default is None.
multi_investment_periods (bool, default False) – Whether to optimise as a single investment period or to optimize in
multiple investment periods. Then, snapshots should be a
pd.MultiIndex.
weights (dict-like) –
Weights for alternate objective function. The default is None, which
minimizes generation capacity. The weights dictionary should be keyed
with the component and variable (see pypsa/variables.csv), followed
by a float, dict, pd.Series or pd.DataFrame for the coefficients of the
objective function. Examples:
snapshots (list-like, optional) – Set of snapshots to consider in the optimization. The default is None.
branch_outages (list-like/pandas.Index/pandas.MultiIndex, optional) – Subset of passive branches to consider as possible outages. If a list
or a pandas.Index is passed, it is assumed to identify lines. If a
multiindex is passed, its first level has to contain the component names,
the second the assets. The default None results in all passive branches
to be considered.
multi_investment_periods (bool, default False) – Whether to optimise as a single investment period or to optimise in multiple
investment periods. Then, snapshots should be a pd.MultiIndex.
model_kwargs (dict) – Keyword arguments used by linopy.Model, such as solver_dir or chunk.
**kwargs – Keyword argument used by linopy.Model.solve, such as solver_name,
problem_fn or solver options directly passed to the solver.
Iterative linear optimization updating the line parameters for passive AC
and DC lines. This is helpful when line expansion is enabled. After each
successful solving, line impedances and line resistance are recalculated
based on the optimization result. If warmstart is possible, it uses the
result from the previous iteration to fasten the optimization.
Parameters:
snapshots (list or index slice) – A list of snapshots to optimise, must be a subset of
network.snapshots, defaults to network.snapshots
msq_threshold (float, default 0.05) – Maximal mean square difference between optimized line capacity of
the current and the previous iteration. As soon as this threshold is
undercut, and the number of iterations is bigger than ‘min_iterations’
the iterative optimization stops
min_iterations (integer, default 1) – Minimal number of iteration to run regardless whether the msq_threshold
is already undercut
max_iterations (integer, default 100) – Maximal number of iterations to run regardless whether msq_threshold
is already undercut
track_iterations (bool, default False) – If True, the intermediate branch capacities and values of the
objective function are recorded for each iteration. The values of
iteration 0 represent the initial state.
line_unit_size (float, default None) – The unit size for line components.
Use None if no discretization is desired.
link_unit_size (dict-like, default None) – A dictionary containing the unit sizes for link components,
with carrier names as keys. Use None if no discretization is desired.
line_threshold (float, default 0.3) – The threshold relative to the unit size for discretizing line components.
link_threshold (float, default 0.3) – The threshold relative to the unit size for discretizing link components.
**kwargs – Keyword arguments of the n.optimize function which runs at each iteration
Sets constraints for fixing modular variables of a given component. It
allows to define optimal capacity of a component as multiple of the nominal
capacity of the single module.
Sets power dispatch constraints for committable devices for a given
component and a given attribute. The linearized approximation of the unit
commitment problem is inspired by Hua et al. (2017) DOI:
10.1109/TPWRS.2017.2735026.
Set an capacity expansion limit for assets of the same carrier at the same
bus (e.g. ‘onwind’ at bus ‘1’). The function searches for columns in the
buses dataframe matching the pattern “nom_{min/max}_{carrier}”. In case
the constraint should only be defined for one investment period, the column
name can be constructed according to “nom_{min/max}_{carrier}_{period}”
where period must be in n.investment_periods.
buses (pandas.Index, optional) – Subset of buses where load shedding should be available.
Defaults to all buses.
sign (float/Series, optional) – Scaling of the load shedding. This is used to scale the price of the
load shedding. The default is 1e-3 which translates to a measure in kW instead
of MW.
marginal_cost (float/Series, optional) – Price of the load shedding. The default is 1e2.
p_nom (float/Series, optional) – Maximal load shedding. The default is 1e9 (kW).
snapshots (list or index slice) – A list of snapshots to optimise, must be a subset of
network.snapshots, defaults to network.snapshots
multi_investment_periods (bool, default False) – Whether to optimise as a single investment period or to optimize in multiple
investment periods. Then, snapshots should be a pd.MultiIndex.
Run modelling-to-generate-alternatives (MGA) on network to find near-
optimal solutions.
Parameters:
n (pypsa.Network snapshots : list-like) – Set of snapshots to consider in the optimization. The default is None.
multi_investment_periods (bool, default False) – Whether to optimise as a single investment period or to optimize in
multiple investment periods. Then, snapshots should be a
pd.MultiIndex.
weights (dict-like) –
Weights for alternate objective function. The default is None, which
minimizes generation capacity. The weights dictionary should be keyed
with the component and variable (see pypsa/variables.csv), followed
by a float, dict, pd.Series or pd.DataFrame for the coefficients of the
objective function. Examples:
snapshots (list-like, optional) – Set of snapshots to consider in the optimization. The default is None.
branch_outages (list-like/pandas.Index/pandas.MultiIndex, optional) – Subset of passive branches to consider as possible outages. If a list
or a pandas.Index is passed, it is assumed to identify lines. If a
multiindex is passed, its first level has to contain the component names,
the second the assets. The default None results in all passive branches
to be considered.
multi_investment_periods (bool, default False) – Whether to optimise as a single investment period or to optimise in multiple
investment periods. Then, snapshots should be a pd.MultiIndex.
model_kwargs (dict) – Keyword arguments used by linopy.Model, such as solver_dir or chunk.
**kwargs – Keyword argument used by linopy.Model.solve, such as solver_name,
problem_fn or solver options directly passed to the solver.
Iterative linear optimization updating the line parameters for passive AC
and DC lines. This is helpful when line expansion is enabled. After each
successful solving, line impedances and line resistance are recalculated
based on the optimization result. If warmstart is possible, it uses the
result from the previous iteration to fasten the optimization.
Parameters:
snapshots (list or index slice) – A list of snapshots to optimise, must be a subset of
network.snapshots, defaults to network.snapshots
msq_threshold (float, default 0.05) – Maximal mean square difference between optimized line capacity of
the current and the previous iteration. As soon as this threshold is
undercut, and the number of iterations is bigger than ‘min_iterations’
the iterative optimization stops
min_iterations (integer, default 1) – Minimal number of iteration to run regardless whether the msq_threshold
is already undercut
max_iterations (integer, default 100) – Maximal number of iterations to run regardless whether msq_threshold
is already undercut
track_iterations (bool, default False) – If True, the intermediate branch capacities and values of the
objective function are recorded for each iteration. The values of
iteration 0 represent the initial state.
line_unit_size (float, default None) – The unit size for line components.
Use None if no discretization is desired.
link_unit_size (dict-like, default None) – A dictionary containing the unit sizes for link components,
with carrier names as keys. Use None if no discretization is desired.
line_threshold (float, default 0.3) – The threshold relative to the unit size for discretizing line components.
link_threshold (float, default 0.3) – The threshold relative to the unit size for discretizing link components.
**kwargs – Keyword arguments of the n.optimize function which runs at each iteration
snapshots (list or index slice) – A list of snapshots to optimise, must be a subset of
network.snapshots, defaults to network.snapshots
multi_investment_periods (bool, default False) – Whether to optimise as a single investment period or to optimize in multiple
investment periods. Then, snapshots should be a pd.MultiIndex.
snapshots (list or index slice) – A list of snapshots to optimise, must be a subset of
n.snapshots, defaults to n.snapshots
multi_investment_periods (bool, default False) – Whether to optimise as a single investment period or to optimise in multiple
investment periods. Then, snapshots should be a pd.MultiIndex.
transmission_losses (int, default 0) – Whether an approximation of transmission losses should be included
in the linearised power flow formulation. A passed number will denote
the number of tangents used for the piecewise linear approximation.
Defaults to 0, which ignores losses.
linearized_unit_commitment (bool, default False) – Whether to optimise using the linearised unit commitment formulation or not.
model_kwargs (dict) – Keyword arguments used by linopy.Model, such as solver_dir or chunk.
extra_functionality (callable) – This function must take two arguments
extra_functionality(network, snapshots) and is called after
the model building is complete, but before it is sent to the
solver. It allows the user to
add/change constraints and add/change the objective function.
assign_all_duals (bool, default False) – Whether to assign all dual values or only those that already
have a designated place in the network.
Initializes variables ‘attr’ for a given component c to allow a modular
expansion of the attribute ‘attr_nom’ It allows to define ‘n_opt’, the
optimal number of installed modules.
Computes linear power flow for a selection of branch outages.
Parameters:
snapshots (list-like|single snapshot) – A subset or an elements of network.snapshots on which to run
the power flow, defaults to network.snapshots
NB: currently this only works for a single snapshot
branch_outages (list-like) – A list of passive branches which are to be tested for outages.
If None, it’s take as all network.passive_branches_i()
Returns:
p0 – num_passive_branch x num_branch_outages DataFrame of new power flows
Calculate the capacity factor of components in the network.
If bus_carrier is given, only the assets are considered which are
connected to buses with carrier bus_carrier.
For information on the list of arguments, see the docs in
Network.statistics or pypsa.statistics.StatisticsAccessor.
Parameters:
aggregate_time (str, bool, optional) – Type of aggregation when aggregating time series.
Note that for {‘mean’, ‘sum’} the time series are aggregated to
using snapshot weightings. With False the time series is given. Defaults to ‘mean’.
Calculate the curtailment of components in the network in MWh.
The calculation only considers assets with a p_max_pu time
series, which is used to quantify the available power potential.
If bus_carrier is given, only the assets are considered which are
connected to buses with carrier bus_carrier.
For information on the list of arguments, see the docs in
Network.statistics or pypsa.statistics.StatisticsAccessor.
Parameters:
aggregate_time (str, bool, optional) – Type of aggregation when aggregating time series.
Note that for {‘mean’, ‘sum’} the time series are aggregated to MWh
using snapshot weightings. With False the time series is given in MW. Defaults to ‘sum’.
Calculate the dispatch of components in the network. Units depend on
the regarded bus carrier.
If bus_carrier is given, only the dispatch to and from buses with
carrier bus_carrier is calculated.
For information on the list of arguments, see the docs in
Network.statistics or pypsa.statistics.StatisticsAccessor.
Parameters:
aggregate_time (str, bool, optional) – Type of aggregation when aggregating time series.
Note that for {‘mean’, ‘sum’} the time series are aggregated to MWh
using snapshot weightings. With False the time series is given in MW. Defaults to ‘sum’.
Deprecated since version 0.28: This will be removed in 0.29. Use ‘energy_balance’ instead.
Calculate the energy balance of components in the network. Positive
values represent a supply and negative a withdrawal. Units depend on
the regarded bus carrier.
For information on the list of arguments, see the docs in
Network.statistics or pypsa.statistics.StatisticsAccessor.
Whether to obtain the nodal or carrier-wise energy balance. Default is True, corresponding to the carrier-wise balance.
aggregate_timestr, bool, optional
Type of aggregation when aggregating time series.
Note that for {‘mean’, ‘sum’} the time series are aggregated to MWh
using snapshot weightings. With False the time series is given in MW. Defaults to ‘sum’.
Calculate the market value of components in the network in given
currency/MWh or currency/unit_{bus_carrier} where unit_{bus_carrier} is
the unit of the bus carrier.
If bus_carrier is given, only the market value resulting from buses with
carrier bus_carrier are calculated.
For information on the list of arguments, see the docs in
Network.statistics or pypsa.statistics.StatisticsAccessor.
Parameters:
aggregate_time (str, bool, optional) – Type of aggregation when aggregating time series.
Note that for {‘mean’, ‘sum’} the time series are aggregated to
using snapshot weightings. With False the time series is given. Defaults to ‘mean’.
Calculate the operational expenditure in the network in given currency.
If bus_carrier is given, only components which are connected to buses
with carrier bus_carrier are considered.
For information on the list of arguments, see the docs in
Network.statistics or pypsa.statistics.StatisticsAccessor.
Parameters:
aggregate_time (str, bool, optional) – Type of aggregation when aggregating time series.
Note that for {‘mean’, ‘sum’} the time series are aggregated
using snapshot weightings. With False the time series is given. Defaults to ‘sum’.
Calculate the revenue of components in the network in given currency.
The revenue is defined as the net revenue of an asset, i.e cost of input - revenue of output.
If kind is set to “input” or “output” only the revenue of the input or output is considered.
If bus_carrier is given, only the revenue resulting from buses with carrier
bus_carrier is considered.
For information on the list of arguments, see the docs in
Network.statistics or pypsa.statistics.StatisticsAccessor.
Parameters:
aggregate_time (str, bool, optional) – Type of aggregation when aggregating time series.
Note that for {‘mean’, ‘sum’} the time series are aggregated to
using snapshot weightings. With False the time series is given. Defaults to ‘sum’.
kind (str, optional) – Type of revenue to consider. If ‘input’ only the revenue of the input is considered.
If ‘output’ only the revenue of the output is considered. Defaults to None.
Calculate the transmission of branch components in the network. Units
depend on the regarded bus carrier.
If bus_carrier is given, only the flow between buses with
carrier bus_carrier is calculated.
For information on the list of arguments, see the docs in
Network.statistics or pypsa.statistics.StatisticsAccessor.
Parameters:
aggregate_time (str, bool, optional) – Type of aggregation when aggregating time series.
Note that for {‘mean’, ‘sum’} the time series are aggregated to MWh
using snapshot weightings. With False the time series is given in MW. Defaults to ‘sum’.
legend (~matplotlib.legend.Legend) – The legend for which these legend artists are being created.
orig_handle (~matplotlib.artist.Artist or similar) – The object for which these legend artists are being created.
xdescent (int) – The rectangle (xdescent, ydescent, width, height) that the
legend artists being created should fit within.
ydescent (int) – The rectangle (xdescent, ydescent, width, height) that the
legend artists being created should fit within.
width (int) – The rectangle (xdescent, ydescent, width, height) that the
legend artists being created should fit within.
height (int) – The rectangle (xdescent, ydescent, width, height) that the
legend artists being created should fit within.
fontsize (int) – The fontsize in pixels. The legend artists being created should
be scaled according to the given fontsize.
trans (~matplotlib.transforms.Transform) – The transform that is applied to the legend artists being created.
Typically from unit coordinates in the handler box to screen
coordinates.
Layouting function from networkx. See
list
of available options. By default coordinates are determined for a
planar layout
if the network graph is planar, otherwise for a
Kamada-Kawai layout.
Returns:
coordinates – DataFrame containing the generated coordinates with
buses as index and [‘x’, ‘y’] as columns.
Plot the network buses and lines interactively using plotly.
Parameters:
fig (dict, default None) – If not None, figure is built upon this fig.
bus_colors (dict/pandas.Series) – Colors for the buses, defaults to “cadetblue”. If bus_sizes is a
pandas.Series with a Multiindex, bus_colors defaults to the
n.carriers[‘color’] column.
bus_alpha (float) – Adds alpha channel to buses, defaults to 1.
bus_sizes (float/pandas.Series) – Sizes of bus points, defaults to 10.
bus_cmap (plt.cm.ColorMap/str) – If bus_colors are floats, this color map will assign the colors
bus_colorbar (dict) – Plotly colorbar, e.g. {‘title’ : ‘my colorbar’}
bus_text (pandas.Series) – Text for each bus, defaults to bus names
line_colors (str/pandas.Series) – Colors for the lines, defaults to ‘rosybrown’.
link_colors (str/pandas.Series) – Colors for the links, defaults to ‘darkseagreen’.
transfomer_colors (str/pandas.Series) – Colors for the transfomer, defaults to ‘orange’.
line_widths (dict/pandas.Series) – Widths of lines, defaults to 1.5
link_widths (dict/pandas.Series) – Widths of links, defaults to 1.5
transformer_widths (dict/pandas.Series) – Widths of transformer, defaults to 1.5
line_text (pandas.Series) – Text for lines, defaults to line names.
link_text (pandas.Series) – Text for links, defaults to link names.
tranformer_text (pandas.Series) – Text for transformers, defaults to transformer names.
Define the mapbox layout style of the interactive plot. If this is set
to a mapbox layout, the argument mapbox_token must be a valid Mapbox
API access token.
mapbox_token (string) – Mapbox API access token. Obtain from https://www.mapbox.com.
Can also be included in mapbox_parameters as accesstoken=mapbox_token.
mapbox_parameters (dict) – Configuration parameters of the Mapbox layout.
E.g. {“bearing”: 5, “pitch”: 10, “zoom”: 1, “style”: ‘dark’}.
Plot the network buses and lines using matplotlib and cartopy.
Parameters:
margin (float, defaults to 0.05) – Margin at the sides as proportion of distance between max/min x, y
Will be ignored if boundaries are given.
ax (matplotlib ax, defaults to plt.gca()) – Axis to which to plot the network
geomap (bool/str, default True) – Switch to use Cartopy and draw geographical features.
If string is passed, it will be used as a resolution argument,
valid options are ‘10m’, ‘50m’ and ‘110m’.
projection (cartopy.crs.Projection, defaults to None) – Define the projection of your geomap, only valid if cartopy is
installed. If None (default) is passed the projection for cartopy
is set to cartopy.crs.PlateCarree
bus_colors (dict/pandas.Series) – Colors for the buses, defaults to “cadetblue”. If bus_sizes is a
pandas.Series with a Multiindex, bus_colors defaults to the
n.carriers[‘color’] column.
bus_alpha (float) – Adds alpha channel to buses, defaults to 1.
bus_sizes (dict/pandas.Series) – Sizes of bus points, defaults to 1e-2. If a multiindexed Series is passed,
the function will draw pies for each bus (first index level) with
segments of different color (second index level). Such a Series is ob-
tained by e.g. n.generators.groupby([‘bus’, ‘carrier’]).p_nom.sum()
bus_cmap (plt.cm.ColorMap/str) – If bus_colors are floats, this color map will assign the colors
bus_norm (plt.Normalize|matplotlib.colors.*Norm) – The norm applied to the bus_cmap.
bus_split_circles (bool, default False) – Draw half circles if bus_sizes is a pandas.Series with a Multiindex.
If set to true, the upper half circle per bus then includes all positive values
of the series, the lower half circle all negative values. Defaults to False.
line_colors (str/pandas.Series) – Colors for the lines, defaults to ‘rosybrown’.
link_colors (str/pandas.Series) – Colors for the links, defaults to ‘darkseagreen’.
transfomer_colors (str/pandas.Series) – Colors for the transfomer, defaults to ‘orange’.
line_alpha (str/pandas.Series) – Alpha for the lines, defaults to 1.
link_alpha (str/pandas.Series) – Alpha for the links, defaults to 1.
transfomer_alpha (str/pandas.Series) – Alpha for the transfomer, defaults to 1.
line_widths (dict/pandas.Series) – Widths of lines, defaults to 1.5
link_widths (dict/pandas.Series) – Widths of links, defaults to 1.5
transformer_widths (dict/pandas.Series) – Widths of transformer, defaults to 1.5
line_cmap (plt.cm.ColorMap/str|dict) – If line_colors are floats, this color map will assign the colors.
link_cmap (plt.cm.ColorMap/str|dict) – If link_colors are floats, this color map will assign the colors.
transformer_cmap (plt.cm.ColorMap/str|dict) – If transformer_colors are floats, this color map will assign the colors.
line_norm (plt.Normalize|matplotlib.colors.*Norm) – The norm applied to the line_cmap.
link_norm (plt.Normalize|matplotlib.colors.*Norm) – The norm applied to the link_cmap.
transformer_norm (matplotlib.colors.Normalize|matplotlib.colors.*Norm) – The norm applied to the transformer_cmap.
flow (snapshot/pandas.Series/function/string) – Flow to be displayed in the plot, defaults to None. If an element of
n.snapshots is given, the flow at this timestamp will be
displayed. If an aggregation function is given, is will be applied
to the total network flow via pandas.DataFrame.agg (accepts also
function names). Otherwise flows can be specified by passing a pandas
Series with MultiIndex including all necessary branch components.
Use the line_widths argument to additionally adjust the size of the
flow arrows.
Layouting function from networkx which
overrules coordinates given in n.buses[['x','y']]. See
list
of available options.
title (string) – Graph title
boundaries (list of four floats) – Boundaries of the plot in format [x1, x2, y1, y2]
branch_components (list of str) – Branch components to be plotted, defaults to Line and Link.
jitter (None|float) – Amount of random noise to add to bus positions to distinguish
overlapping buses
color_geomap (dict or bool) – Specify colors to paint land and sea areas in.
If True, it defaults to {‘ocean’: ‘lightblue’, ‘land’: ‘whitesmoke’}.
If no dictionary is provided, colors are white.
If False, no geographical features are plotted.
Returns:
bus_collection, branch_collection1, … – Collections for buses and branches.
n_clusters (int) – Final number of clusters desired.
buses_i (None | pandas.Index, default=None) – Subset of buses to cluster. If None, all buses are considered.
branch_components (List, default=None) – Subset of all branch_components in the network. If None, all branch_components are considered.
feature (None | pandas.DataFrame, default=None) – Feature to be considered for the clustering.
The DataFrame must be indexed with buses_i.
If None, all buses have the same similarity.
affinity (str or callable, default=’euclidean’) – Metric used to compute the linkage.
Can be “euclidean”, “l1”, “l2”, “manhattan”, “cosine”, or “precomputed”.
If linkage is “ward”, only “euclidean” is accepted.
If “precomputed”, a distance matrix (instead of a similarity matrix) is needed as input for the fit method.
linkage (‘ward’, ‘complete’, ‘average’ or ‘single’, default=’ward’) – Which linkage criterion to use.
The linkage criterion determines which distance to use between sets of observation.
The algorithm will merge the pairs of cluster that minimize this criterion.
- ‘ward’ minimizes the variance of the clusters being merged.
- ‘average’ uses the average of the distances of each observation of the two sets.
- ‘complete’ or ‘maximum’ linkage uses the maximum distances between all observations of the two sets.
- ‘single’ uses the minimum of the distances between all observations of the two sets.
kwargs – Any remaining arguments to be passed to Hierarchical Clustering (e.g. memory, connectivity).
Returns:
busmap – Mapping of network.buses to clusters (indexed by
non-negative integers).
Cluster the network using Hierarchical Agglomerative Clustering.
Parameters:
n (pypsa.Network) – The buses must have coordinates x, y.
buses_i (None | pandas.Index, default=None) – Subset of buses to cluster. If None, all buses are considered.
branch_components (List, default=["Line", "Link"]) – Subset of all branch_components in the network.
feature (None | pandas.DataFrame, default=None) – Feature to be considered for the clustering.
The DataFrame must be indexed with buses_i.
If None, all buses have the same similarity.
affinity (str or callable, default=’euclidean’) – Metric used to compute the linkage.
Can be “euclidean”, “l1”, “l2”, “manhattan”, “cosine”, or “precomputed”.
If linkage is “ward”, only “euclidean” is accepted.
If “precomputed”, a distance matrix (instead of a similarity matrix) is needed as input for the fit method.
linkage (‘ward’, ‘complete’, ‘average’ or ‘single’, default=’ward’) – Which linkage criterion to use.
The linkage criterion determines which distance to use between sets of observation.
The algorithm will merge the pairs of cluster that minimize this criterion.
- ‘ward’ minimizes the variance of the clusters being merged.
- ‘average’ uses the average of the distances of each observation of the two sets.
- ‘complete’ or ‘maximum’ linkage uses the maximum distances between all observations of the two sets.
- ‘single’ uses the minimum of the distances between all observations of the two sets.
line_length_factor (float, default=1.0) – Factor to multiply the spherical distance between two new buses in order to get new line lengths.
kwargs – Any remaining arguments to be passed to Hierarchical Clustering (e.g. memory, connectivity).
Returns:
Clustering – A named tuple containing network, busmap and linemap