Skip to content

Network ¶

Network(
    import_name: str | Path = "",
    name: str = "Unnamed Network",
    ignore_standard_types: bool = False,
    **kwargs: Any,
)

Bases: NetworkComponentsMixin, NetworkDescriptorsMixin, NetworkTransformMixin, NetworkIndexMixin, NetworkConsistencyMixin, NetworkGraphMixin, NetworkPowerFlowMixin, NetworkIOMixin

Network container for all pypsa.Components and helds most of PyPSA's functionality.

v0.1.0 | Design

Parameters:

  • import_name (string or Path, default: '' ) –

    Path to netCDF file, HDF5 .h5 store or folder of CSV files from which to import network data. The string could be a URL. If cloudpathlib is installed, the string could be a object storage URI with an s3, gs or az URI scheme.

  • name (string, default: 'Unnamed Network' ) –

    Network name.

  • ignore_standard_types (boolean, default: False ) –

    If True, do not read in PyPSA standard types into standard types DataFrames.

  • kwargs (Any, default: {} ) –

    Any remaining attributes to set

Examples:

>>> nw1 = pypsa.Network("network.nc")
>>> nw2 = pypsa.Network("/my/folder")
>>> nw3 = pypsa.Network("https://github.com/PyPSA/PyPSA/raw/master/examples/scigrid-de/scigrid-with-load-gen-trafos.nc")
>>> nw4 = pypsa.Network("s3://my-bucket/my-network.nc")

Methods:

Attributes:

pypsa.Network.optimize instance-attribute ¶

Network optimization functionality accessor.

pypsa.Network.cluster instance-attribute ¶

Network clustering functionality accessor.

pypsa.Network.statistics instance-attribute ¶

Network statistics functionality accessor.

pypsa.Network.plot instance-attribute ¶

plot: PlotAccessor = PlotAccessor(self)

Network plotting functionality accessor.

pypsa.Network.name property writable ¶

name: str

Name of the network.

v0.1.0

The name is set when the network is created. It can also be changed by setting the name attribute. It is only descriptive and not used for any functionality.

Examples:

>>> n.name
'AC-DC-Meshed'
>>> n = pypsa.Network(name='Unnamed Network')
>>> n.name
'Unnamed Network'
>>> n.name = 'net'
>>> n.name
'net'

pypsa.Network.pypsa_version property ¶

pypsa_version: str

PyPSA version of the network.

v0.10.0

The PyPSA version is set when the network is created and cannot be changed manually. When a network of an older version is imported, the version is automatically updated to the current version.

Examples:

>>> n = pypsa.Network()
>>> n.pypsa_version
'1.0.0'

pypsa.Network.meta property writable ¶

meta: dict

Dictionary of the network meta data.

v0.20.0

Any additional meta data can be added to the network by setting the meta attribute. Meta data will be saved on export.

Examples:

>>> n = pypsa.Network()
>>> n.meta['description'] = 'This is a test network'
>>> n.meta['any_key'] = 'Any Key can be added'
>>> n.meta
{'description': 'This is a test network', 'any_key': 'Any Key can be added'}

pypsa.Network.model deletable property ¶

model: Model

Access to linopy model object.

v0.21.0

After optimizing a network, the linopy model object is stored in the network and can be accessed via this property. It cannot be set manually.

Examples:

>>> n.model
Linopy LP model
===============

Variables:
----------
* Generator-p_nom (name)
* Line-s_nom (name)
* Link-p_nom (name)
* Generator-p (snapshot, name)
* Line-s (snapshot, name)
* Link-p (snapshot, name)
* objective_constant

Constraints:
------------
* Generator-ext-p_nom-lower (name)
* Line-ext-s_nom-lower (name)
* Link-ext-p_nom-lower (name)
* Generator-ext-p-lower (snapshot, name)
* Generator-ext-p-upper (snapshot, name)
* Line-ext-s-lower (snapshot, name)
* Line-ext-s-upper (snapshot, name)
* Link-ext-p-lower (snapshot, name)
* Link-ext-p-upper (snapshot, name)
* Bus-nodal_balance (name, snapshot)
* Kirchhoff-Voltage-Law (snapshot, cycle)
* GlobalConstraint-co2_limit

Status:
-------
ok

pypsa.Network.objective property ¶

objective: float | None

Objective value of the solved network.

v0.21.0

The property yields the objective value of the solved network. It is set after optimizing the network points to the linopy solution (e.g. is an alias for n.model.objective.value). When loading a network from file and the model object is not loaded, the objective value is still available, as it is stored in the network object.

When optimizing for system costs, the total system costs are the sum of the pypsa.Network.objective and the pypsa.Network.objective_constant.

Examples:

>>> n.objective
-47274166...
>>> n.objective + n.objective_constant
<xarray.DataArray ()> Size: 8B
array(18441021...)

pypsa.Network.objective_constant property ¶

objective_constant: float | None

Objective constant of the network.

v0.21.0

The property yields the fixed part of the objective function. It is set after optimizing the network.

When optimizing for system costs, the total system costs are the sum of the pypsa.Network.objective and the pypsa.Network.objective_constant. When loading a network from file and the model object is not loaded, the objective constant is still available, as it is stored in the network object.

Examples:

>>> n.objective_constant
<xarray.DataArray ()> Size: 8B
array(65715187...)
>>> n.objective + n.objective_constant
<xarray.DataArray ()> Size: 8B
array(18441021...)

pypsa.Network.is_solved property ¶

is_solved: bool

Check if the network has been solved.

v0.35.0

A solved network has an objective[] value assigned. A model[] does not necessarily need to be stored in the network.

Returns:

  • bool –

    True if the network has been solved, False otherwise.

Examples:

>>> n.is_solved
True

pypsa.Network.crs property writable ¶

crs: Any

Coordinate reference system of the network's geometries.

v0.26.0

Examples:

>>> n.crs
<Geographic 2D CRS: EPSG:4326>
Name: WGS 84
Axis Info [ellipsoidal]:
- Lat[north]: Geodetic latitude (degree)
- Lon[east]: Geodetic longitude (degree)
Area of Use:
- name: World.
- bounds: (-180.0, -90.0, 180.0, 90.0)
Datum: World Geodetic System 1984 ensemble
- Ellipsoid: WGS 84
- Prime Meridian: Greenwich

pypsa.Network.srid property writable ¶

srid: int

Spatial reference system identifier of the network's geometries.

v0.26.0

Examples:

>>> n.srid
4326
See Also

pypsa.Network.crs, pypsa.Network.shapes

pypsa.Network.__str__ ¶

__str__() -> str

Get a string representation of the network.

v0.33.0

Examples:

>>> str(n)
"PyPSA Network 'AC-DC-Meshed'"
>>> str(n_stochastic)
"Stochastic PyPSA Network 'Stochastic-Network'"

pypsa.Network.__repr__ ¶

__repr__() -> str

Get representation of the network.

v0.3.0

Examples:

>>> n
PyPSA Network 'AC-DC-Meshed'
----------------------------
Components:
 - Bus: 9
 - Carrier: ...
 - Generator: ...
 - GlobalConstraint: ...
 - Line: ...
 - Link: ...
 - Load: ...
 - SubNetwork: ...
Snapshots: 10

pypsa.Network.__add__ ¶

__add__(other: Network) -> None

Merge all components of two networks.

v0.28.0

Parameters:

  • other (Network) –

    Network to merge into this one.

See Also

pypsa.Network.merge

Examples:

>>> n1 = pypsa.Network()
>>> n2 = pypsa.Network()
>>> n1.add("Bus", "bus1")
>>> n2.add("Bus", "bus2")
>>> new_network = n1 + n2
>>> len(new_network.buses)
2

pypsa.Network.__eq__ ¶

__eq__(other: object) -> bool

Check for equality of two networks.

Parameters:

  • other (Any) –

    The other network to compare with.

Returns:

  • bool –

    True if the networks are equal, False otherwise.

See Also

pypsa.Network.equals

pypsa.Network.__getitem__ ¶

__getitem__(key: str) -> Network

Return a shallow slice of the Network object.

A network can be sliced in three different ways: 1. If the key is a scenario name and the network has scenarios, the corresponding scenario is returned as a new network object. See pypsa.Network.get_scenario. 2. If the network is a collection and the key is a name of one of the networks in the collection, that network is returned. 3. If the key is a bus name or a boolean indexer for buses, a sliced copy of the network is returned, containing only the selected buses and all connected components. See pypsa.Network.slice_network.

A warning will be issued if the key matches multiple of the above entities. In that case, the first match is returned. But it is recommended to use the explicit methods (e.g. get_scenario(), get_network()) or use unique scenario, collection and bus names to avoid ambiguity.

Parameters:

  • key (str or boolean mask) –

    The key or boolean mask to select a scenario, a network from a collection or slice the network based on buses.

Returns:

Examples:

Select single scenario from a stochastic network:

>>> n_stochastic
Stochastic PyPSA Network 'Stochastic-Network'
---------------------------------------------
Components:
- Bus: 3
- Generator: 12
- Load: 3
Snapshots: 2920
Scenarios: 3
>>> n_stochastic["high"]
PyPSA Network 'Stochastic-Network - Scenario 'high''
----------------------------------------------------
Components:
- Bus: 1
- Generator: 4
- Load: 1
Snapshots: 2920

Select single collection from a network collection:

>>> nc
NetworkCollection
-----------------
Networks: 2
Index name: 'network'
Entries: ['AC-DC-Meshed', 'AC-DC-Meshed-Shuffled-Load']
>>> nc["AC-DC-Meshed"]
PyPSA Network 'AC-DC-Meshed'
----------------------------
Components:
 - Bus: 9
 - Carrier: 6
 - Generator: 6
 - GlobalConstraint: 1
 - Line: 7
 - Link: 4
 - Load: 6
 - SubNetwork: 3
Snapshots: 10

Select a network slice based on buses:

>>> n
PyPSA Network 'AC-DC-Meshed'
----------------------------
Components:
 - Bus: 9
 - Carrier: 6
 - Generator: 6
 - GlobalConstraint: 1
 - Line: 7
 - Link: 4
 - Load: 6
 - SubNetwork: 3
Snapshots: 10
>>> n["London"]
PyPSA Network 'AC-DC-Meshed'
----------------------------
Components:
- Bus: 1
- Carrier: 6
- GlobalConstraint: 1
- Load: 1
Snapshots: 10

or use the pandas .loc method to select multiple buses:

>>> n[n.buses.carrier=='AC']
PyPSA Network 'AC-DC-Meshed'
----------------------------
Components:
- Bus: 6
- Carrier: 6
- Generator: 6
- GlobalConstraint: 1
- Line: 4
- Link: 1
- Load: 6
Snapshots: 10

pypsa.Network.equals ¶

equals(other: Any, log_mode: str = 'silent') -> bool

Check for equality of two networks.

Parameters:

  • other (Any) –

    The other network to compare with.

  • log_mode (str, default: 'silent' ) –

    Controls how differences are reported: - 'silent': No logging, just returns True/False - 'verbose': Prints differences but doesn't raise errors - 'strict': Raises ValueError on first difference

Raises:

  • ValueError –

    If log_mode is 'strict' and components are not equal.

Returns:

  • bool –

    True if the networks are equal, False otherwise.

Examples:

>>> n1 = pypsa.Network()
>>> n2 = pypsa.Network()
>>> n1.add("Bus", "bus1")
>>> n2.add("Bus", "bus2")
>>> n1.equals(n2)
False

pypsa.Network.to_crs ¶

to_crs(new: int | str | CRS) -> None

Convert the network's geometries and bus coordinates to a new crs.

v0.26.0

See Also

pypsa.Network.crs, pypsa.Network.srid, pypsa.Network.shapes

pypsa.Network.explore ¶

explore(*args: Any, **kwargs: Any) -> Any

pypsa.Network.copy ¶

copy(
    snapshots: Sequence | None = None,
    investment_periods: Sequence | None = None,
    ignore_standard_types: bool = False,
) -> Network

Return a deep copy of Network object.

v0.4.0

If only default arguments are passed, the copy will be created via copy.deepcopy and will contain all components and time-varying data. For most networks this is the fastest way. However, if the network is very large, it might be better to filter snapshots and investment periods to reduce the size of the copy. In this case copy.deepcopy is not used and only the selected snapshots and investment periods are copied to a new object.

Parameters:

  • snapshots (list or tuple or Index, default: self.snapshots ) –

    A list of snapshots to copy, must be a subset of n.snapshots. Pass an empty list ignore all snapshots.

  • investment_periods (list or tuple or Index, default: self.investment_period_weightings.index ) –

    A list of investment periods to copy, must be a subset of n.investment_periods. Pass

  • ignore_standard_types (boolean, default: False ) –

    Ignore the PyPSA standard types.

Returns:

  • n ( Network ) –

    The copied network object.

Examples:

With a simple reference the network is not copied:

>>> n = pypsa.examples.ac_dc_meshed()
>>> network_copy = n
>>> id(network_copy) == id(n)
True

Use the copy method to create a new network object:

>>> network_copy = n.copy()
>>> id(network_copy) == id(n)
False

You can also filter on a subset of snapshots (or investment periods):

>>> 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',
               '2015-01-01 04:00:00', '2015-01-01 05:00:00',
               '2015-01-01 06:00:00', '2015-01-01 07:00:00',
               '2015-01-01 08:00:00', '2015-01-01 09:00:00'],
              dtype='datetime64[ns]', name='snapshot', freq=None)
>>> network_copy = n.copy(snapshots=n.snapshots[0])
>>> network_copy.snapshots
DatetimeIndex(['2015-01-01'], dtype='datetime64[ns]', name='snapshot', freq=None)

pypsa.Network.branches ¶

branches() -> DataFrame

Get branches.

v0.3.0

Branches are Lines, Links and Transformers.

Note

This method will return a merged copy of all branches of the network. Changes to the returned DataFrame will not be reflected in the network.

Examples:

>>> n.branches()
                         active    b  b_pu  ...         x      x_pu  x_pu_eff
component name                                  ...

Line 0 True 0.0 0.0 ... 0.796878 0.000006 0.000006 1 True 0.0 0.0 ... 0.391560 0.000003 0.000003 2 True 0.0 0.0 ... 0.000000 0.000000 0.000000 3 True 0.0 0.0 ... 0.000000 0.000000 0.000000 4 True 0.0 0.0 ... 0.000000 0.000000 0.000000 5 True 0.0 0.0 ... 0.238800 0.000002 0.000002 6 True 0.0 0.0 ... 0.400000 0.000003 0.000003 Link Norwich Converter True NaN NaN ... NaN NaN NaN Norway Converter True NaN NaN ... NaN NaN NaN Bremen Converter True NaN NaN ... NaN NaN NaN DC link True NaN NaN ... NaN NaN NaN [11 rows x 61 columns]

See Also

pypsa.Network.passive_branches, pypsa.Network.controllable_branches

pypsa.Network.passive_branches ¶

passive_branches() -> DataFrame

Get passive branches.

v0.3.0

Passive branches are Lines and Transformers.

Note

This method will return a merged copy of all passive branches of the network. Changes to the returned DataFrame will not be reflected in the network.

Examples:

>>> n.passive_branches()
            active    b  b_pu  ...         x      x_pu  x_pu_eff
component                     ...
0            True  0.0   0.0  ...  0.796878  0.000006  0.000006
1            True  0.0   0.0  ...  0.391560  0.000003  0.000003
2            True  0.0   0.0  ...  0.000000  0.000000  0.000000
3            True  0.0   0.0  ...  0.000000  0.000000  0.000000
4            True  0.0   0.0  ...  0.000000  0.000000  0.000000
5            True  0.0   0.0  ...  0.238800  0.000002  0.000002
6            True  0.0   0.0  ...  0.400000  0.000003  0.000003

[7 rows x 38 columns]

pypsa.Network.controllable_branches ¶

controllable_branches() -> DataFrame

Get controllable branches.

v0.3.0

Controllable branches are Links.

Note

This method will return a merged copy of all controllable branches of the network. Changes to the returned DataFrame will not be reflected in the network.

Examples:

>>> n.controllable_branches()
                active    b  b_pu  ...         x      x_pu  x_pu_eff
component name                     ...
Line      0       True  0.0   0.0  ...  0.796878  0.000006  0.000006
        1       True  0.0   0.0  ...  0.391560  0.000003  0.000003
        2       True  0.0   0.0  ...  0.000000  0.000000  0.000000
        3       True  0.0   0.0  ...  0.000000  0.000000  0.000000
        4       True  0.0   0.0  ...  0.000000  0.000000  0.000000
        5       True  0.0   0.0  ...  0.238800  0.000002  0.000002
        6       True  0.0   0.0  ...  0.400000  0.000003  0.000003

[7 rows x 38 columns]
See Also

pypsa.Network.branches, pypsa.Network.passive_branches

pypsa.Network.determine_network_topology ¶

determine_network_topology(
    investment_period: int | str | None = None,
    skip_isolated_buses: bool = False,
) -> Network

Build sub_networks from topology.

v0.3.0

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.

pypsa.Network.cycle_matrix ¶

cycle_matrix(
    investment_period: str | int | None = None,
    apply_weights: bool = False,
) -> DataFrame

Get the cycles in the network and represent them as a DataFrame.

v1.0.0

This function identifies a cycle basis of the network topology and returns a DataFrame representation of the cycle matrix. The cycles matrix is a sparse matrix with branches as rows and independent cycles as columns. An entry of +1 indicates the branch is traversed in the direction from bus0 to bus1 in that cycle, -1 indicates the opposite direction, and 0 indicates the branch is not part of the cycle.

Parameters:

  • investment_period (str or int, default: None ) –

    Investment period to use when determining network topology. If not given, all branches are considered regardless of build_year and lifetime.

  • apply_weights (bool, default: False ) –

    Whether to apply weights (e.g., reactance for AC lines, resistance for DC lines) to the cycles.

Returns:

  • DataFrame –

    A DataFrame with branches as rows (MultiIndex of (component, name)) and cycles as columns. Each column represents an independent cycle in the network.

pypsa.Network.component ¶

component(c_name: str) -> Component

Get a component from the network.

Deprecated in v1.0.0

Use n.components.<component> or n.components[component_name] instead.

pypsa.Network.iterate_components ¶

iterate_components(
    components: Collection[str] | None = None,
    skip_empty: bool = True,
) -> Iterator[Component]

Iterate over components.

Deprecated in v1.0.0

Use for component in n.components instead.

Examples:

>>> for component in n.iterate_components():
...     print(component)
...     break
'Bus' Components