Skip to content

Utilities API

utils

Static information and general utility functions for pypsa_validation_processing.

MissingInputError

Bases: Exception

Raised by a statistics function when a required input key is missing.

The message names the missing key (e.g. a dotted config path such as sector.district_heating.district_heating_loss). Network_Processor catches it and skips the variable for that network.

remap_unit_index(series: pd.Series | pd.DataFrame, unit_mapping: dict = UNITS_MAPPING) -> pd.Series | pd.DataFrame

Remaps unit index to standard value for statistics with need for direct comparison of input-output flows.

Parameters:

Name Type Description Default
series Series | DataFrame

A series with a MultiIndex with a unit level.

required
unit_mapping dict

Dictionary with old unit values as keys and new unit values as values, by default UNITS_MAPPING

UNITS_MAPPING

Returns:

Type Description
Series | DataFrame

A series with a MultiIndex with a unit level remapped.

create_location_index_from_copperplate(raw_input: pd.Series | pd.DataFrame, usage_location_list: list, column_name: str = 'location')

Replace the values of level column_name of an indexed object. Default column_name to be replaced is "location" for backward compatibility.

This helper rebuilds the index of raw_input from its index frame and overwrites the column_name column with values from usage_location_list. It is mainly used when location information from a copperplate-carrier result must be mapped back to explicit regional labels.

Parameters:

Name Type Description Default
raw_input Series or DataFrame

Input object with a (Multi)Index that includes a location level. The function preserves data values and index level order/names.

required
usage_location_list list

New location values to assign row-by-row. Must have the same length as raw_input.

required
column_name str

Name of the index level to replace, by default "location".

'location'

Returns:

Type Description
Series or DataFrame

A copy of raw_input with the same data and a rebuilt index where the column_name level has been replaced.

Raises:

Type Description
ValueError

If usage_location_list length does not match the number of rows, or if the index cannot be reconstructed with the existing index names.

ValueError

If column_name is not found in the index levels of raw_input.

attribute_locations(n: pypsa.Network, flows: pd.Series | pd.DataFrame) -> pd.Series | pd.DataFrame

Attribute flows on copperplate buses to a location (D1).

pypsa.statistics already attributes a flow to the location of the bus at the evaluated port (D1.1, D1.2). This helper applies the copperplate exception: a Link flow at location EU is moved to the location of the Link's bus1 (D1.3). If bus1 is a copperplate bus as well, the flow stays at EU (D1.4). Flows of other components are not changed.

Parameters:

Name Type Description Default
n Network

Network the flows were evaluated on.

required
flows Series | DataFrame

Result of a pypsa.statistics call whose index contains the levels component, name and location. pypsa.statistics drops the component level if components is a single string, so pass a list (e.g. components=["Link"]).

required

Returns:

Type Description
Series | DataFrame

Copy of flows with the location level replaced. Rows are not regrouped, so two rows may now share all index values.

Raises:

Type Description
ValueError

If the index of flows lacks one of the required levels.

fossil_oil_share(n: pypsa.Network) -> float

Return the system-wide fossil share of oil f_oil (D2).

Yearly supply to all oil buses, summed over all locations; Stores are excluded. The same value applies to every location and every snapshot.

Parameters:

Name Type Description Default
n Network

Network to evaluate.

required

Returns:

Type Description
float

f_oil in [0, 1]; 0.0 if no oil is supplied.

Raises:

Type Description
ValueError

If a component other than a Store with a carrier outside OIL_FOSSIL_CARRIERS and OIL_NON_FOSSIL_CARRIERS supplies oil.

fossil_gas_share(n: pypsa.Network) -> float

Return the system-wide fossil share of gas f_gas (D3).

Yearly supply to all gas buses, summed over all locations. Stores and gas transport (GAS_TRANSPORT_CARRIERS and every Link whose bus0 and bus1 are both gas buses) are excluded. The same value applies to every location and every snapshot.

Parameters:

Name Type Description Default
n Network

Network to evaluate.

required

Returns:

Type Description
float

f_gas in [0, 1]; 0.0 if no gas is supplied.

Raises:

Type Description
ValueError

If a non-excluded component with a carrier outside GAS_FOSSIL_CARRIERS and GAS_NON_FOSSIL_CARRIERS supplies gas.

apply_domestic_share(energy_stats: pd.Series | pd.DataFrame, energy_totals: pd.DataFrame | None, kind: str) -> pd.Series | pd.DataFrame

Multiply flows by the domestic share d_k(c) of their country (D4).

d_k(c) = total domestic k / (total domestic k + total international k) with c = the first two characters of the location. The share is looked up only for rows with a non-zero value (in any snapshot); rows that are 0 everywhere stay 0 without a lookup, e.g. the pseudo-location EU.

Parameters:

Name Type Description Default
energy_stats Series | DataFrame

Energy statistics with a location index level; a DataFrame has snapshots as columns.

required
energy_totals DataFrame | None

Energy totals of one year, indexed by country (C2.4).

required
kind str

"aviation" or "navigation".

required

Returns:

Type Description
Series | DataFrame

energy_stats multiplied row-wise by d_k; a denominator of 0 gives 0.

Raises:

Type Description
ValueError

If energy_totals is None or kind is not supported.

MissingInputError

If a row with non-zero Energy statistics belongs to a country without a row in energy_totals; Network_Processor then skips the variable.

non_energy_use(demand: pd.Series | pd.DataFrame, shares: pd.DataFrame | None, carrier: str) -> pd.Series | pd.DataFrame

Return the industrial non-energy use NE_x(l) (D5, Eurostat fallback).

NE_x(l) = S[c, x] · demand(l) with c = the first two characters of the location and S the Eurostat shares (C2.5). A country without a row for carrier gets the unweighted mean of all rows of carrier, with one WARNING per call naming the countries (none for the copperplate EU). NE_H2 is 0, with one WARNING per call. 0 ≤ S ≤ 1 is checked when the file is read; a share outside [0, 1] here (e.g. after an adaptation of the shares) is clipped to [0, 1] with one WARNING per call, so 0 ≤ NE_x(l) ≤ demand(l).

Parameters:

Name Type Description Default
demand Series | DataFrame

Industry demand of carrier (e.g. the gas for industry Load) with a location index level; a DataFrame has snapshots as columns.

required
shares DataFrame | None

Index (country, carrier), column non_energy_share (C2.5). Read from the CSV written by the sister package eurostat-energy-balance_processing (utils.calculate_industry_non_energy_shares, written by IAMC_Creator.write_industry_non_energy_shares).

required
carrier str

"Natural Gas", "Oil", "Coal" or "H2".

required

Returns:

Type Description
Series | DataFrame

Non-energy use with the index and columns of demand.

Raises:

Type Description
ValueError

If carrier is not supported, or shares is None for a carrier other than "H2".

apply_coke_correction(coal_energy: pd.Series | pd.DataFrame, kappa: float | None = None) -> pd.Series | pd.DataFrame

Apply the coke correction to the energy part of industrial coal (D6). PyPSA reports with coal for industry the coal, that goes into coke ovens, Eurostats final energy counts the coke, that comes out of them.

FE = E · (1 − κ) + E · κ / MWH_COAL_PER_MWH_COKE with E the coal for industry demand minus its non-energy use (D5).

Parameters:

Name Type Description Default
coal_energy Series | DataFrame

Energy part E of the industrial coal demand.

required
kappa float | None

Coke share κ in [0, 1] from the physical method (C2.5). If None (default), the Eurostat fallback κ = 0 applies and one WARNING is logged.

None

Returns:

Type Description
Series | DataFrame

Coal final energy with the index and columns of coal_energy.

Raises:

Type Description
ValueError

If kappa is outside [0, 1].

decentral_heat_split(n: pypsa.Network, aggregate_per_year: bool = True) -> pd.Series | pd.DataFrame

Split the input to decentral heat supply between sectors (D8).

For each bus carrier b of DECENTRAL_HEAT_BUS_CARRIERS and location l: D8_x(l) = Σ_b σ_b,x(l) · I_b(l). I_b is the withdrawal of the Links that supply heat to b at their non-heat input ports (location per D1), plus the heat supplied by Generators (solar thermal) and by CHPs (Links with a further non-heat output) to b. Heat storage and heat vents are excluded. σ_b,x are yearly demand shares, applied to every snapshot.

Parameters:

Name Type Description Default
n Network

Network to evaluate.

required
aggregate_per_year bool

If True (default), return yearly values as a Series; otherwise a DataFrame with snapshots as columns.

True

Returns:

Type Description
Series | DataFrame

Index levels sector (rc, agr, ind, other), location, carrier (input carrier) and unit (normalised to MWh, C6.5). Empty if no decentral heat bus is supplied.

ensure_all_locations(result: pd.Series | pd.DataFrame, n: pypsa.Network, unit: str, aggregate_per_year: bool) -> pd.Series | pd.DataFrame

Add every location of n missing in result (C6.13).

Added rows are 0.0; for intensive results (quantity level, C6.12) they are NaN.

Parameters:

Name Type Description Default
result Series | DataFrame

Result of a statistics function whose index levels contain at least location and unit (C6.1-C6.3), or a result with zero rows (e.g. an empty n.statistics result).

required
n Network

Evaluated network; its locations are the non-empty values of n.buses.location.

required
unit str

Normalised unit of the variable (a key of UNITS_MAPPING) for the added rows.

required
aggregate_per_year bool

If True, return a :class:pandas.Series; if False, a :class:pandas.DataFrame with the snapshots of n as columns. Needed because n.statistics returns an empty pd.Series in both modes.

required

Returns:

Type Description
Series | DataFrame

result plus one row per missing location with 0.0 (aggregate_per_year=False: in every snapshot column of n). If result has a quantity level (intensive, C6.12), two rows value and weight are added instead, both NaN, not 0.0: the weighted quantity does not exist at a missing location (C6.13, A-5). Further index levels of result are NaN in the added rows; C8 aggregates them away.

Raises:

Type Description
ValueError

If a non-empty result lacks the index level location or unit.

load_weighted_price(n: pypsa.Network, carriers: list[str], aggregate_per_year: bool) -> pd.Series | pd.DataFrame

Return the Load-weighted marginal price P[c](l) per location (D9).

Port of pypsa-de price_load (export_ariadne_variables.py l.3378-3402, commit a5baa7e9): weight w = withdrawal of the Loads with a carrier in carriers, cost K = Σ p_t·λ_b,t with λ_b the marginal price of the Load's bus (CO2 price included), value K / w. Loads are attributed to the location of their bus (D1.1); K and w are summed over all carriers before dividing.

Parameters:

Name Type Description Default
n Network

Solved network to evaluate.

required
carriers list[str]

Load carriers to price, e.g. ["industry electricity"].

required
aggregate_per_year bool

If True, w and K are weighted with n.snapshot_weightings.objective and summed over the year (C6.12); if False, per snapshot and unweighted.

required

Returns:

Type Description
Series | DataFrame

MultiIndex [location, unit, quantity], quantity ∈ {value, weight}, unit label PRICE_UNIT on both rows; only locations with at least one such Load. The value is NaN where the weight is 0.0 (per snapshot for aggregate_per_year=False).