power_grid_model (Python API)

This is the Python API reference for the power-grid-model library. Due to the nature of how Python module works, we cannnot hide the implementation detail completely from the user. As a general rule, any Python modules/functions/classes not documented in this API documentation are internal implementations. The user should not use any of them. We do not guarantee the stability or even the existence of those modules.

class power_grid_model.PowerGridModel(*_args, **_kwargs)

Bases: object

Main class for Power Grid Model

property batch_error: PowerGridBatchError | None

Get the batch error object, if present, after a batch calculation with errors.

Also works when continue_on_batch_error was set to True during the calculation.

Returns:

Batch error object, or None

property all_component_count: dict[ComponentType, int]

Get amount of elements per component type. If the count for a component type is zero, it will not be in the returned dictionary.

Returns:

A dictionary with

  • key: Component type name

  • value: Integer count of elements of this type

copy() PowerGridModel

Copy the current model

Returns:

A copy of PowerGridModel

__init__(input_data: dict[ComponentTypeVar, _SingleComponentData], system_frequency: float = 50.0)

Initialize the model from an input data set.

Parameters:
  • input_data

    Input data dictionary

    • key: Component type

    • value: Component data with the correct type SingleComponentData

  • system_frequency – Frequency of the power system, default 50 Hz

update(*, update_data: dict[ComponentTypeVar, _ComponentData])

Update the model with changes.

The model will be in an invalid state if the update fails and should be discarded.

Parameters:

update_data

Update data dictionary

  • key: Component type

  • value: Component data with the correct type ComponentData (single scenario or batch)

Raises:

PowerGridError if the update fails. The model is left in an invalid state and should be discarded.

Returns:

None

get_indexer(component_type: ComponentTypeLike, ids: ndarray)

Get array of indexers given array of ids for component type.

This enables syntax like input_data[ComponentType.node][get_indexer(ids)]

Parameters:
  • component_type – Type of component

  • ids – Array of ids

Returns:

Array of indexers, same shape as input array ids

calculate_power_flow(*, symmetric: bool = True, error_tolerance: float = 1e-08, max_iterations: int = 20, calculation_method: CalculationMethod | str = CalculationMethod.newton_raphson, threading: int = -1, output_component_types: None | set[ComponentTypeVar] | list[ComponentTypeVar] = None, continue_on_batch_error: bool = False, decode_error: bool = True, tap_changing_strategy: TapChangingStrategy | str = TapChangingStrategy.disabled) dict[ComponentTypeVar, SingleArray]
calculate_power_flow(*, symmetric: bool = True, error_tolerance: float = 1e-08, max_iterations: int = 20, calculation_method: CalculationMethod | str = CalculationMethod.newton_raphson, update_data: None = None, threading: int = -1, output_component_types: None | set[ComponentTypeVar] | list[ComponentTypeVar] = None, continue_on_batch_error: bool = False, decode_error: bool = True, tap_changing_strategy: TapChangingStrategy | str = TapChangingStrategy.disabled) dict[ComponentTypeVar, SingleArray]
calculate_power_flow(*, symmetric: bool = True, error_tolerance: float = 1e-08, max_iterations: int = 20, calculation_method: CalculationMethod | str = CalculationMethod.newton_raphson, update_data: None = None, threading: int = -1, output_component_types: ComponentAttributeFilterOptions = None, continue_on_batch_error: bool = False, decode_error: bool = True, tap_changing_strategy: TapChangingStrategy | str = TapChangingStrategy.disabled) dict[ComponentType, dict[AttributeTypeVar, SingleColumn]]
calculate_power_flow(*, symmetric: bool = True, error_tolerance: float = 1e-08, max_iterations: int = 20, calculation_method: CalculationMethod | str = CalculationMethod.newton_raphson, update_data: None = None, threading: int = -1, output_component_types: dict[ComponentType, set[AttributeTypeVar] | list[AttributeTypeVar] | None | ComponentAttributeFilterOptions] = None, continue_on_batch_error: bool = False, decode_error: bool = True, tap_changing_strategy: TapChangingStrategy | str = TapChangingStrategy.disabled) dict[ComponentType, SingleArray | dict[AttributeTypeVar, SingleColumn]]
calculate_power_flow(*, symmetric: bool = True, error_tolerance: float = 1e-08, max_iterations: int = 20, calculation_method: CalculationMethod | str = CalculationMethod.newton_raphson, update_data: dict[ComponentTypeVar, _BatchComponentData] | list[dict[ComponentTypeVar, _BatchComponentData]] = None, threading: int = -1, output_component_types: None | set[ComponentTypeVar] | list[ComponentTypeVar] = None, continue_on_batch_error: bool = False, decode_error: bool = True, tap_changing_strategy: TapChangingStrategy | str = TapChangingStrategy.disabled) dict[ComponentType, DenseBatchArray]
calculate_power_flow(*, symmetric: bool = True, error_tolerance: float = 1e-08, max_iterations: int = 20, calculation_method: CalculationMethod | str = CalculationMethod.newton_raphson, update_data: dict[ComponentTypeVar, _BatchComponentData] | list[dict[ComponentTypeVar, _BatchComponentData]] = None, threading: int = -1, output_component_types: ComponentAttributeFilterOptions = None, continue_on_batch_error: bool = False, decode_error: bool = True, tap_changing_strategy: TapChangingStrategy | str = TapChangingStrategy.disabled) dict[ComponentType, dict[AttributeTypeVar, BatchColumn]]
calculate_power_flow(*, symmetric: bool = True, error_tolerance: float = 1e-08, max_iterations: int = 20, calculation_method: CalculationMethod | str = CalculationMethod.newton_raphson, update_data: dict[ComponentTypeVar, _BatchComponentData] | list[dict[ComponentTypeVar, _BatchComponentData]] = None, threading: int = -1, output_component_types: dict[ComponentType, set[AttributeTypeVar] | list[AttributeTypeVar] | None | ComponentAttributeFilterOptions] = None, continue_on_batch_error: bool = False, decode_error: bool = True, tap_changing_strategy: TapChangingStrategy | str = TapChangingStrategy.disabled) dict[ComponentType, DenseBatchArray | dict[AttributeTypeVar, BatchColumn]]

Calculate power flow once with the current model attributes. Or calculate in batch with the given update dataset in batch.

Parameters:
  • symmetric (bool, optional) –

    Whether to perform a three-phase symmetric calculation.

    • True: Three-phase symmetric calculation, even for asymmetric loads/generations (Default).

    • False: Three-phase asymmetric calculation.

  • error_tolerance (float, optional) – Error tolerance for voltage in p.u., applicable only when the calculation method is iterative.

  • max_iterations (int, optional) – Maximum number of iterations, applicable only when the calculation method is iterative.

  • calculation_method (an enumeration or string) –

    The calculation method to use.

    • newton_raphson: Use Newton-Raphson iterative method (default).

    • linear: Use linear method.

  • update_data (dict, list of dict, optional) –

    None: Calculate power flow once with the current model attributes.

    Or a dictionary for batch calculation with batch update.

    • key: Component type name to be updated in batch.

    • value:

      • For homogeneous update batch (a 2D numpy structured array):

        • Dimension 0: Each batch.

        • Dimension 1: Each updated element per batch for this component type.

      • For inhomogeneous update batch (a dictionary containing two keys):

    Or a list of such dictionaries (batch datasets) to represent multiple dimensions of cartesian product. The calculation core will interpret these datasets as a cartesian product of all the scenarios. Each batch dataset in the list represents one dimension of the cartesian product. The output will then have row size equal to the product of the batch sizes of all these datasets, in 1D flat structure. E.g., if you have three batch datasets with batch sizes 2, 3, and 4 respectively, and the number of nodes is 5, the final output for nodes will have shape (2*3*4, 5).

  • threading (int, optional) –

    Applicable only for batch calculation.

    • < 0: Sequential

    • = 0: Parallel, use number of hardware threads

    • > 0: Specify number of parallel threads

  • output_component_types (ComponentAttributeMapping) –

    • None: Row based data for all component types.

    • set[ComponentTypeVar] or list[ComponentTypeVar]: Row based data for the specified component types.

    • ComponentAttributeFilterOptions: Columnar data for all component types.

    • ComponentAttributeMappingDict:

      key: ComponentType value:

      • None: Row based data for the specified component types.

      • ComponentAttributeFilterOptions: Columnar data for the specified component types.

      • set[str] | list[str]: Columnar data for the specified component types and attributes.

  • continue_on_batch_error (bool, optional) – Continue the program (instead of throwing error) if some scenarios fail. You can still retrieve the errors and succeeded/failed scenarios via the batch_error.

  • decode_error (bool, optional) – Decode error messages to their derived types if possible.

Returns:

Dictionary of results of all components.

  • key: Component type name to be updated in batch.

  • value:

    • For single calculation: 1D numpy structured array for the results of this component type.

    • For batch calculation: 2D numpy structured array for the results of this component type.

      • Dimension 0: Each batch.

      • Dimension 1: The result of each element for this component type.

Raises:

Exception – In case an error in the core occurs, an exception will be thrown.

calculate_state_estimation(*, symmetric: bool = True, error_tolerance: float = 1e-08, max_iterations: int = 20, calculation_method: CalculationMethod | str = CalculationMethod.iterative_linear, update_data: None = None, threading: int = -1, output_component_types: None | set[ComponentTypeVar] | list[ComponentTypeVar] = None, continue_on_batch_error: bool = False, decode_error: bool = True) dict[ComponentType, SingleArray]
calculate_state_estimation(*, symmetric: bool = True, error_tolerance: float = 1e-08, max_iterations: int = 20, calculation_method: CalculationMethod | str = CalculationMethod.iterative_linear, update_data: None = None, threading: int = -1, output_component_types: ComponentAttributeFilterOptions = None, continue_on_batch_error: bool = False, decode_error: bool = True) dict[ComponentType, dict[AttributeTypeVar, SingleColumn]]
calculate_state_estimation(*, symmetric: bool = True, error_tolerance: float = 1e-08, max_iterations: int = 20, calculation_method: CalculationMethod | str = CalculationMethod.iterative_linear, update_data: None = None, threading: int = -1, output_component_types: dict[ComponentType, set[AttributeTypeVar] | list[AttributeTypeVar] | None | ComponentAttributeFilterOptions] = None, continue_on_batch_error: bool = False, decode_error: bool = True) dict[ComponentType, SingleArray | dict[AttributeTypeVar, SingleColumn]]
calculate_state_estimation(*, symmetric: bool = True, error_tolerance: float = 1e-08, max_iterations: int = 20, calculation_method: CalculationMethod | str = CalculationMethod.iterative_linear, update_data: dict[ComponentTypeVar, _BatchComponentData] | list[dict[ComponentTypeVar, _BatchComponentData]] = None, threading: int = -1, output_component_types: None | set[ComponentTypeVar] | list[ComponentTypeVar] = None, continue_on_batch_error: bool = False, decode_error: bool = True) dict[ComponentType, DenseBatchArray]
calculate_state_estimation(*, symmetric: bool = True, error_tolerance: float = 1e-08, max_iterations: int = 20, calculation_method: CalculationMethod | str = CalculationMethod.iterative_linear, update_data: dict[ComponentTypeVar, _BatchComponentData] | list[dict[ComponentTypeVar, _BatchComponentData]] = None, threading: int = -1, output_component_types: ComponentAttributeFilterOptions = None, continue_on_batch_error: bool = False, decode_error: bool = True) dict[ComponentType, dict[AttributeTypeVar, BatchColumn]]
calculate_state_estimation(*, symmetric: bool = True, error_tolerance: float = 1e-08, max_iterations: int = 20, calculation_method: CalculationMethod | str = CalculationMethod.iterative_linear, update_data: dict[ComponentTypeVar, _BatchComponentData] | list[dict[ComponentTypeVar, _BatchComponentData]] = None, threading: int = -1, output_component_types: dict[ComponentType, set[AttributeTypeVar] | list[AttributeTypeVar] | None | ComponentAttributeFilterOptions] = None, continue_on_batch_error: bool = False, decode_error: bool = True) dict[ComponentType, DenseBatchArray | dict[AttributeTypeVar, BatchColumn]]

Calculate state estimation once with the current model attributes. Or calculate in batch with the given update dataset in batch.

Parameters:
  • symmetric (bool, optional) –

    Whether to perform a three-phase symmetric calculation.

    • True: Three-phase symmetric calculation, even for asymmetric loads/generations (Default).

    • False: Three-phase asymmetric calculation.

  • error_tolerance (float, optional) – error tolerance for voltage in p.u., only applicable when the calculation method is iterative.

  • max_iterations (int, optional) – Maximum number of iterations, applicable only when the calculation method is iterative.

  • calculation_method (an enumeration) – Use iterative linear method.

  • update_data (dict, optional) –

    None: Calculate state estimation once with the current model attributes.

    Or a dictionary for batch calculation with batch update.

    • key: Component type name to be updated in batch.

    • value:

      • For homogeneous update batch (a 2D numpy structured array):

        • Dimension 0: Each batch.

        • Dimension 1: Each updated element per batch for this component type.

      • For inhomogeneous update batch (a dictionary containing two keys):

    Or a list of such dictionaries (batch datasets) to represent multiple dimensions of cartesian product. The calculation core will interpret these datasets as a cartesian product of all the scenarios. Each batch dataset in the list represents one dimension of the cartesian product. The output will then have row size equal to the product of the batch sizes of all these datasets, in 1D flat structure. E.g., if you have three batch datasets with batch sizes 2, 3, and 4 respectively, and the number of nodes is 5, the final output for nodes will have shape (2*3*4, 5).

  • threading (int, optional) –

    Applicable only for batch calculation.

    • < 0: Sequential

    • = 0: Parallel, use number of hardware threads

    • > 0: Specify number of parallel threads

  • output_component_types (ComponentAttributeMapping) –

    • None: Row based data for all component types.

    • set[ComponentTypeVar] or list[ComponentTypeVar]: Row based data for the specified component types.

    • ComponentAttributeFilterOptions: Columnar data for all component types.

    • ComponentAttributeMappingDict:

      key: ComponentType value:

      • None: Row based data for the specified component types.

      • ComponentAttributeFilterOptions: Columnar data for the specified component types.

      • set[str] | list[str]: Columnar data for the specified component types and attributes.

  • continue_on_batch_error (bool, optional) – Continue the program (instead of throwing error) if some scenarios fail. You can still retrieve the errors and succeeded/failed scenarios via the batch_error.

  • decode_error (bool, optional) – Decode error messages to their derived types if possible.

Returns:

Dictionary of results of all components.

  • key: Component type name to be updated in batch.

  • value:

    • For single calculation: 1D numpy structured array for the results of this component type.

    • For batch calculation: 2D numpy structured array for the results of this component type.

      • Dimension 0: Each batch.

      • Dimension 1: The result of each element for this component type.

Raises:

Exception – In case an error in the core occurs, an exception will be thrown.

calculate_short_circuit(*, calculation_method: CalculationMethod | str = CalculationMethod.iec60909, update_data: None = None, threading: int = -1, output_component_types: None | set[ComponentTypeVar] | list[ComponentTypeVar] = None, continue_on_batch_error: bool = False, decode_error: bool = True, short_circuit_voltage_scaling: ShortCircuitVoltageScaling | str = ShortCircuitVoltageScaling.maximum) dict[ComponentTypeVar, SingleArray]
calculate_short_circuit(*, calculation_method: CalculationMethod | str = CalculationMethod.iec60909, update_data: None = None, threading: int = -1, output_component_types: ComponentAttributeFilterOptions = None, continue_on_batch_error: bool = False, decode_error: bool = True, short_circuit_voltage_scaling: ShortCircuitVoltageScaling | str = ShortCircuitVoltageScaling.maximum) dict[ComponentType, dict[AttributeTypeVar, SingleColumn]]
calculate_short_circuit(*, calculation_method: CalculationMethod | str = CalculationMethod.iec60909, update_data: None = None, threading: int = -1, output_component_types: dict[ComponentType, set[AttributeTypeVar] | list[AttributeTypeVar] | None | ComponentAttributeFilterOptions] = None, continue_on_batch_error: bool = False, decode_error: bool = True, short_circuit_voltage_scaling: ShortCircuitVoltageScaling | str = ShortCircuitVoltageScaling.maximum) dict[ComponentType, SingleArray | dict[AttributeTypeVar, SingleColumn]]
calculate_short_circuit(*, calculation_method: CalculationMethod | str = CalculationMethod.iec60909, update_data: dict[ComponentTypeVar, _BatchComponentData] | list[dict[ComponentTypeVar, _BatchComponentData]] = None, threading: int = -1, output_component_types: None | set[ComponentTypeVar] | list[ComponentTypeVar] = None, continue_on_batch_error: bool = False, decode_error: bool = True, short_circuit_voltage_scaling: ShortCircuitVoltageScaling | str = ShortCircuitVoltageScaling.maximum) dict[ComponentType, DenseBatchArray]
calculate_short_circuit(*, calculation_method: CalculationMethod | str = CalculationMethod.iec60909, update_data: dict[ComponentTypeVar, _BatchComponentData] | list[dict[ComponentTypeVar, _BatchComponentData]] = None, threading: int = -1, output_component_types: ComponentAttributeFilterOptions = None, continue_on_batch_error: bool = False, decode_error: bool = True, short_circuit_voltage_scaling: ShortCircuitVoltageScaling | str = ShortCircuitVoltageScaling.maximum) dict[ComponentType, dict[AttributeTypeVar, BatchColumn]]
calculate_short_circuit(*, calculation_method: CalculationMethod | str = CalculationMethod.iec60909, update_data: dict[ComponentTypeVar, _BatchComponentData] | list[dict[ComponentTypeVar, _BatchComponentData]] = None, threading: int = -1, output_component_types: dict[ComponentType, set[AttributeTypeVar] | list[AttributeTypeVar] | None | ComponentAttributeFilterOptions] = None, continue_on_batch_error: bool = False, decode_error: bool = True, short_circuit_voltage_scaling: ShortCircuitVoltageScaling | str = ShortCircuitVoltageScaling.maximum) dict[ComponentType, DenseBatchArray | dict[AttributeTypeVar, BatchColumn]]

Calculate a short circuit once with the current model attributes. Or calculate in batch with the given update dataset in batch

Parameters:
  • calculation_method (an enumeration) – Use the iec60909 standard.

  • update_data

    None: calculate a short circuit once with the current model attributes.

    Or a dictionary for batch calculation with batch update

    • key: Component type name to be updated in batch

    • value:

      • For homogeneous update batch (a 2D numpy structured array):

        • Dimension 0: each batch

        • Dimension 1: each updated element per batch for this component type

      • For inhomogeneous update batch (a dictionary containing two keys):

    Or a list of such dictionaries (batch datasets) to represent multiple dimensions of cartesian product. The calculation core will interpret these datasets as a cartesian product of all the scenarios. Each batch dataset in the list represents one dimension of the cartesian product. The output will then have row size equal to the product of the batch sizes of all these datasets, in 1D flat structure. E.g., if you have three batch datasets with batch sizes 2, 3, and 4 respectively, and the number of nodes is 5, the final output for nodes will have shape (2*3*4, 5).

  • threading (int, optional) –

    Applicable only for batch calculation.

    • < 0: Sequential

    • = 0: Parallel, use number of hardware threads

    • > 0: Specify number of parallel threads

  • output_component_types (ComponentAttributeMapping) –

    • None: Row based data for all component types.

    • set[ComponentTypeVar] or list[ComponentTypeVar]: Row based data for the specified component types.

    • ComponentAttributeFilterOptions: Columnar data for all component types.

    • ComponentAttributeMappingDict:

      key: ComponentType value:

      • None: Row based data for the specified component types.

      • ComponentAttributeFilterOptions: Columnar data for the specified component types.

      • set[str] | list[str]: Columnar data for the specified component types and attributes.

  • continue_on_batch_error (bool, optional) – Continue the program (instead of throwing error) if some scenarios fail. You can still retrieve the errors and succeeded/failed scenarios via the batch_error.

  • decode_error (bool, optional) – Decode error messages to their derived types if possible.

  • short_circuit_voltage_scaling ({ShortCircuitVoltageSaling, str}, optional) – Whether to use the maximum or minimum voltage scaling. By default, the maximum voltage scaling is used to calculate the short circuit.

Returns:

Dictionary of results of all components.

  • key: Component type name to be updated in batch.

  • value:

    • For single calculation: 1D numpy structured array for the results of this component type.

    • For batch calculation: 2D numpy structured array for the results of this component type.

      • Dimension 0: Each batch.

      • Dimension 1: The result of each element for this component type.

Raises:

Exception – In case an error in the core occurs, an exception will be thrown.

power_grid_model.initialize_array(data_type: DatasetTypeLike, component_type: ComponentTypeLike, shape: int | tuple[int], empty: bool = False) SingleArray
power_grid_model.initialize_array(data_type: DatasetTypeLike, component_type: ComponentTypeLike, shape: tuple[int, int], empty: bool = False) DenseBatchArray

Initializes an array for use in Power Grid Model calculations

Parameters:
  • data_type – input, update, sym_output, or asym_output

  • component_type – one component type, e.g. node

  • shape – shape of initialization integer, it is a 1-dimensional array tuple, it is an N-dimensional (tuple.shape) array

  • empty – if True, leave the memory block un-initialized

Returns:

np structured array with all entries as null value

power_grid_model.attribute_dtype(data_type: DatasetTypeLike, component_type: ComponentTypeLike, attribute: AttributeTypeLike) dtype

Gives out dtype of the attribute to be used in a columnar data format

Parameters:
  • data_type (DatasetTypeLike) – The type of dataset (input, update, sym_output, or asym_output)

  • component_type (ComponentTypeLike) – The type of component (e.g., node)

  • attribute (AttributeTypeLike) – The attribute whose dtype is required

Returns:

The dtype of the specified attribute

Return type:

np.dtype

power_grid_model.attribute_empty_value(data_type: DatasetTypeLike, component_type: ComponentTypeLike, attribute: AttributeTypeLike) ndarray

Returns the empty value for a specific attribute in the Power Grid Model.

Parameters:
  • data_type (DatasetTypeLike) – The type of dataset (input, update, sym_output, or asym_output)

  • component_type (ComponentTypeLike) – The type of component (e.g., node)

  • attribute (AttributeTypeLike) – The attribute whose empty value is required

Returns:

The empty value for the specified attribute

Return type:

np.ndarray

power_grid_model.power_grid_meta_data: PowerGridMetaData

The data types for all dataset types and components used by the Power Grid Model.

enum

Common enumerations used by the power-grid-model library.

Note: these enumeration match the C++ arithmetic core, so don’t change the values unless you change them in C++ as well

class power_grid_model.enum.AngleMeasurementType(*values)

Bases: IntEnum

The type of the angle measurement for current sensors.

local_angle = 0

The angle is relative to the local voltage angle

global_angle = 1

The angle is relative to the global voltage angle.

class power_grid_model.enum.Branch3Side(*values)

Bases: IntEnum

Branch3 Sides

side_1 = 0
side_2 = 1
side_3 = 2
class power_grid_model.enum.BranchSide(*values)

Bases: IntEnum

Branch Sides

from_side = 0
to_side = 1
class power_grid_model.enum.CalculationMethod(*values)

Bases: IntEnum

Calculation Methods

linear = 0
newton_raphson = 1
iterative_linear = 2
iterative_current = 3
linear_current = 4
iec60909 = 5
class power_grid_model.enum.CalculationType(*values)

Bases: IntEnum

Calculation Types

power_flow = 0
state_estimation = 1
short_circuit = 2
class power_grid_model.enum.ComponentAttributeFilterOptions(*values)

Bases: IntEnum

Filter option component or attribute

everything = 0

Filter all components/attributes

relevant = 1

Filter only non-empty components/attributes that contain non-NaN values

class power_grid_model.enum.FaultPhase(*values)

Bases: IntEnum

The faulty phase(s) affected by the provided fault type

abc = 0

All phases are faulty in a three-phase fault

a = 1

The first phase is faulty in a single-phase-to-ground fault

b = 2

The second phase is faulty in a single-phase-to-ground fault

c = 3

The third phase is faulty in a single-phase-to-ground fault

ab = 4

The first and second phase are faulty in a two-phase or two-phase-to-ground fault

ac = 5

The first and third phase are faulty in a two-phase or two-phase-to-ground fault

bc = 6

The second and third phase are faulty in a two-phase or two-phase-to-ground fault

default_value = -1

Use the default fault phase. Depends on the fault_type.

nan = -128

Unspecified fault phase. Needs to be overloaded at the latest in the update_data

class power_grid_model.enum.FaultType(*values)

Bases: IntEnum

The type of fault represented by a fault component

three_phase = 0
single_phase_to_ground = 1
two_phase = 2
two_phase_to_ground = 3
nan = -128

Unspecified fault type. Needs to be overloaded at the latest in the update_data

class power_grid_model.enum.LoadGenType(*values)

Bases: IntEnum

Load and Generator Types

const_power = 0
const_impedance = 1
const_current = 2
class power_grid_model.enum.MeasuredTerminalType(*values)

Bases: IntEnum

The type of asset measured by a (power) sensor.

NOTE: MeasuredTerminalType.node is deprecated and will be removed in a future release. The reason for deprecation is that, contrary to the other terminal types, it does not represent a real terminal. It is a fundamentally different concept that can lead to confusion and errors. Please use one of the other terminal types instead.

branch_from = 0

Measuring the from-terminal between a branch (except link) and a node

branch_to = 1

Measuring the to-terminal between a branch (except link) and a node

source = 2

Measuring the terminal between a source and a node

shunt = 3

Measuring the terminal between a shunt and a node

load = 4

Measuring the terminal between a load and a node

generator = 5

Measuring the terminal between a generator and a node

branch3_1 = 6

Measuring the terminal-1 between a branch3 and a node

branch3_2 = 7

Measuring the terminal-2 between a branch3 and a node

branch3_3 = 8

Measuring the terminal-3 between a branch3 and a node

node = 9

[DEPRECATED] Measuring the total power injection into a node

class power_grid_model.enum.ShortCircuitVoltageScaling(*values)

Bases: IntEnum

Voltage scaling for short circuit calculations

minimum = 0
maximum = 1
class power_grid_model.enum.TapChangingStrategy(*values)

Bases: IntEnum

Tap Changing Strategies

disabled = 0

Disable automatic tap adjustment

any_valid_tap = 1

Adjust tap position automatically; optimize for any value in the voltage band

min_voltage_tap = 2

Adjust tap position automatically; optimize for the lower end of the voltage band

max_voltage_tap = 3

Adjust tap position automatically; optimize for the higher end of the voltage band

fast_any_tap = 4

Adjust tap position automatically; optimize for any value in the voltage band; binary search

class power_grid_model.enum.WindingType(*values)

Bases: IntEnum

Transformer Winding Types

wye = 0

Star connection without an explicit neutral reference. This winding does not provide a connection to neutral/ground.

wye_n = 1

Star connection with an explicit neutral reference. This winding provides a connection to neutral/ground.

delta = 2

Delta connection. This winding does not provide a connection to neutral/ground.

zigzag = 3

Zigzag/Interconnected connection. This winding does not provide a connection to neutral/ground

zigzag_n = 4

Zigzag/Interconnected connection with neutral. This winding provides a reference to neutral/ground.

data types

Data types involving PGM datasets.

Many data types are used throughout the power grid model project. In an attempt to clarify type hints, some types are defined/exposed and explained.

class power_grid_model.data_types.SparseBatchArray

Bases: TypedDict

A sparse batch array is a dictionary containing the keys indptr and data.

  • data: a SingleArray. The exact dtype depends on the type of component.

  • indptr: an IndexPointer representing the start and end indices for each batch scenario.

  • Examples:

    • structure: {“indptr”: IndexPointer, “data”: SingleArray}

    • concrete example: {“indptr”: [0, 2, 2, 3], “data”: [(0, 1, 1), (1, 1, 1), (0, 0, 0)]}

      • the scenario 0 sets the statuses of components with ids 0 and 1 to 1 (and keeps defaults for other components)

      • scenario 1 keeps the default values for all components

      • scenario 2 sets the statuses of component with id 0 to 0 (and keeps defaults for other components)

indptr: IndexPointer
data: SingleArray
class power_grid_model.data_types.SparseBatchColumnarData

Bases: TypedDict

Sparse batch columnar data is a dictionary containing the keys indptr and data.

  • data: a SingleColumnarData. The exact supported attribute columns depend on the component type.

  • indptr: an IndexPointer representing the start and end indices for each batch scenario.

  • Examples:

    • structure: {“indptr”: IndexPointer, “data”: SingleColumnarData}

    • concrete example: {“indptr”: [0, 2, 2, 3], “data”: {“id”: [0, 1, 0], “status”: [1, 1, 0]}}

      • the scenario 0 sets the status of components with ids 0 and 1 to 1 (and keeps defaults for other components)

      • scenario 1 keeps the default values for all components

      • scenario 2 sets the status of component with id 0 to 0 (and keeps defaults for other components)

indptr: IndexPointer
data: dict[AttributeTypeVar, SingleColumn]
power_grid_model.data_types.BatchArray = DenseBatchArray | power_grid_model._core.data_types.SparseBatchArray

A batch array is a either a DenseBatchArray or a SparseBatchArray.

type power_grid_model.data_types.BatchColumn = ndarray

A batch column is a two-dimensional structured numpy array containing a list of the same attribute of multiple components of the same type. Otherwise, similar to SingleColumn.

power_grid_model.data_types.BatchColumnarData = dict[~AttributeTypeVar, BatchColumn] | power_grid_model._core.data_types.SparseBatchColumnarData

Batch columnar data is either a DenseBatchColumnarData or a SparseBatchColumnarData.

power_grid_model.data_types.BatchComponentData = DenseBatchArray | power_grid_model._core.data_types.SparseBatchArray | dict[~AttributeTypeVar, BatchColumn] | power_grid_model._core.data_types.SparseBatchColumnarData

Batch component data can be BatchArray or BatchColumnarData.

power_grid_model.data_types.BatchDataset

A batch dataset is a dictionary where the keys are the component types and the values are BatchComponentData

alias of dict[ComponentTypeVar, _BatchComponentData]

power_grid_model.data_types.ColumnarData = dict[~AttributeTypeVar, SingleColumn] | dict[~AttributeTypeVar, BatchColumn] | power_grid_model._core.data_types.SparseBatchColumnarData

Columnar data can be SingleColumnarData or BatchColumnarData.

power_grid_model.data_types.ComponentData = SingleArray | DenseBatchArray | power_grid_model._core.data_types.SparseBatchArray | dict[~AttributeTypeVar, SingleColumn] | dict[~AttributeTypeVar, BatchColumn] | power_grid_model._core.data_types.SparseBatchColumnarData

Component data can be DataArray or ColumnarData.

power_grid_model.data_types.DataArray = SingleArray | DenseBatchArray | power_grid_model._core.data_types.SparseBatchArray

A data array can be a SingleArray or a BatchArray.

power_grid_model.data_types.Dataset

A general data set can be a SingleDataset or a BatchDataset.

alias of dict[ComponentTypeVar, _ComponentData]

type power_grid_model.data_types.DenseBatchArray = ndarray

A dense batch array is a two-dimensional structured numpy array containing a list of components of the same type for each scenario. Otherwise similar to SingleArray.

power_grid_model.data_types.DenseBatchColumnarData

Batch columnar data is a dictionary where the keys are the attribute types of the same component and the values are BatchColumn.

alias of dict[AttributeTypeVar, BatchColumn]

power_grid_model.data_types.DenseBatchData = DenseBatchArray | dict[~AttributeTypeVar, BatchColumn]

Dense batch data can be a DenseBatchArray or a DenseBatchColumnarData.

type power_grid_model.data_types.IndexPointer = ndarray

An index pointer is a one-dimensional numpy int64 array containing n+1 elements where n is the amount of scenarios, representing the start and end indices for each batch scenario as follows:

  • The elements are the indices in the data that point to the first element of that scenario.

  • The last element is one after the data index of the last element of the last scenario.

  • The first element and last element will therefore be 0 and the size of the data, respectively.

type power_grid_model.data_types.SingleArray = ndarray

A single array is a one-dimensional structured numpy array containing a list of components of the same type.

  • Examples:

    • structure: <1d-array>

    • concrete: array(

      [(0, 10500.0), (0, 10500.0)], dtype=power_grid_meta_data[DatasetType.input][ComponentType.node].dtype

      )

type power_grid_model.data_types.SingleColumn = ndarray

A single column is a one-dimensional structured numpy array containing a list of the same attribute of multiple components of the same type.

  • Examples:

    • structure: <1d-array>

    • concrete:

      • array( [0, 1], dtype=power_grid_meta_data[DatasetType.input][ComponentType.node].dtype.fields[AttributeType.id][0]

      ) - array(

      [10500.0, 10500.0], dtype=power_grid_meta_data[DatasetType.input][ComponentType.node].dtype.fields[AttributeType.u_rated][0]

      )

power_grid_model.data_types.SingleColumnarData

Single columnar data is a dictionary where the keys are the attribute types of the same component and the values are SingleColumn.

alias of dict[AttributeTypeVar, SingleColumn]

power_grid_model.data_types.SingleComponentData = SingleArray | dict[~AttributeTypeVar, SingleColumn]

Single component data can be SingleArray or SingleColumnarData.

power_grid_model.data_types.SingleDataset

A single dataset is a dictionary where the keys are the component types and the values are ComponentData

alias of dict[ComponentTypeVar, _SingleComponentData]

power_grid_model.data_types.SparseBatchData = power_grid_model._core.data_types.SparseBatchArray | power_grid_model._core.data_types.SparseBatchColumnarData

Sparse batch data can be a SparseBatchArray or a SparseBatchColumnarData.

type power_grid_model.data_types.SparseDataComponentType = str

A string representing the component type of sparse data structures.

Must be either “data” or “indptr”.

error types

Error classes used by the power-grid-model library.

exception power_grid_model.errors.AutomaticTapCalculationError

Bases: PowerGridError

Automatic tap changer with tap at LV side is unsupported for automatic tap changing calculation.

exception power_grid_model.errors.AutomaticTapInputError

Bases: PowerGridError

Automatic tap changer has invalid configuration.

exception power_grid_model.errors.ConflictID

Bases: InvalidID

Conflicting IDs found.

exception power_grid_model.errors.ConflictingAngleMeasurementType

Bases: PowerGridError

Conflicting angle measurement types found.

exception power_grid_model.errors.ConflictVoltage

Bases: PowerGridError

There is a confliciting voltage

exception power_grid_model.errors.ExperimentalFeature

Bases: PowerGridError

An experimental feature was used but experimental features are not enabled.

exception power_grid_model.errors.IDNotFound

Bases: InvalidID

A reference to a non-existent ID was provided.

exception power_grid_model.errors.IDWrongType

Bases: InvalidID

A referenced ID points to a component that cannot be referenced here.

exception power_grid_model.errors.InvalidArguments

Bases: PowerGridError

A (combination of) input arguments is not valid.

exception power_grid_model.errors.InvalidBranch(*args, **kwargs)

Bases: PowerGridError

A branch is invalid.

[DEPRECATED] This error is no longer relevant and may be reduced in a future release.

__init__(*args, **kwargs)
exception power_grid_model.errors.InvalidBranch3(*args, **kwargs)

Bases: PowerGridError

A branch3 is invalid.

[DEPRECATED] This error is no longer relevant and may be reduced in a future release.

__init__(*args, **kwargs)
exception power_grid_model.errors.InvalidCalculationMethod

Bases: PowerGridError

Invalid calculation method provided.

exception power_grid_model.errors.InvalidID

Bases: PowerGridError

An ID is invalid.

exception power_grid_model.errors.InvalidMeasuredObject

Bases: InvalidID

A provided measured object is invalid.

exception power_grid_model.errors.InvalidRegulatedObject

Bases: InvalidID

A provided regulated object is invalid.

exception power_grid_model.errors.InvalidShortCircuitPhaseOrType

Bases: PowerGridError

Invalid (combination of) short circuit types and phase(s) provided.

exception power_grid_model.errors.InvalidTransformerClock

Bases: PowerGridError

Invalid transformer clock found.

exception power_grid_model.errors.IterationDiverge

Bases: PowerGridError

Unable to iteratively converge to an optimum within the set number of iterations and precision.

exception power_grid_model.errors.MaxIterationReached

Bases: IterationDiverge

Maximum number of iterations reached.

exception power_grid_model.errors.MissingCaseForEnumError

Bases: InvalidArguments

An enum value is not covered in a for loop.

This usually happens when an invalid combination of (enum) settings is provided.

exception power_grid_model.errors.NotObservableError

Bases: SparseMatrixError

Attempting to solve a non-observable system.

exception power_grid_model.errors.PowerGridBatchError

Bases: PowerGridError

Error occurs in batch calculation.

failed_scenarios: ndarray
succeeded_scenarios: ndarray
error_messages: list[str]
errors: list[PowerGridError]
exception power_grid_model.errors.PowerGridDatasetError

Bases: PowerGridError

Error occurs during dataset handling.

exception power_grid_model.errors.PowerGridError

Bases: RuntimeError

Generic power grid error.

exception power_grid_model.errors.PowerGridNotImplementedError

Bases: PowerGridError

The functionality is either not supported or not yet implemented.

exception power_grid_model.errors.PowerGridSerializationError

Bases: PowerGridError

Error occurs during (de-)serialization.

exception power_grid_model.errors.PowerGridUnreachableHitError

Bases: PowerGridError

Supposedly unreachable code was hit.

This usually means a failed assumption and may be caused by a bug in the PGM library.

exception power_grid_model.errors.SparseMatrixError

Bases: PowerGridError

Attempting to invert a non-invertible matrix.

exception power_grid_model.errors.UnsupportedRegulatorCombinationError

Bases: PowerGridError

The combination of voltage regulators and transformer tap regulators is not supported in the same model.

exception power_grid_model.errors.UnsupportedVoltageRegulatorSourceCombinationError

Bases: PowerGridError

Nodes with a source and a voltage regulated load/generator are not supported when both are enabled.

typing

Type hints for the power-grid-model library.

This includes all miscellaneous type hints not under dataset or categories.

class power_grid_model.typing.DatasetType(*values)

A DatasetType is the type of a Dataset in power grid model.

  • Examples:

    • DatasetType.input = “input”

    • DatasetType.update = “update”

input = 'input'
sym_output = 'sym_output'
asym_output = 'asym_output'
update = 'update'
sc_output = 'sc_output'
class power_grid_model.typing.DatasetTypeVar

alias of TypeVar(‘DatasetTypeVar’, bound=DatasetTypeLike)

class power_grid_model.typing.ComponentType(*values)

A ComponentType is the type of a grid component.

  • Examples:

    • ComponentType.node = “node”

    • ComponentType.line = “line”

node = 'node'
line = 'line'
asym_line = 'asym_line'
generic_branch = 'generic_branch'
transformer = 'transformer'
transformer_tap_regulator = 'transformer_tap_regulator'
three_winding_transformer = 'three_winding_transformer'
sym_load = 'sym_load'
sym_gen = 'sym_gen'
asym_load = 'asym_load'
asym_gen = 'asym_gen'
voltage_regulator = 'voltage_regulator'
shunt = 'shunt'
source = 'source'
sym_voltage_sensor = 'sym_voltage_sensor'
asym_voltage_sensor = 'asym_voltage_sensor'
sym_power_sensor = 'sym_power_sensor'
asym_power_sensor = 'asym_power_sensor'
sym_current_sensor = 'sym_current_sensor'
asym_current_sensor = 'asym_current_sensor'
fault = 'fault'
class power_grid_model.typing.ComponentTypeVar

alias of TypeVar(‘ComponentTypeVar’, bound=ComponentTypeLike)

class power_grid_model.typing.ComponentMetaData(dtype: dtype, dtype_dict: dict[AttributeTypeLike, Any], nans: dict[AttributeTypeLike, float | int], nan_scalar: ndarray)

Data class for component metadata

dtype: dtype
dtype_dict: dict[AttributeTypeLike, Any]
nans: dict[AttributeTypeLike, float | int]
nan_scalar: ndarray
__init__(dtype: dtype, dtype_dict: dict[AttributeTypeLike, Any], nans: dict[AttributeTypeLike, float | int], nan_scalar: ndarray) None
power_grid_model.typing.DatasetMetaData

alias of dict[ComponentTypeVar, ComponentMetaData]

power_grid_model.typing.PowerGridMetaData

alias of dict[DatasetType, dict[ComponentTypeVar, ComponentMetaData]]

power_grid_model.typing.ComponentAttributeMapping ComponentAttributeMapping

Type hint for mapping component attributes.

ComponentAttributeMapping can be one of the following:

validation

power_grid_model.validation.validate_input_data(input_data: dict[ComponentTypeVar, _SingleComponentData], calculation_type: CalculationType | None = None, symmetric: bool = True) list[ValidationError] | None

Validates the entire input dataset:

  1. Is the data structure correct? (checking data types and numpy array shapes)

  2. Are all required values provided? (checking NaNs)

  3. Are all ID’s unique? (checking object identifiers across all components)

  4. Are the supplied values valid? (checking limits and other logic as described in “Graph Data Model”)

Parameters:
  • input_data – A power-grid-model input dataset

  • calculation_type – Supply a calculation method, to allow missing values for unused fields

  • symmetric – A boolean to state whether input data will be used for a symmetric or asymmetric calculation

Returns:

None if the data is valid, or a list containing all validation errors.

Raises:

Error – KeyError | TypeError | ValueError: if the data structure is invalid.

power_grid_model.validation.validate_batch_data(input_data: dict[ComponentTypeVar, _SingleComponentData], update_data: dict[ComponentTypeVar, _BatchComponentData], calculation_type: CalculationType | None = None, symmetric: bool = True) dict[int, list[ValidationError]] | None

The input dataset is validated:

  1. Is the data structure correct? (checking data types and numpy array shapes)

  2. Are all input data ID’s unique? (checking object identifiers across all components)

For each batch the update data is validated:
  1. Is the update data structure correct? (checking data types and numpy array shapes)

  2. Are all update ID’s valid? (checking object identifiers across update and input data)

Then (for each batch independently) the input dataset is updated with the batch’s update data and validated:
  1. Are all required values provided? (checking NaNs)

  2. Are the supplied values valid? (checking limits and other logic as described in “Graph Data Model”)

Parameters:
  • input_data – A power-grid-model input dataset

  • update_data – A power-grid-model update dataset (one or more batches)

  • calculation_type – Supply a calculation method, to allow missing values for unused fields

  • symmetric – A boolean to state whether input data will be used for a symmetric or asymmetric calculation

Returns:

None if the data is valid, or a dictionary containing all validation errors, where the key is the batch number (0-indexed).

Raises:

Error – KeyError | TypeError | ValueError: if the data structure is invalid.

power_grid_model.validation.assert_valid_input_data(input_data: dict[ComponentTypeVar, _SingleComponentData], calculation_type: CalculationType | None = None, symmetric: bool = True)

Validates the entire input dataset:

  1. Is the data structure correct? (checking data types and numpy array shapes)

  2. Are all required values provided? (checking NaNs)

  3. Are all ID’s unique? (checking object identifiers across all components)

  4. Are the supplied values valid? (checking limits and other logic as described in “Graph Data Model”)

Parameters:
  • input_data – A power-grid-model input dataset

  • calculation_type – Supply a calculation method, to allow missing values for unused fields

  • symmetric – A boolean to state whether input data will be used for a symmetric or asymmetric calculation

Raises:
  • KeyError | TypeError | ValueError – if the data structure is invalid.

  • ValidationException – if the contents are invalid.

power_grid_model.validation.assert_valid_batch_data(input_data: dict[ComponentTypeVar, _SingleComponentData], update_data: dict[ComponentTypeVar, _BatchComponentData], calculation_type: CalculationType | None = None, symmetric: bool = True)

The input dataset is validated:

  1. Is the data structure correct? (checking data types and numpy array shapes)

  2. Are all input data ID’s unique? (checking object identifiers across all components)

For each batch the update data is validated:
  1. Is the update data structure correct? (checking data types and numpy array shapes)

  2. Are all update ID’s valid? (checking object identifiers across update and input data)

Then (for each batch independently) the input dataset is updated with the batch’s update data and validated:
  1. Are all required values provided? (checking NaNs)

  2. Are the supplied values valid? (checking limits and other logic as described in “Graph Data Model”)

Parameters:
  • input_data – a power-grid-model input dataset

  • update_data – a power-grid-model update dataset (one or more batches)

  • calculation_type – Supply a calculation method, to allow missing values for unused fields

  • symmetric – A boolean to state whether input data will be used for a symmetric or asymmetric calculation

Raises:
  • KeyError | TypeError | ValueError – if the data structure is invalid.

  • ValidationException – if the contents are invalid.

power_grid_model.validation.assert_valid_data_structure(data: dict[ComponentTypeVar, _ComponentData], data_type: DatasetType) None

Checks if all component names are valid and if the data inside the component matches the required Numpy structured array as defined in the Power Grid Model meta data.

Parameters:
  • data – A power-grid-model input/update dataset

  • data_type – ‘input’ or ‘update’

Raises:

Error – KeyError, TypeError

power_grid_model.validation.errors_to_string(errors: list[ValidationError] | dict[int, list[ValidationError]] | None, name: str = 'the data', details: bool = False, id_lookup: list[str] | dict[int, str] | None = None) str

Convert a set of errors (list or dict) to a human readable string representation.

Parameters:
  • errors – The error objects. List for input_data only, dict for batch data.

  • name – Human understandable name of the dataset, e.g. input_data, or update_data.

  • details – Display object ids and error specific information.

  • id_lookup – A list or dict (int->str) containing textual object ids

Returns:

A human readable string representation of a set of errors.

class power_grid_model.validation.ValidationException(errors: list[ValidationError] | dict[int, list[ValidationError]], name: str = 'data')

An exception storing the name of the validated data, a list/dict of errors and a convenient conversion to string to display a summary of all the errors when printing the exception.

__init__(errors: list[ValidationError] | dict[int, list[ValidationError]], name: str = 'data')

validation errors

Error classes

class power_grid_model.validation.errors.ValidationError

Bases: ABC

The Validation Error is an abstract base class which should be extended by all validation errors. It supplies three public member variables: component, field and ids; storing information about the origin of the validation error. Error classes can extend the public members. For example:

NotBetweenError(ValidationError):

component = ‘vehicle’ field = ‘direction’ id = [3, 14, 15, 92, 65, 35] ref_value = (-3.1416, 3.1416)

For convenience, a human readable representation of the error is supplied using the str() function. I.e. print(str(error)) will print a human readable error message like:

Field direction is not between -3.1416 and 3.1416 for 6 vehicles

component: ComponentType | list[ComponentType] | None = None

The component, or components, to which the error applies.

field: AttributeType | list[AttributeType] | list[tuple[ComponentType, AttributeType]] | None = None

The field, or fields, to which the error applies. A field can also be a tuple (component, field) when multiple components are being addressed.

ids: list[int] | list[tuple[ComponentType, int]] | None = None

The object identifiers to which the error applies. A field object identifier can also be a tuple (component, id) when multiple components are being addressed.

property component_str: str

A string representation of the component to which this error applies

property field_str: str

A string representation of the field to which this error applies

get_context(id_lookup: list[str] | dict[int, str] | None = None) dict[str, Any]

Returns a dictionary that supplies (human readable) information about this error. Each member variable is included in the dictionary. If a function {field_name}_str() exists, the value is overwritten by that function.

Parameters:

id_lookup – A list or dict (int->str) containing textual object ids

class power_grid_model.validation.errors.SingleFieldValidationError(component: ComponentType, field: AttributeType, ids: Iterable[int] | None)

Bases: ValidationError

Base class for an error that applies to a single field in a single component

__init__(component: ComponentType, field: AttributeType, ids: Iterable[int] | None)
Parameters:
  • component – Component name

  • field – Field name

  • ids – List of component IDs (not row indices)

class power_grid_model.validation.errors.MultiFieldValidationError(component: ComponentType, fields: list[AttributeType], ids: list[int])

Bases: ValidationError

Base class for an error that applies to multiple fields in a single component

__init__(component: ComponentType, fields: list[AttributeType], ids: list[int])
Parameters:
  • component – Component name

  • fields – List of field names

  • ids – List of component IDs (not row indices)

class power_grid_model.validation.errors.MultiComponentValidationError(fields: list[tuple[ComponentType, AttributeType]], ids: list[tuple[ComponentType, int]])

Bases: ValidationError

Base class for an error that applies to multiple components, and, subsequently, multiple fields. Even if both fields have the same name, they are considered to be different fields and notated as such. E.g. the two fields id fields of the node and line component: [(‘node’, ‘id’), (‘line’, ‘id’)].

__init__(fields: list[tuple[ComponentType, AttributeType]], ids: list[tuple[ComponentType, int]])
Parameters:
  • fields – List of field names, formatted as tuples (component, field)

  • ids – List of component IDs (not row indices), formatted as tuples (component, id)

class power_grid_model.validation.errors.NotIdenticalError(component: ComponentType, field: AttributeType, ids: Iterable[int], values: list[Any])

Bases: SingleFieldValidationError

The value is not unique within a single column in a dataset E.g. When two nodes share the same id.

__init__(component: ComponentType, field: AttributeType, ids: Iterable[int], values: list[Any])
Parameters:
  • component – Component name

  • field – Field name

  • ids – List of component IDs (not row indices)

values: list[Any]
unique: set[Any]
num_unique: int
class power_grid_model.validation.errors.NotUniqueError(component: ComponentType, field: AttributeType, ids: Iterable[int] | None)

Bases: SingleFieldValidationError

The value is not unique within a single column in a dataset E.g. When two nodes share the same id.

class power_grid_model.validation.errors.MultiComponentNotUniqueError(fields: list[tuple[ComponentType, AttributeType]], ids: list[tuple[ComponentType, int]])

Bases: MultiComponentValidationError

The value is not unique between multiple columns in multiple components E.g. When a node and a line share the same id.

class power_grid_model.validation.errors.InvalidValueError(component: ComponentType, field: AttributeType, ids: list[int], values: list)

Bases: SingleFieldValidationError

The value is not a valid value in the supplied list of supported values. E.g. an enum value that is not supported for a specific feature.

__init__(component: ComponentType, field: AttributeType, ids: list[int], values: list)
Parameters:
  • component – Component name

  • field – Field name

  • ids – List of component IDs (not row indices)

values: list
property values_str: str

A string representation of the field to which this error applies.

class power_grid_model.validation.errors.InvalidEnumValueError(component: ComponentType, field: AttributeType, ids: list[int], enum: type[Enum] | list[type[Enum]])

Bases: SingleFieldValidationError

The value is not a valid value in the supplied enumeration type. E.g. a sym_load has a non existing LoadGenType.

__init__(component: ComponentType, field: AttributeType, ids: list[int], enum: type[Enum] | list[type[Enum]])
Parameters:
  • component – Component name

  • field – Field name

  • ids – List of component IDs (not row indices)

enum: type[Enum] | list[type[Enum]]
property enum_str: str

A string representation of the field to which this error applies.

class power_grid_model.validation.errors.SameValueError(component: ComponentType, fields: list[AttributeType], ids: list[int])

Bases: MultiFieldValidationError

The value of two fields is equal. E.g. A line has the same from_node as to_node.

class power_grid_model.validation.errors.NotBooleanError(component: ComponentType, field: AttributeType, ids: Iterable[int] | None)

Bases: SingleFieldValidationError

Invalid boolean value. Boolean fields don’t really exist in our data structure, they are 1-byte signed integers and should contain either a 0 (=False) or a 1 (=True).

class power_grid_model.validation.errors.MissingValueError(component: ComponentType, field: AttributeType, ids: Iterable[int] | None)

Bases: SingleFieldValidationError

A required value was missing, i.e. NaN.

class power_grid_model.validation.errors.IdNotInDatasetError(component: ComponentType, ids: list[int], ref_dataset: DatasetType)

Bases: SingleFieldValidationError

An object identifier does not exist in the original data. E.g. An update data set contains a record for a line that doesn’t exist in the input data set.

__init__(component: ComponentType, ids: list[int], ref_dataset: DatasetType)
Parameters:
  • component – Component name

  • field – Field name

  • ids – List of component IDs (not row indices)

ref_dataset: DatasetType
class power_grid_model.validation.errors.InvalidIdError(component: ComponentType, field: AttributeType, ids: list[int] | None = None, ref_components: ComponentType | list[ComponentType] | None = None, filters: dict[str, Any] | None = None)

Bases: SingleFieldValidationError

An object identifier does not refer to the right type of object. E.g. An line’s from_node refers to a source.

Filters can have been applied to check a subset of the records. E.g. This error may apply only to power_sensors that are said to be connected to a source (filter: measured_terminal_type=source). This useful to spot validation mistakes, due to ambiguity.

E.g. when a sym_power_sensor is connected to a load, but measured_terminal_type is accidentally set to ‘source’, the error is:

“Field measured_object does not contain a valid source id for 1 sym_power_sensor. (measured_terminal_type=source)”

__init__(component: ComponentType, field: AttributeType, ids: list[int] | None = None, ref_components: ComponentType | list[ComponentType] | None = None, filters: dict[str, Any] | None = None)
Parameters:
  • component – Component name

  • field – Field name

  • ids – List of component IDs (not row indices)

ref_components: list[ComponentType]
property ref_components_str

A string representation of the components to which this error applies

property filters_str

A string representation of the filters that have been applied to the data to which this error refers

class power_grid_model.validation.errors.TwoValuesZeroError(component: ComponentType, fields: list[AttributeType], ids: list[int])

Bases: MultiFieldValidationError

A record has a 0.0 value in two fields at the same time. E.g. A line’s r1, x1 are both 0.

class power_grid_model.validation.errors.ComparisonError(component: ComponentType, field: AttributeType, ids: list[int], ref_value: int | float | str | tuple[int | float | str, ...])

Bases: SingleFieldValidationError

Base class for comparison errors. E.g. A transformer’s i0 is not greater or equal to it’s p0 divided by it’s sn

RefType = int | float | str | tuple[int | float | str, ...]
__init__(component: ComponentType, field: AttributeType, ids: list[int], ref_value: int | float | str | tuple[int | float | str, ...])
Parameters:
  • component – Component name

  • field – Field name

  • ids – List of component IDs (not row indices)

property ref_value_str

A string representation of the reference value. E.g. ‘zero’, ‘one’, ‘field_a and field_b’ or ‘123’.

class power_grid_model.validation.errors.NotGreaterThanError(component: ComponentType, field: AttributeType, ids: list[int], ref_value: int | float | str | tuple[int | float | str, ...])

Bases: ComparisonError

The value of a field is not greater than a reference value or expression.

class power_grid_model.validation.errors.NotGreaterOrEqualError(component: ComponentType, field: AttributeType, ids: list[int], ref_value: int | float | str | tuple[int | float | str, ...])

Bases: ComparisonError

The value of a field is not greater or equal to a reference value or expression.

class power_grid_model.validation.errors.NotLessThanError(component: ComponentType, field: AttributeType, ids: list[int], ref_value: int | float | str | tuple[int | float | str, ...])

Bases: ComparisonError

The value of a field is not less than a reference value or expression.

class power_grid_model.validation.errors.NotLessOrEqualError(component: ComponentType, field: AttributeType, ids: list[int], ref_value: int | float | str | tuple[int | float | str, ...])

Bases: ComparisonError

The value of a field is not smaller or equal to a reference value or expression.

class power_grid_model.validation.errors.NotBetweenError(component: ComponentType, field: AttributeType, ids: list[int], ref_value: int | float | str | tuple[int | float | str, ...])

Bases: ComparisonError

The value of a field is not between two a reference values or expressions (exclusive).

class power_grid_model.validation.errors.NotBetweenOrAtError(component: ComponentType, field: AttributeType, ids: list[int], ref_value: int | float | str | tuple[int | float | str, ...])

Bases: ComparisonError

The value of a field is not between two a reference values or expressions (inclusive).

class power_grid_model.validation.errors.InfinityError(component: ComponentType, field: AttributeType, ids: Iterable[int] | None)

Bases: SingleFieldValidationError

The value of a field is infinite.

class power_grid_model.validation.errors.TransformerClockError(component: ComponentType, fields: list[AttributeType], ids: list[int])

Bases: MultiFieldValidationError

Invalid clock number.

class power_grid_model.validation.errors.FaultPhaseError(component: ComponentType, fields: list[AttributeType], ids: list[int])

Bases: MultiFieldValidationError

The fault phase does not match the fault type.

class power_grid_model.validation.errors.PQSigmaPairError(component: ComponentType, fields: list[AttributeType], ids: list[int])

Bases: MultiFieldValidationError

The combination of p_sigma and q_sigma is not valid. They should be both present or both absent.

class power_grid_model.validation.errors.InvalidAssociatedEnumValueError(component: ComponentType, fields: list[AttributeType], ids: list[int], enum: type[Enum] | list[type[Enum]])

Bases: MultiFieldValidationError

The value is not a valid value in combination with the other specified attributes. E.g. When a transformer tap regulator has a branch3 control side but regulates a transformer.

__init__(component: ComponentType, fields: list[AttributeType], ids: list[int], enum: type[Enum] | list[type[Enum]])
Parameters:
  • component – Component name

  • fields – List of field names

  • ids – List of component IDs (not row indices)

  • enum – The supported enum values

enum: type[Enum] | list[type[Enum]]
property enum_str: str

A string representation of the field to which this error applies.

class power_grid_model.validation.errors.InvalidVoltageRegulationError(component: ComponentType, field: AttributeType, ids: Iterable[int] | None)

Bases: SingleFieldValidationError

U_ref values for voltage regulators connected to the same node are not identical.

class power_grid_model.validation.errors.UnsupportedMeasuredTerminalType(component: ComponentType, field: AttributeType, ids: list[int], values: list)

Bases: InvalidValueError

The measured terminal type is not a supported value.

Supported values are in the supplied list of values.

class power_grid_model.validation.errors.MixedCurrentAngleMeasurementTypeError(component: ComponentType, fields: list[AttributeType], ids: list[int])

Bases: MultiFieldValidationError

Mixed current angle measurement type error.

class power_grid_model.validation.errors.MixedPowerCurrentSensorError(fields: list[tuple[ComponentType, AttributeType]], ids: list[tuple[ComponentType, int]])

Bases: MultiComponentValidationError

Mixed power and current sensor error.

class power_grid_model.validation.errors.MissingVoltageAngleMeasurementError(fields: list[tuple[ComponentType, AttributeType]], ids: list[tuple[ComponentType, int]])

Bases: MultiComponentValidationError

Missing voltage angle measurement error.

utils

power_grid_model.utils.get_dataset_type(data: dict[ComponentTypeVar, _ComponentData]) DatasetType

Deduce the dataset type from the provided dataset.

Parameters:

data – the dataset

Raises:
  • ValueError – if the dataset type cannot be deduced because multiple dataset types match the format (probably because the data contained no supported components, e.g. was empty)

  • PowerGridError – if no dataset type matches the format of the data (probably because the data contained conflicting data formats)

Returns:

The dataset type.

power_grid_model.utils.get_dataset_scenario(dataset: dict[ComponentTypeVar, _BatchComponentData], scenario: int) dict[ComponentTypeVar, _SingleComponentData]

Obtain the single dataset at a given scenario, independently of the internal batch data structure.

Parameters:
  • dataset – the batch dataset

  • scenario – the scenario index

Raises:

IndexError – if the scenario is out of range for any of the components.

Returns:

The dataset for a specific scenario

power_grid_model.utils.get_dataset_batch_size(dataset: dict[ComponentTypeVar, _BatchComponentData]) int

Get the number of scenarios in the batch dataset.

Parameters:

dataset – the batch dataset

Raises:

ValueError – if the batch dataset is inconsistent.

Returns:

The size of the batch dataset. Making use of existing _utils function.

power_grid_model.utils.get_component_batch_size(data_array: DenseBatchArray | SparseBatchArray | dict[AttributeTypeVar, BatchColumn] | SparseBatchColumnarData) int

Determine the number of batch scenarios and verify the data structure

Parameters:

data_array – batch data for power-grid-model

Returns:

The number of batch scenarios in data_array

power_grid_model.utils.is_columnar(component_data: SingleArray | DenseBatchArray | SparseBatchArray | dict[AttributeTypeVar, SingleColumn] | dict[AttributeTypeVar, BatchColumn] | SparseBatchColumnarData) bool

Check if component_data is columnar or row based

power_grid_model.utils.is_sparse(component_data: SingleArray | DenseBatchArray | SparseBatchArray | dict[AttributeTypeVar, SingleColumn] | dict[AttributeTypeVar, BatchColumn] | SparseBatchColumnarData) bool

Check if component_data is sparse or dense. Only batch data can be sparse.

power_grid_model.utils.json_deserialize(data: str | bytes, data_filter: set[ComponentTypeVar] | list[ComponentTypeVar] | ComponentAttributeFilterOptions | None | dict[ComponentType, set[AttributeTypeVar] | list[AttributeTypeVar] | None | ComponentAttributeFilterOptions] = None) dict[ComponentTypeVar, _ComponentData]

Load serialized JSON data to a new dataset.

Parameters:
  • data – the data to deserialize.

  • data_filter – the data filter to apply to the dataset.

Raises:
  • ValueError – if the data is inconsistent with the rest of the dataset or a component is unknown.

  • PowerGridError – if there was an internal error.

Returns:

A tuple containing the deserialized dataset in Power grid model input format and the type of the dataset.

power_grid_model.utils.json_serialize(data: dict[ComponentTypeVar, _ComponentData], dataset_type: DatasetType | None = None, use_compact_list: bool = False, indent: int = 2) str

Dump data to a JSON str.

If the dataset_type is not specified or None, it will be deduced from the dataset if possible. Deduction is not possible in case data is empty.

Parameters:
  • data – the dataset

  • dataset_type – the type of the dataset. Defaults to None. Required str-type if data is empty.

  • use_compact_list – whether or not to use compact lists (sparse data). Defaults to False.

  • indent – use specified indentation to make data more readable Use 0 or negative value for no indentation. Defaults to 2

Raises:

PowerGridError – if there was an internal error.

Returns:

A serialized string containing the dataset.

power_grid_model.utils.msgpack_deserialize(data: bytes, data_filter: set[ComponentTypeVar] | list[ComponentTypeVar] | ComponentAttributeFilterOptions | None | dict[ComponentType, set[AttributeTypeVar] | list[AttributeTypeVar] | None | ComponentAttributeFilterOptions] = None) dict[ComponentTypeVar, _ComponentData]

Load serialized msgpack data to a new dataset.

Parameters:

data – the data to deserialize.

Raises:
  • ValueError – if the data is inconsistent with the rest of the dataset or a component is unknown.

  • PowerGridError – if there was an internal error.

Returns:

A tuple containing the deserialized dataset in Power grid model input format and the type of the dataset.

power_grid_model.utils.msgpack_serialize(data: dict[ComponentTypeVar, _ComponentData], dataset_type: DatasetType | None = None, use_compact_list: bool = False) bytes

Dump the data to raw msgpack bytes.

If the dataset_type is not specified or None, it will be deduced from the dataset if possible. Deduction is not possible in case data is empty.

Parameters:
  • data – the dataset

  • dataset_type – the type of the dataset. Defaults to None. Required str-type if data is empty.

  • use_compact_list – whether or not to use compact lists (sparse data). Defaults to False.

Raises:
  • KeyError – if the dataset_type was not provided and could not be deduced from the dataset (i.e. it was empty).

  • PowerGridError – if there was an internal error.

Returns:

A serialized string containing the dataset.

power_grid_model.utils.json_deserialize_from_file(file_path: Path, data_filter: set[ComponentTypeVar] | list[ComponentTypeVar] | ComponentAttributeFilterOptions | None | dict[ComponentType, set[AttributeTypeVar] | list[AttributeTypeVar] | None | ComponentAttributeFilterOptions] = None) dict[ComponentTypeVar, _ComponentData]

Load and deserialize a JSON file to a new dataset.

Parameters:

file_path – the path to the file to load and deserialize.

Raises:
  • ValueError – if the data is inconsistent with the rest of the dataset or a component is unknown.

  • PowerGridError – if there was an internal error.

Returns:

The deserialized dataset in Power grid model input format.

power_grid_model.utils.json_serialize_to_file(file_path: Path, data: dict[ComponentTypeVar, _ComponentData], dataset_type: DatasetType | None = None, use_compact_list: bool = False, indent: int | None = 2)

Export JSON data in most recent format.

Parameters:
  • file_path – the path to the file to load and deserialize.

  • data – a single or batch dataset for power-grid-model.

  • use_compact_list – write components on a single line.

  • indent – indent of the file. Defaults to 2.

Returns:

Save to file.

power_grid_model.utils.msgpack_deserialize_from_file(file_path: Path, data_filter: set[ComponentTypeVar] | list[ComponentTypeVar] | ComponentAttributeFilterOptions | None | dict[ComponentType, set[AttributeTypeVar] | list[AttributeTypeVar] | None | ComponentAttributeFilterOptions] = None) dict[ComponentTypeVar, _ComponentData]

Load and deserialize a msgpack file to a new dataset.

Parameters:

file_path – the path to the file to load and deserialize.

Raises:
  • ValueError – if the data is inconsistent with the rest of the dataset or a component is unknown.

  • PowerGridError – if there was an internal error.

Returns:

The deserialized dataset in Power grid model input format.

power_grid_model.utils.msgpack_serialize_to_file(file_path: Path, data: dict[ComponentTypeVar, _ComponentData], dataset_type: DatasetType | None = None, use_compact_list: bool = False)

Export msgpack data in most recent format.

Parameters:
  • file_path – the path to the file to load and deserialize.

  • data – a single or batch dataset for power-grid-model.

  • use_compact_list – write components on a single line.

  • indent – indent of the file, default 2.

Returns:

Save to file.

power_grid_model.utils.msgpack_deserialize_from_stream(stream: IO[bytes], data_filter: set[ComponentTypeVar] | list[ComponentTypeVar] | ComponentAttributeFilterOptions | None | dict[ComponentType, set[AttributeTypeVar] | list[AttributeTypeVar] | None | ComponentAttributeFilterOptions] = None) dict[ComponentTypeVar, _ComponentData]

Load and deserialize a msgpack file to a new dataset.

Parameters:

stream – the Binary IO stream to the file to load and deserialize.

Raises:
  • ValueError – if the data is inconsistent with the rest of the dataset or a component is unknown.

  • PowerGridError – if there was an internal error.

Returns:

The deserialized dataset in Power grid model input format.

power_grid_model.utils.msgpack_serialize_to_stream(stream: IO[bytes], data: dict[ComponentTypeVar, _ComponentData], dataset_type: DatasetType | None = None, use_compact_list: bool = False)

Export msgpack data in most recent format.

Parameters:
  • stream – the Binary IO stream to the file to load and deserialize.

  • data – a single or batch dataset for power-grid-model.

  • use_compact_list – write components on a single line.

Returns:

Save to BytesIO file.

power_grid_model.utils.import_json_data(json_file: Path, data_type: DatasetType, *args, **kwargs) dict[ComponentTypeVar, _ComponentData]

[deprecated] Import json data.

WARNING: This function is deprecated. Please use json_deserialize_from_file instead.

Parameters:
  • json_file – path to the json file.

  • data_type – type of data: input, update, sym_output, or asym_output.

  • [deprecated] – All extra positional and keyword arguments are ignored.

Returns:

A single or batch dataset for power-grid-model.

power_grid_model.utils.export_json_data(json_file: Path, data: dict[ComponentTypeVar, _ComponentData], indent: int | None = 2, compact: bool = False, use_deprecated_format: bool = True)

[deprecated] Export json data in a deprecated serialization format.

WARNING: This function is deprecated. Please use json_serialize_to_file instead.

For backwards compatibility, this function outputs the deprecated serialization format by default. This feature may be removed in the future.

Parameters:
  • json_file – path to json file.

  • data – a single or batch dataset for power-grid-model.

  • indent – indent of the file, default 2.

  • compact – write components on a single line.

  • use_deprecated_format – use the old style format. Defaults to True for backwards compatibility.

Returns:

Save to file.

power_grid_model.utils.self_test()

Perform a self-test of the Power Grid Model functionality.

Tests whether the installation was successful and there are no build errors, segmentation violations, undefined symbols, etc.

This function is designed to validate the basic functionality of data serialization, model instantiation, power flow calculation, and serialization of results using the Power Grid Model library.

Raises:

PowerGridError – if there was an internal error.