VeraGridEngine.Simulations.EMT.problems package

Submodules

VeraGridEngine.Simulations.EMT.problems.emt_problem_dae module

Module providing the EmtProblemDae class, which acts as the electrical parser for the generic BaseProblem layer. It translates electrical components (buses, branches, injections) into the unified DAE mathematical structure.

class VeraGridEngine.Simulations.EMT.problems.emt_problem_dae.EmtInjectionSeedStore(n_injections: int)[source]

Bases: object

Fixed-size container storing PF-derived initialization seeds for EMT injections.

The store is indexed by the position of each injection in the pre-built injection_devices list of EmtProblemDae._build_structure_and_collect. This avoids dynamic dictionaries for numerical data and keeps memory layout explicit and preallocated.

Parameters:

n_injections – Number of injection devices in the EMT problem.

get_ac_seed(injection_index: int) ndarray[source]

Return the AC phase-power seed in NABC order.

Parameters:

injection_index – Injection position in the fixed injection list.

Returns:

Complex power vector in NABC order.

get_dc_seed(injection_index: int) float[source]

Return the DC active-power seed.

Parameters:

injection_index – Injection position in the fixed injection list.

Returns:

DC active power in per unit.

has_seed(injection_index: int) bool[source]

Return whether the given injection has a stored seed.

Parameters:

injection_index – Injection position in the fixed injection list.

Returns:

True if a seed exists, False otherwise.

set_ac_seed(injection_index: int, phase_power: ndarray) None[source]

Store one AC four-phase power seed.

Parameters:
  • injection_index – Injection position in the fixed injection list.

  • phase_power – Complex power vector in NABC order.

Returns:

None.

set_dc_seed(injection_index: int, power_value: float) None[source]

Store one DC active-power seed.

Parameters:
  • injection_index – Injection position in the fixed injection list.

  • power_value – DC active power in per unit.

Returns:

None.

exception VeraGridEngine.Simulations.EMT.problems.emt_problem_dae.EmtInterfaceValidationError(message: str)[source]

Bases: ValueError

Exception raised when one EMT interface is incompatible with the bus shell.

The dynamic editor may expose a maximum editable interface that is broader than the currently configured static network. This exception reports those mismatches explicitly before EMT assembly can silently skip substitutions.

class VeraGridEngine.Simulations.EMT.problems.emt_problem_dae.EmtProblemDae(grid: MultiCircuit, options: EmtOptions, pf_results_3Ph: PowerFlowResults3Ph | None = None, pf_results_3ph: PowerFlowResults3Ph | None = None, pf_results: PowerFlowResults | None = None, progress_signal: DummySignal | None = None, progress_text: DummySignal | None = None)[source]

Bases: EmtProblemTemplate

Electrical parser layer for the EMT DAE Problem.

Responsibilities:
  • Traverses the MultiCircuit to extract electrical devices.

  • Constructs nodal KCL balances per phase.

  • Processes external piecewise events into the unified block.

  • Maintains mapping between physical devices and symbolic variables.

  • Delegates all mathematical and indexing plumbing to BaseProblem.

  • Initializes PF-based guesses AND evaluates mdl.init_eqs explicitly (Explicit init).

add_device_var(dev: Generator | Battery | Load | ExternalGrid | StaticGenerator | Shunt | ControllableShunt | CurrentInjection | Line | DcLine | Transformer2W | HvdcLine | VSC | UPFC | Winding | Switch | SeriesReactance | FluidNode | FluidPath | FluidP2x | FluidTurbine | FluidPump | Substation | Bus | BusBar | VoltageLevel | Country | Region | Community | Municipality | Area | Zone | Transformer3W | TransformerNW | OverheadLineType | Wire | TransformerType | EmissionGas | BranchGroup | LineLocations | LineLocation | ModellingAuthority | Facility | Fuel | Investment | InvestmentsGroup | Contingency | ContingencyGroup | RemedialAction | RemedialActionGroup | Technology | Owner | UndergroundLineType | SequenceLineType | RmsModelTemplate | EmtModelTemplate | FmuTemplate | RmsEvent | RmsEventsGroup | ShortCircuitEvent | IfMeasurement | ItMeasurement | QfMeasurement | PfMeasurement | QtMeasurement | PtMeasurement | QiMeasurement | PiMeasurement | VmMeasurement | VaMeasurement | PgMeasurement | QgMeasurement, var: Var) None[source]

Registers a variable belonging to a specific device.

property boundary_update: EmtBoundaryUpdateProtocol | None

Return the endogenous EMT boundary updater consumed by the EMT solvers.

emt_boundary_update(t_curr: float, x_prev: ndarray, full_params: ndarray) None[source]

Update runtime boundaries before the Newton step.

Retained mode events are applied first. Afterwards, history-dependent EMT models update their internal boundary data.

Parameters:
  • t_curr – Current simulation time.

  • x_prev – Previous accepted state vector.

  • full_params – Flat full parameter vector.

Returns:

None

get_build_report() Dict[str, float][source]

Return the EMT problem build timing report.

Returns:

Build timing report.

Return type:

Dict[str, float]

get_device_vars_dict() Dict[Generator | Battery | Load | ExternalGrid | StaticGenerator | Shunt | ControllableShunt | CurrentInjection | Line | DcLine | Transformer2W | HvdcLine | VSC | UPFC | Winding | Switch | SeriesReactance | FluidNode | FluidPath | FluidP2x | FluidTurbine | FluidPump | Substation | Bus | BusBar | VoltageLevel | Country | Region | Community | Municipality | Area | Zone | Transformer3W | TransformerNW | OverheadLineType | Wire | TransformerType | EmissionGas | BranchGroup | LineLocations | LineLocation | ModellingAuthority | Facility | Fuel | Investment | InvestmentsGroup | Contingency | ContingencyGroup | RemedialAction | RemedialActionGroup | Technology | Owner | UndergroundLineType | SequenceLineType | RmsModelTemplate | EmtModelTemplate | FmuTemplate | RmsEvent | RmsEventsGroup | ShortCircuitEvent | IfMeasurement | ItMeasurement | QfMeasurement | PfMeasurement | QtMeasurement | PtMeasurement | QiMeasurement | PiMeasurement | VmMeasurement | VaMeasurement | PgMeasurement | QgMeasurement, List[Var]][source]

Returns the dictionary mapping electrical devices to their variables.

get_floquet_ak_stack(trajectory: ndarray, h: float, jac_evaluator: Any | None = None, static_params: ndarray | None = None) ndarray | None[source]

Return the stack of reduced transition matrices used for Floquet analysis.

Parameters:
  • trajectory – State trajectory over one period.

  • h – Time step.

  • jac_evaluator – Optional Jacobian evaluator.

  • static_params – Optional static parameter vector.

Returns:

Stack of reduced transition matrices or None.

get_init_guess_info() DataFrame[source]

Return a table with the explicitly initialized variable guesses.

Returns:

DataFrame with UID, variable name and initialization value.

get_init_guess_table(include_all_vars: bool = True, only_in_init_guess: bool = False, tol_zero: float = 1e-12) DataFrame[source]

Return a table with uid, alias/name and initial value for each variable.

include_all_vars:
  • True: include all state+algebraic vars, even if not in init_guess (value=0).

  • False: include only uids present in init_guess (or only_in_init_guess=True).

only_in_init_guess:
  • True: filter to only those explicitly initialized (uid in init_guess).

  • False: keep everything (depending on include_all_vars).

tol_zero:

threshold to flag values close to zero.

get_next_forced_event_time(t_prev: float, t_target: float) float | None[source]

Return the earliest forced-alignment event time in the interval (t_prev, t_target].

Parameters:
  • t_prev – Previous solver time.

  • t_target – Nominal target time.

Returns:

Earliest forced event time or None.

reset_boundary_update_state(t0: float = 0.0) None[source]

Reset the EMT boundary update state before a new solver run starts.

Parameters:

t0 – Initial simulation time.

Returns:

None

set_diff_init_guess(mdl: Block, reference_powerflow: Any, val: float) None[source]

Set the temporary initial guess for a mapped differential variable during the parsing phase.

Parameters:
  • mdl – Model block containing the external mapping.

  • reference_powerflow – Reference key used to locate the mapped differential variable.

  • val – Initialization value.

Returns:

None

set_events_group(emt_events_group: EmtEventsGroup | None) None[source]

Activate the selected EMT events group inside the problem runtime layer.

Continuous EMT events are mapped to runtime piecewise(time) expressions. Discrete EMT mode events are stored as scheduled updates consumed by the boundary update hook used by the EMT solvers.

Parameters:

emt_events_group – EMT events group to activate. None keeps all EMT events active.

Returns:

None

set_external_param(mdl: Block, key: VarPowerFlowReferenceType, value: float) None[source]

Set a PF-derived value either as an event parameter if the mapped variable belongs to mdl.event_dict.

set_if_exists(mdl: Block, key: VarPowerFlowReferenceType, value: float, persist_after_native_init: bool = False) None[source]

Set an initialization value only if the external mapping contains the key.

Parameters:
  • mdl – Model block containing the external mapping.

  • key – External mapping key.

  • value – Initialization value.

  • persist_after_native_init – Preserve the mapped guess after native initialization.

Returns:

None

set_init_guess(mdl: Block, reference_powerflow: Any, val: float) None[source]

Set the temporary initial guess for a mapped variable during the parsing phase.

Parameters:
  • mdl – Model block containing the external mapping.

  • reference_powerflow – Reference key used to locate the mapped variable.

  • val – Initialization value.

Returns:

None

set_init_guess_and_preserve_post_init(mdl: Block, reference_powerflow: Any, val: float) None[source]

Set one mapped initialization guess and preserve it after native initialization.

Parameters:
  • mdl – Model block containing the external mapping.

  • reference_powerflow – Reference key used to locate the mapped variable.

  • val – Initialization value.

Returns:

None.

set_internal_diff_init_if_exists(mdl: Block, var_name: str, value: float) None[source]

Set one temporary differential initial guess for an internal variable if it exists.

Parameters:
  • mdl – Root model block.

  • var_name – Differential variable name.

  • value – Initialization value.

Returns:

None.

set_internal_init_if_exists(mdl: Block, var_name: str, value: float) None[source]

Set one temporary initial guess for an internal variable if it exists.

Parameters:
  • mdl – Root model block.

  • var_name – Internal variable name.

  • value – Initialization value.

Returns:

None.

set_internal_mode_if_exists(mdl: Block, var_name: str, value: float) None[source]

Set one retained runtime mode default if the mode variable exists.

Parameters:
  • mdl – Root model block.

  • var_name – Retained mode variable name.

  • value – Runtime mode value.

Returns:

None.

set_internal_runtime_if_exists(mdl: Block, var_name: str, value: float) None[source]

Set one internal runtime parameter default if the variable exists in event_dict.

Parameters:
  • mdl – Root model block.

  • var_name – Runtime parameter variable name.

  • value – Runtime parameter value.

Returns:

None.

update(t: float, x: ndarray, params: ndarray) None[source]

Boundary update entry point compatible with BoundaryUpdateWrapper.

Parameters:
  • t – Current simulation time.

  • x – Previous accepted state vector.

  • params – Flat full parameter vector.

Returns:

None

property vars_glob_name2uid: Dict[str, int]

Returns the dictionary mapping global variable names to UIDs.

exception VeraGridEngine.Simulations.EMT.problems.emt_problem_dae.EmtTopologyError(message: str)[source]

Bases: Exception

Exception raised when EMT topology validation fails. This includes orphaned in_vars/out_vars and floating bus phases.

VeraGridEngine.Simulations.EMT.problems.emt_problem_dae.find_name_in_block(name: str, block: Block)[source]
VeraGridEngine.Simulations.EMT.problems.emt_problem_dae.validate_line_phase_layout(branch: Any, mdl: Block, logger: Logger)[source]

Validate that a pi-line EMT block matches the physical branch phase layout.

The EMT parameter mapper writes reduced branch matrices into the fixed NABC API map using branch.ys. This helper therefore checks that the symbolic pi-line terminal layout still matches the physical branch phase mask before the device is flattened into the system model. A mismatch is a topology error, so the function reports it through the shared logger and preserves the original model instead of silently rebuilding it.

Parameters:
  • branch – Grid branch device.

  • mdl – EMT block associated with the branch.

  • logger – Shared system logger used to report invalid topology states.

VeraGridEngine.Simulations.EMT.problems.emt_problem_template module

class VeraGridEngine.Simulations.EMT.problems.emt_problem_template.EmtBoundaryUpdateProtocol(*args, **kwargs)[source]

Bases: Protocol

Structural protocol implemented by EMT boundary update providers.

get_next_forced_event_time(t_prev: float, t_target: float) float | None[source]

Return the next exact-alignment event time inside (t_prev, t_target].

update(t: float, x: ndarray[tuple[Any, ...], dtype[float64]], params: ndarray[tuple[Any, ...], dtype[float64]]) None[source]

Update the full parameter vector in place.

class VeraGridEngine.Simulations.EMT.problems.emt_problem_template.EmtProblemTemplate(sys_block: Block, static_parameter_values_mapping: Dict[Var, Const], glob_time: Var, progress_signal: DummySignal | None = None, progress_text: DummySignal | None = None)[source]

Bases: ABC

Intermediate layer that manages DAE plumbing including indexing, variable mapping, and event updating, regardless of whether the system comes from an electrical circuit or a generic mathematical model.

CONSTANT_PARAMS_NAME = 'cprms'
DIFF_NAME = 'diff'
TIME_NAME = 'glob_time'
VARIABLE_PARAMS_NAME = 'vprms'
VARS_NAME = 'vars'
property boundary_update: EmtBoundaryUpdateProtocol | None

Return the boundary update provider consumed by EMT solvers.

Problems without endogenous boundary logic return None.

def_event_params_fn(ev_param: ndarray[tuple[Any, ...], dtype[float64]], tm: float) ndarray[tuple[Any, ...], dtype[float64]][source]

Update only the continuous runtime parameter slice.

Retained discrete mode parameters are preserved exactly as they enter this function. They are expected to be modified explicitly by the boundary update layer or by future event logic.

Parameters:
  • ev_param – Current flat runtime parameter vector.

  • tm – Current simulation time.

Returns:

Updated flat runtime parameter vector.

property event_parameters_eqs: List[Any]
property event_params_values: ndarray[tuple[Any, ...], dtype[float64]]

Return the current flat runtime parameter vector.

Returns:

Current flat runtime parameter vector.

get_algebraic_eqs() List[Any][source]

Return the ordered list of algebraic equations.

Returns:

Ordered list of algebraic equations.

get_algebraic_var_number() int[source]

Return the number of algebraic variables.

Returns:

Number of algebraic variables.

get_algebraic_vars() List[Var][source]

Return the ordered list of algebraic variables.

Returns:

Ordered list of algebraic variables.

get_alias_names_dict() Dict[int, str][source]

Return the alias-name mapping used by symbolic kernels.

Returns:

Alias-name dictionary.

get_all_vars_number() int[source]

Return the total number of state and algebraic variables.

Returns:

Total number of variables.

get_compiler_names_dict() Dict[int, str][source]

Return the compiler-name mapping used by symbolic kernels.

Returns:

Compiler-name dictionary.

get_constant_parameters() List[Var][source]

Return the ordered list of constant parameters.

Returns:

Ordered list of constant parameters.

get_diff_var_idx(dv: Var) int[source]

Return the flat differential index associated with the given differential variable.

Parameters:

dv – Differential variable to locate.

Returns:

Flat differential index.

get_diff_var_number() int[source]

Return the number of differential variables.

Returns:

Number of differential variables.

get_diff_vars() List[Var][source]

Return the ordered list of differential variables.

Returns:

Ordered list of differential variables.

get_dx0() ndarray[tuple[Any, ...], dtype[float64]][source]

Build the initial differential vector from the stored differential initialization guess.

Returns:

Initial differential vector.

get_event_parameter_equations() List[Any][source]

Return the runtime event-parameter equations.

Returns:

Event-parameter equations.

get_floquet_ak_stack(trajectory: ndarray, h: float, jac_evaluator: Any | None = None, static_params: ndarray[tuple[Any, ...], dtype[float64]] | None = None) ndarray | None[source]

Return the stack of transition matrices used for Floquet analysis.

Parameters:
  • trajectory – State trajectory over one period.

  • h – Time step.

  • jac_evaluator – Optional Jacobian evaluator.

  • static_params – Optional static parameter vector.

Returns:

Stack of transition matrices or None.

get_full_param_index(uid: int) int[source]

Return the flat full-parameter index associated with the given UID.

Parameters:

uid – Parameter unique identifier.

Returns:

Flat index inside the full parameter vector.

get_newton_trace_collector() Any | None[source]

Return the Newton trace collector instance.

Returns:

Newton trace collector instance or None.

get_parameters_values() List[Const][source]

Return the ordered list of constant parameter values.

Returns:

Ordered list of constant parameter values.

get_runtime_continuous_parameters() List[Var][source]

Return the ordered list of continuous runtime parameters.

Returns:

Continuous runtime parameters.

get_runtime_continuous_slice() slice[source]

Return the slice of continuous runtime inputs inside the flat runtime vector.

Returns:

Continuous runtime slice.

get_runtime_mode_parameters() List[Var][source]

Return the ordered list of retained mode runtime parameters.

Returns:

Mode runtime parameters.

get_runtime_mode_slice() slice[source]

Return the slice of retained mode parameters inside the flat runtime vector.

Returns:

Mode runtime slice.

get_state_eqs() List[Any][source]

Return the ordered list of state equations.

Returns:

Ordered list of state equations.

get_state_vars() List[Var][source]

Return the ordered list of state variables.

Returns:

Ordered list of state variables.

get_states_number() int[source]

Return the number of state variables.

Returns:

Number of state variables.

get_var_idx(v: Var) int[source]

Return the flat variable index associated with the given variable.

Parameters:

v – Variable to locate.

Returns:

Flat variable index.

get_variable_parameter_number() int[source]

Return the number of runtime parameters.

Returns:

Number of runtime parameters.

get_variable_parameters() List[Var][source]

Return the ordered list of runtime parameters.

Returns:

Ordered list of runtime parameters.

get_x0() ndarray[tuple[Any, ...], dtype[float64]][source]

Build the initial state vector from the stored initialization guess.

Returns:

Initial state vector.

property glob_time: Var

Return the global time symbolic variable.

Returns:

Global time symbolic variable.

rebuild_runtime_param_vectors() None[source]

Rebuild the runtime and constant parameter buffers.

Returns:

None

reset_boundary_update_state(t0: float = 0.0) None[source]

Reset runtime parameter values before a new EMT simulation starts.

Parameters:

t0 – Initial simulation time.

Returns:

None

set_events_group(emt_events_group: EmtEventsGroup | None) None[source]

Apply a selected EMT events group to the runtime parameter equations.

The method is generic with respect to the specific EMT templates used in the problem. Any runtime parameter exposed through event_dict / mode_dict can be reassigned with a piecewise time function driven by the selected group of grid.emt_events.

set_newton_trace_collector(collector: Any) None[source]

Set the Newton trace collector instance.

Parameters:

collector – Newton trace collector instance.

Returns:

None

set_runtime_mode_parameters(mode_parameters: List[Var]) None[source]

Classify a subset of runtime parameters as retained discrete mode parameters.

The physical storage remains a single flat runtime vector. This method only changes the semantic partition and rebuilds the associated index maps and runtime initialization buffers.

Parameters:

mode_parameters – Runtime parameters to classify as mode parameters.

Returns:

None

state_and_algebraic_vars() List[Var][source]
Returns:

property uid2idx_diff: Dict[int, int]

Return the UID-to-differential-index mapping.

Returns:

UID-to-differential-index mapping.

property uid2idx_event_params: Dict[int, int]

Return the UID-to-runtime-parameter-index mapping.

Returns:

UID-to-runtime-parameter-index mapping.

property uid2idx_params: Dict[int, int]

Return the UID-to-constant-parameter-index mapping.

Returns:

UID-to-constant-parameter-index mapping.

property uid2idx_vars: Dict[int, int]

Return the UID-to-variable-index mapping.

Returns:

UID-to-variable-index mapping.

update_variable_params(t: float) None[source]

Update the internal runtime parameter values at the given time.

Parameters:

t – Current time.

Returns:

None

property vars_glob_name2uid: Dict[str, int]
Returns:

VeraGridEngine.Simulations.EMT.problems.emt_problem_template.get_solver_forced_event_time(boundary_updater: EmtBoundaryUpdateProtocol | None, t_prev: float, t_target: float) float | None[source]

Query the next forced-alignment event time if the updater exposes it.

Legacy boundary updaters that only implement update() are treated as having no forced event alignment requirements.

VeraGridEngine.Simulations.EMT.problems.emt_problem_template.is_problem_owned_boundary_updater(problem: EmtProblemTemplate, boundary_updater: EmtBoundaryUpdateProtocol | None) bool[source]

Return whether the updater is owned by the EMT problem itself.

This distinguishes endogenous problem boundary logic from external wrappers supplied by tests or demos.

VeraGridEngine.Simulations.EMT.problems.emt_problem_template.resolve_solver_boundary_updater(problem: EmtProblemTemplate, boundary_updater: EmtBoundaryUpdateProtocol | None, t0: float) EmtBoundaryUpdateProtocol | None[source]

Resolve the boundary updater consumed by an EMT solver.

The problem-owned updater remains the default, but demos and legacy callers may still provide external wrappers that only implement update().

Module contents