API Reference

This section provides detailed API documentation for the 4PACE core modules.

Power System Base (psys & model)

class fourpace.psys.Bus(name: str, Vbase: float, type: str = 'PQ')[source]

Bases: Graph

Representation of a Bus (Node) in a power system grid. Inherits from nx.Graph, allowing the bus to act as a subgraph containing connected components.

property P: float

Calculates the net active power (P) injected into this bus by all connected components.

property Q: float

Calculates the net reactive power (Q) injected into this bus by all connected components.

property S: complex

Calculates the net apparent power (S) injected into this bus (P + jQ).

add_component(component: BusComponent)[source]

Connects a single component to this bus.

add_components(components: list[BusComponent])[source]

Connects multiple components to this bus simultaneously.

component(name: str) BusComponent[source]

Retrieves a specific component connected to this bus by its name.

property components: list

Returns a list of all components (e.g., loads, generators) attached to this bus.

get()[source]

Returns the current state variables of the bus: [V, theta, P, Q].

total_cost() float[source]

Calculates the total generation cost of all generators connected to this bus.

class fourpace.psys.Grid(Sbase: float)[source]

Bases: Graph

The main class representing the macro-level Power Grid network. Handles system topology, Y-bus matrix construction, and basic power flow operations.

add_bus(bus: Bus)[source]

Adds a single bus to the grid.

add_busses(busses: list[Bus])[source]

Adds a list of buses to the grid.

apply_profile(step_or_dict)[source]

Updates the P and Q values of grid loads based on the specified time step in the attached profile.

Parameters:

step_or_dictint or dict

The hour index (int) to fetch from the DataFrame, or a dictionary specifying load multipliers directly.

attach_profile(df: DataFrame)[source]

Attaches a time-series profile (e.g., hourly load or solar generation profile) to the grid.

Parameters:

dfpandas.DataFrame

The time-series data profile.

build_ybus() ndarray[source]

Constructs the Steady-State Admittance Matrix (Y-bus). Used for standard Load Flow calculations.

build_ybus_pos()[source]

Constructs the Positive-Sequence Y-bus matrix (Y1). Incorporates generator subtransient reactances (Xd”). Used for fault calculation and transient stability analysis.

build_ybus_zero()[source]

Constructs the Zero-Sequence Y-bus Matrix (Y0). * CRITICAL: This structure is highly dependent on transformer grounding/connection types. * Used for asymmetrical fault analysis (e.g., SLG, DLG).

bus(name: str) Bus[source]

Retrieves a Bus object by its name.

property buses: list[Bus]

Returns a list of all Bus objects in the system.

calculate_PQ(i: int) tuple[float, float][source]

Calculates the active (P) and reactive (Q) power injected at bus ‘i’ using power flow equations and the Y-bus matrix.

Parameters:

iint

The index of the bus in the self.buses list.

Returns:

tuple[float, float]

(P_i, Q_i) values in per-unit (p.u.).

check_overload() dict[source]

Inspects the loading status of all branches and generators in the system.

Returns:

dict

A dictionary containing loading percentages categorized by ‘branches’ and ‘generators’.

connect(from_bus: str, to_bus: str, branch: BranchComponent)[source]

Connects two buses via a branch component (e.g., Transmission Line or Transformer).

get_peak_load_hour() int[source]

Finds and returns the hour (index) at which the system experiences the maximum total active power load.

kron_reduction(Y_matrix: ndarray, keep_nodes: list[str]) ndarray[source]

Reduces the dimensions of the Y-bus matrix using Kron Reduction (Network Equivalencing). Eliminates non-essential nodes while preserving the electrical characteristics between the specified ‘keep_nodes’. Essential for Transient Stability Analysis.

Parameters:

Y_matrixnp.ndarray

The original admittance matrix.

keep_nodeslist[str]

A list of bus names to retain (e.g., buses with generators).

Returns:

np.ndarray

The reduced admittance matrix.

classmethod load(filepath: str) Grid[source]

Loads the grid topology and parameters from a configuration file (YAML or JSON).

Parameters:

filepathstr

The path to the configuration file (e.g., ‘config.yaml’).

Returns:

Grid

A fully initialized Grid object ready for simulation.

loading_status()[source]

Checks and prints the loading status (overload warnings) for all branches and generators.

result()[source]

Prints the load flow calculation results (Voltage, Angle, Active & Reactive Power) to the console.

update_motor_slip(motor: AsynchronousMachine, V_pu: float)[source]

Updates the slip of an induction motor to find the equilibrium point where electromagnetic torque (Te) equals mechanical torque (Tm).

Parameters:

motorAsynchronousMachine

The induction motor object.

V_pufloat

The current terminal voltage (p.u.).

class fourpace.model.AsynchronousMachine(name: str, P_rated: float, V_rated: float, Rs: float, Xs: float, Rr: float, Xr: float, Xm: float, poles: int = 4, freq: float = 50.0, s: float = 0.02, load_type: str = 'constant_torque')[source]

Bases: BusComponent

Represents a three-phase induction motor. Power consumption dynamically updates based on voltage, slip, and torque-speed characteristics.

cost() float[source]

Calculates the total operating cost of the component.

incremental_cost() float[source]

Calculates the marginal/incremental cost (dC/dP) for economic dispatch.

update_pq_from_slip(V_mag_pu: float, Sbase: float)[source]

Updates the active (P) and reactive (Q) power draw based on the current slip and terminal voltage.

class fourpace.model.Battery(name: str, P_max: float, E_max: float, init_soc: float = 0.5, eta: float = 0.95, I_fault_limit_pu: float = 1.5, is_candidate: bool = False, capex_per_mw: float = 0.0, capex_per_mwh: float = 0.0, max_build_mw: float = 0.0, max_build_mwh: float = 0.0, lifetime_years: int = 10, interest_rate: float = 0.05)[source]

Bases: BusComponent

Represents a Battery Energy Storage System (BESS). Manages State of Charge (SoC) across time-series simulations and optimization routines.

cost() float[source]

Calculates the total operating cost of the component.

incremental_cost() float[source]

Calculates the marginal/incremental cost (dC/dP) for economic dispatch.

class fourpace.model.BranchComponent(name: str, R: float, X: float, S_max: float | None = None)[source]

Bases: ABC

Abstract base class for all elements connecting two buses in the power system. (e.g., Transmission Lines, Transformers, Series FACTS).

class fourpace.model.BusComponent(name: str, P: float = 0.0, Q: float = 0.0, R: float = 0.0, X: float = 0.0)[source]

Bases: ABC

Abstract base class for all elements connected to a single bus (node) in the power system. (e.g., Generators, Loads, Shunts, Inverters).

property S: complex

Returns the apparent power (S = P + jQ) of the component.

abstract cost() float[source]

Calculates the total operating cost of the component.

abstract incremental_cost() float[source]

Calculates the marginal/incremental cost (dC/dP) for economic dispatch.

class fourpace.model.Inverter(name: str, S_max: float, P: float = 0.0, Q: float = 0.0, control_mode: str = 'grid_following', source_type: str = 'solar', R: float = 0.0, X: float = 0.0, I_fault_limit_pu: float = 1.2, is_candidate: bool = False, capex_per_mw: float = 0.0, max_build_mw: float = 0.0, lifetime_years: int = 15, interest_rate: float = 0.05)[source]

Bases: BusComponent

Represents an Inverter-Based Resource (IBR) such as a Solar PV farm or a BESS inverter. Models grid-following behavior and implements fault current limitations during short-circuits.

cost() float[source]

Calculates the total operating cost of the component.

incremental_cost() float[source]

Calculates the marginal/incremental cost (dC/dP) for economic dispatch.

class fourpace.model.Load(name: str, model: str = 'P', P: float = 0, Q: float = 0, R: float = 0, X: float = 0)[source]

Bases: BusComponent

Represents a static electrical load. Supports ZIP modeling (Constant Impedance ‘Z’, Constant Current ‘I’, Constant Power ‘P’).

cost() float[source]

Calculates the total operating cost of the component.

incremental_cost() float[source]

Calculates the marginal/incremental cost (dC/dP) for economic dispatch.

update_voltage_dependence(V_mag: float, V_nom: float = 1.0)[source]

Modifies actual power consumption based on the terminal voltage and selected load model.

class fourpace.model.Shunt(name: str, Q_nom: float = 0.0, V_nom: float = 1.0)[source]

Bases: BusComponent

Represents a passive shunt compensator (Capacitor bank or Reactor). Reactive power injection varies with the square of the voltage.

cost() float[source]

Calculates the total operating cost of the component.

incremental_cost() float[source]

Calculates the marginal/incremental cost (dC/dP) for economic dispatch.

update_voltage_dependence(V_mag: float)[source]

Updates reactive power injection based on actual bus voltage.

class fourpace.model.SynchronousMachine(name: str, P: float = 0.0, Q: float = 0.0, a: float = 0.0, b: float = 0.0, c: float = 0.0, Pmin: float = 0.0, Pmax: float | None = None, Qmin: float | None = None, Qmax: float | None = None, S_rated: float | None = None, pf: float = 0.85, mode: str = 'generator', R: float = 0.0, X: float = 0.0, H: float = 5.0, Xd: float = 1.0, Xd_prime: float = 0.3, Xd_sub: float = 0.2, X2: float = 0.2, X0: float = 0.05, Td0_prime: float = 5.0, avr: AVR | None = None, gov: Governor | None = None, pss: PSS | None = None, is_candidate: bool = False, capex_per_mw: float = 0.0, max_build_mw: float = 0.0, lifetime_years: int = 20, interest_rate: float = 0.05)[source]

Bases: BusComponent

Represents a synchronous generator, motor, or synchronous condenser. Supports steady-state power flow, economic dispatch, and transient dynamic analysis.

cost() float[source]

Calculates the quadratic generation cost: C(P) = a + b*P + c*P^2.

incremental_cost() float[source]

Calculates the marginal cost: dC/dP = b + 2*c*P.

class fourpace.model.Transformer(name: str, R: float, X: float, tap_ratio: float = 1.0, phase_shift: float = 0.0, S_max: float | None = None, auto_tap: bool = False, controlled_bus: str | None = None, target_V: float = 1.0, tap_step: float = 0.0125, tap_min: float = 0.9, tap_max: float = 1.1, R0: float | None = None, X0: float | None = None, connection_type: str = 'Yg-Yg', is_candidate: bool = False, capex_per_mva: float = 0.0, max_build_mva: float = 0.0, lifetime_years: int = 30, interest_rate: float = 0.05)[source]

Bases: BranchComponent

Represents a two-winding power transformer. Supports tap changing (voltage regulation), phase shifting, and specific grounding configurations (connection types) which dictate the zero-sequence path during unbalanced faults.

class fourpace.model.TransmissionLine(name: str, R: float, X: float, B_shunt: float = 0.0, S_max: float | None = None, length_km: float = 1.0, R0: float | None = None, X0: float | None = None, B0_shunt: float | None = None, is_candidate: bool = False, capex_per_mva: float = 0.0, max_build_mva: float = 0.0, lifetime_years: int = 40, interest_rate: float = 0.05)[source]

Bases: BranchComponent

Represents a three-phase AC transmission line using the Pi-equivalent circuit model. Includes zero-sequence impedances crucial for asymmetrical fault and open-conductor analysis.

fourpace.model.get_daily_capex_factor(interest_rate: float, lifetime_years: int) float[source]

Calculates the Capital Recovery Factor (CRF) converted to a daily rate. Used for amortizing Capital Expenditure (CapEx) in microgrid investment planning.

Parameters:

interest_ratefloat

The annual discount or interest rate (e.g., 0.05 for 5%).

lifetime_yearsint

The expected operational lifetime of the asset in years.

Returns:

float

The daily fraction of the total capital cost.

Fault & Protection (fault)

fourpace.fault.DoubleLineToGroundFault(grid: Grid, fault_bus: str, Z_fault: complex = 0j, max_iter: int = 15, tol: float = 0.0001, verbose: int = 0) dict[source]

Iterative Solver for Double Line-to-Ground (DLG) Fault.

Simulates a severe asymmetrical fault by connecting all three sequence networks (Positive, Negative, and Zero) in a parallel configuration.

fourpace.fault.LineToGroundFault(grid: Grid, fault_bus: str, Z_fault: complex = 0j, max_iter: int = 15, tol: float = 0.0001, verbose: int = 0) dict[source]

Iterative Solver for Single Line-to-Ground (SLG) Fault.

Simulates an asymmetrical SLG fault by connecting the Positive, Negative, and Zero sequence networks in series. Smart IBRs are constrained to inject balanced reactive current exclusively into the Positive Sequence network.

fourpace.fault.LineToLineFault(grid: Grid, fault_bus: str, Z_fault: complex = 0j, max_iter: int = 15, tol: float = 0.0001, verbose: int = 0) dict[source]

Iterative Solver for Line-to-Line (LL) Fault.

Simulates a short circuit between two phases. Connects the Positive and Negative sequence networks in parallel. The Zero Sequence network is mathematically excluded from this analysis.

fourpace.fault.OpenConductorFault(grid: Grid, from_bus: str, to_bus: str, n: int = 1, max_iter: int = 15, tol: float = 0.0001, verbose: int = 0) dict[source]

Iterative Solver for Open Conductor (Series) Faults.

Evaluates asymmetric flow configurations caused by broken conductors spanning a transmission line.

Parameters:

nint

Number of open conductors. - n=1: One Conductor Open (Yields a parallel sequence network structure like LL faults). - n=2: Two Conductors Open (Yields a series sequence network structure like SLG faults).

fourpace.fault.ThreePhaseFault(grid: Grid, fault_bus: str, Z_fault: complex = 0j, max_iter: int = 15, tol: float = 0.0001, verbose: int = 0) dict[source]

Iterative Solver for Symmetrical Three-Phase (3PH) Fault.

Calculates fault currents and voltage profiles during a balanced three-phase short circuit. This advanced iterative solver actively monitors bus voltages and allows Inverter-Based Resources (IBRs) to dynamically limit and inject reactive fault current.

Parameters:

gridGrid

The power system grid object.

fault_busstr

The name of the bus where the fault occurs.

Z_faultcomplex

Fault impedance. Default is 0j (bolted fault/dead short).

max_iterint

Maximum number of iterations for the IBR current injection loop.

tolfloat

Convergence tolerance for the voltage profile differences.

verboseint

Verbosity level for logging.

Returns:

dict

A dictionary containing total fault current (p.u.), Thevenin impedance magnitude, and the full system voltage profile (p.u.).

fourpace.fault.analyze_fault(grid: Grid, path: str | None = None, fault_type: str = '3PH', Z_fault: complex = 0j, verbose: int = 0)[source]

Unified Batch Analysis Engine. Automatically scans the entire grid and applies the specified fault type sequentially to all valid system components (Buses or Transmission Lines).

Supported Fault Types: - Shunt Faults (applied at Bus): ‘3PH’, ‘SLG’, ‘LL’, ‘DLG’ - Series Faults (applied at Line): ‘1OP’, ‘2OP’

fourpace.fault.analyze_faults(grid: Grid, path: str | None = None, fault_types: list[str] = ['3PH', 'SLG', 'LL', 'DLG', '1OP', '2OP'], Z_fault: complex = 0j, verbose: int = 0)[source]

Comprehensive Batch Analysis Engine. Executes multiple fault scenarios simultaneously and generates an aggregated Master Report containing the peak short-circuit currents (kA) mapped out across the entire power grid.

Transient Stability (dynamics & control)

fourpace.dynamics.analyze_transient(grid: Grid, fault_bus: str, t_clear: float, t_end: float = 5.0, dt: float = 0.01, verbose: bool = True) DataFrame[source]

Executes a time-domain transient stability simulation.

A 3-Phase fault is applied at fault_bus at t=0 and is cleared at t_clear. Tracks the rotor angle (delta) of all synchronous machines to determine if synchronism is maintained.

Parameters:
  • grid (Grid) – The initialized and solved (steady-state load flow) power system grid.

  • fault_bus (str) – Name of the bus to apply the solid 3-phase fault.

  • t_clear (float) – Time in seconds when the fault is cleared.

  • t_end (float) – Total duration of the simulation in seconds.

  • dt (float) – Integration time step (s).

Returns:

Time-series data containing simulation time and rotor angles.

Return type:

pd.DataFrame

fourpace.dynamics.find_cct(grid: Grid, fault_bus: str, t_min: float = 0.05, t_max: float = 0.5, tol: float = 0.005, path: str | None = None) dict[source]

Automated Binary Search Algorithm to locate the Critical Clearing Time (CCT).

The CCT is the maximum time a fault can remain on the system before a generator loses synchronism (rotor angle deviation > 180 degrees).

Parameters:
  • grid (Grid) – The power system grid object.

  • fault_bus (str) – The bus to test the 3-phase fault on.

  • t_min (float) – Lower bound of the search window (seconds). Default 0.05.

  • t_max (float) – Upper bound of the search window (seconds). Default 0.50.

  • tol (float) – Search precision tolerance. Search stops when high-low < tol. Default 0.005.

  • path (str, optional) – Filepath to save the CSV trajectory of the final stable run.

Returns:

A dictionary containing the final results of the binary search: - ‘CCT_s’ (float): The calculated Critical Clearing Time. - ‘Simulation’ (pandas.DataFrame or None): The time-series trajectory of the most critical stable scenario.

Return type:

dict

fourpace.dynamics.get_state_indices(machines, shunt_facts, series_facts)[source]

Dynamically maps and allocates contiguous memory arrays for every generator, controller (AVR, GOV, PSS), and FACTS device in the system. This allows the RK4 solver to process all states efficiently in a single flattened vector.

Parameters:
  • machines (list) – List of tuples containing (bus_index, SynchronousMachine_object).

  • shunt_facts (list) – List of tuples containing (bus_index, ShuntFACTS_object).

  • series_facts (list) – List of tuples containing (branch_dict, SeriesFACTS_object).

Returns:

(indices_dict, total_number_of_states)

Return type:

tuple

fourpace.dynamics.ode_engine(t: float, state: ndarray, Y_base: ndarray, machines: list, shunt_facts: list, series_facts: list, indices: dict, omega_s: float, V_ref_dict: dict, P_ref_dict: dict, E_fd_0_dict: dict, algebraic_vars: dict) ndarray[source]

The core Differential-Algebraic Equation (DAE) solver engine. It evaluates the derivatives (dx/dt) of all state variables at time ‘t’.

This function utilizes a Norton Equivalent Network approach: 1. Generator voltage sources are converted to Norton current injections. 2. Shunt and Series FACTS devices dynamically modify the Admittance Matrix (Y_eval). 3. The algebraic network equation [I] = [Y][V] is solved to find bus voltages. 4. These new voltages drive the differential equations of the machines and controllers.

fourpace.dynamics.rk4_step(state: ndarray, t: float, dt: float, *args) ndarray[source]

Standard 4th-Order Runge-Kutta numerical integration step.

class fourpace.control.AVR(name: str)[source]

Bases: ABC

Base template for all types of Automatic Voltage Regulators (AVR)

abstract get_Efd(local_state: ndarray) float[source]
abstract get_derivatives(local_state: ndarray, V_ref: float, V_t: float, V_pss: float, *args, **kwargs) ndarray[source]
abstract initialize(V_ref: float, V_t: float, E_fd0: float, *args, **kwargs) ndarray[source]
class fourpace.control.Governor(name: str)[source]

Bases: ABC

Base template for all types of Turbine-Governors

abstract get_Pm(local_state: ndarray) float[source]
abstract get_derivatives(local_state: ndarray, omega_pu: float, P_ref: float, *args, **kwargs) ndarray[source]
abstract initialize(P_m0: float, omega_pu: float, *args, **kwargs) ndarray[source]
class fourpace.control.PSS(name: str)[source]

Bases: ABC

Base template for all types of Power System Stabilizers (PSS)

abstract get_Vpss(local_state: ndarray, omega_pu: float, P_e: float) float[source]
abstract get_derivatives(local_state: ndarray, omega_pu: float, P_e: float, *args, **kwargs) ndarray[source]
abstract initialize(*args, **kwargs) ndarray[source]
class fourpace.control.PSS1A(name: str, K_pss: float = 10.0, T_w: float = 10.0, T1: float = 0.05, T2: float = 0.02, T3: float = 0.05, T4: float = 0.02, V_max: float = 0.1, V_min: float = -0.1)[source]

Bases: PSS

IEEE Standard Power System Stabilizer (PSS1A) Model with 3 State Variables: [x_w, x_1, x_2] - x_w: Washout filter state - x_1: First lead-lag state - x_2: Second lead-lag state

get_Vpss(local_state: ndarray, omega_pu: float, P_e: float) float[source]

Calculates the final clamped V_pss signal

get_derivatives(local_state: ndarray, omega_pu: float, P_e: float, *args, **kwargs) ndarray[source]
initialize(*args, **kwargs) ndarray[source]

At steady state, speed deviation is 0, so all internal states are 0.

class fourpace.control.SEXS(name: str, Ka: float = 200.0, Ta: float = 0.02, Efd_min: float = -5.0, Efd_max: float = 5.0)[source]

Bases: AVR

Simplified Excitation System (IEEE Type 1 Equivalent) Model with 1 State Variable: [E_fd]

get_Efd(local_state: ndarray) float[source]
get_derivatives(local_state: ndarray, V_ref: float, V_t: float, V_pss: float, *args, **kwargs) ndarray[source]
initialize(V_ref: float, V_t: float, E_fd0: float, *args, **kwargs) ndarray[source]
class fourpace.control.TGOV1(name: str, R: float = 0.05, T1: float = 0.5, T2: float = 1.0, T3: float = 3.0, Vmax: float = 1.0, Vmin: float = 0.0, Dt: float = 0.0)[source]

Bases: Governor

IEEE Standard Steam Turbine-Governor Model (TGOV1) Model with 2 State Variables: [P_gv, x_2] - P_gv: Valve position - x_2: Internal turbine steam chest state

get_Pm(local_state: ndarray) float[source]
get_derivatives(local_state: ndarray, omega_pu: float, P_ref_setpoint: float, *args, **kwargs) ndarray[source]
initialize(P_m0: float, omega_pu: float, *args, **kwargs) ndarray[source]

At steady-state, valve position and internal state equal the initial mechanical power.

FACTS Devices (facts)

class fourpace.facts.CSVGN1(name: str, V_ref: float = 1.0, K_svc: float = 100.0, T_1: float = 0.05, B_max: float = 1.0, B_min: float = -1.0)[source]

Bases: ShuntFACTS

Standard Static Var Compensator (SVC) Model. Model with 1 State Variable: [B_svc] - B_svc: The dynamic susceptance of the device.

get_derivatives(local_state: ndarray, V_bus_mag: float) ndarray[source]

Computes the time derivatives (dx/dt) for the internal state variables given the current bus voltage magnitude.

get_susceptance(local_state: ndarray) float[source]

Returns the equivalent dynamic susceptance $B$ (p.u.) provided by the device to the network.

initialize(V_initial: float) ndarray[source]

Calculate initial steady-state B_svc required to maintain V_initial. Usually, in power flow, the SVC might be at B=0 if voltage is fine.

class fourpace.facts.STATCOM1(name: str, V_ref: float = 1.0, K_r: float = 50.0, T_r: float = 0.05, Iq_max: float = 1.0, Iq_min: float = -1.0)[source]

Bases: ShuntFACTS

Generic Static Synchronous Compensator (STATCOM) Model. Model with 1 State Variable: [I_q] - I_q: Reactive current injection (Voltage Source Converter acting as a current source)

get_Iq(local_state: ndarray) float[source]

Returns the dynamic reactive current injection.

get_derivatives(local_state: ndarray, V_bus_mag: float) ndarray[source]

Computes the time derivatives (dx/dt) for the internal state variables given the current bus voltage magnitude.

get_susceptance(local_state: ndarray) float[source]

STATCOMs are modeled as current sources, NOT susceptances.

initialize(V_initial: float) ndarray[source]

STATCOM starts with 0 reactive current injection unless power flow dictates otherwise.

class fourpace.facts.SeriesFACTS(name: str, branch_name: str)[source]

Bases: ABC

Base class for dynamic series compensators (TCSC, SSSC) These do not sit on a bus; they are attached to a specific Branch/Line.

abstract get_derivatives(local_state: ndarray, P_line_flow: float) ndarray[source]
abstract initialize(*args, **kwargs) ndarray[source]
class fourpace.facts.ShuntFACTS(name: str, P: float = 0.0, Q: float = 0.0)[source]

Bases: BusComponent, ABC

Abstract base class for all Shunt Flexible AC Transmission System (FACTS) devices. Designed for shunt-connected dynamic compensators like SVCs and STATCOMs that inject or absorb reactive power to regulate bus voltage.

cost() float[source]

Calculates the total operating cost of the component.

abstract get_derivatives(local_state: ndarray, V_bus_mag: float) ndarray[source]

Computes the time derivatives (dx/dt) for the internal state variables given the current bus voltage magnitude.

abstract get_susceptance(local_state: ndarray) float[source]

Returns the equivalent dynamic susceptance $B$ (p.u.) provided by the device to the network.

incremental_cost() float[source]

Calculates the marginal/incremental cost (dC/dP) for economic dispatch.

abstract initialize(V_initial: float) ndarray[source]

Calculates the initial steady-state values for the device’s internal states based on the initial bus voltage magnitude.

class fourpace.facts.TCSC1(name: str, branch_name: str, P_ref: float, K_p: float = 1.0, T_p: float = 0.05, X_max: float = 0.0, X_min: float = -0.5)[source]

Bases: SeriesFACTS

Generic Thyristor Controlled Series Capacitor (TCSC). Model with 1 State Variable: [X_tcsc] - X_tcsc: The dynamic series reactance added to the line.

get_X_series(local_state: ndarray) float[source]

Returns the dynamic series reactance.

get_derivatives(local_state: ndarray, P_line_flow: float) ndarray[source]
initialize(*args, **kwargs) ndarray[source]

Starts with 0 compensation.

Optimization & Flow (pfa)

fourpace.pfa.CEP(grid: Grid, profile_df: DataFrame | None = None, relax: str = 'SOCP', solver: str = 'SCS')[source]

Capacity Expansion Planning (CEP) Engine.

Co-optimizes long-term investment sizing (Capital Expenditure - CapEx) against short-term operational schedules (Operational Expenditure - OpEx). Determines the absolute most cost-effective capacity (MW / MWh) of candidate Renewable Energy and BESS assets required to satisfy load profiles while respecting all AC grid physics constraints.

Parameters:

gridGrid

The power system grid object containing designated ‘candidate’ components.

profile_dfDataFrame, optional

Time-series load profile.

relaxstr

Relaxation formulation (‘SOCP’ or ‘SDP’).

solverstr

Optimization solver.

fourpace.pfa.MPOPF(grid: Grid, profile_df: DataFrame | None = None, relax: str = 'SOCP', solver: str = 'SCS')[source]

Multi-Period Optimal Power Flow (MPOPF).

Optimizes the dispatch schedule (Active and Reactive power) for generators, smart inverters, and energy storage systems (BESS) over a given time horizon. Minimizes total generation cost and BESS degradation while strictly adhering to AC power flow physics via convex relaxations.

Parameters:

gridGrid

The power system grid object containing topology and components.

profile_dfDataFrame, optional

Time-series data for loads and renewable availability. If None, uses the grid’s attached profile.

relaxstr

The convex relaxation method to use for AC power flow (‘SOCP’ or ‘SDP’). Default is ‘SOCP’.

solverstr

The CVXPY backend solver to use (e.g., ‘SCS’, ‘MOSEK’, ‘CLARABEL’). Default is ‘SCS’.

fourpace.pfa.N1_Screening(grid, peak_hour: int | None = None, relax: str = 'SOCP', solver: str = 'SCS')[source]

N-1 Contingency Screening utilizing Optimal Power Flow.

Systematically disconnects one transmission branch at a time to test grid resilience during peak loading. Identifies weak physical links that cause system collapse or unsolvable overloads.

Parameters:

gridGrid

The power system grid object.

peak_hourint, optional

Specific hour index to test. If None, auto-detects the hour with maximum active power load.

relaxstr

Relaxation method (‘SOCP’ or ‘SDP’).

solverstr

Solver backend (e.g., ‘SCS’).

fourpace.pfa.NR(grid: Grid, tol: float = 1e-06, max_iter: int = 100)[source]

Non-Linear AC Power Flow Solver using the Newton-Raphson (NR) Method.

Computes precise steady-state bus voltages (magnitude and phase angle), branch power flows, and system losses. Includes dynamic PV-to-PQ bus switching to enforce generator reactive power limits (Q-limits), and On-Load Tap Changer (OLTC) auto-adjustments.

Parameters:

gridGrid

The power system grid object.

tolfloat

Convergence tolerance for maximum power mismatch (p.u.). Default is 1e-6.

max_iterint

Maximum number of iterations allowed before aborting. Default is 100.

class fourpace.pfa.NumpyEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: JSONEncoder

Custom JSON Encoder to seamlessly serialize NumPy data types and Python complex numbers into standard JSON format for exporting simulation results.

default(obj)[source]

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return JSONEncoder.default(self, o)
fourpace.pfa.SCOPF(grid, peak_hour: int | None = None, relax: str = 'SOCP', solver: str = 'SCS')[source]

Security-Constrained Optimal Power Flow (SCOPF) with ESS Rescue.

Formulates a massive “Multiverse” optimization problem that simultaneously calculates the base case (N-0) and all single-branch outages (N-1). Ensures that synchronous generators have a single, fixed setpoint across all universes (preventive), while allowing fast-acting Inverters and Batteries to react dynamically (corrective) to survive outages.

Parameters:

gridGrid

The power system grid object.

peak_hourint, optional

Hour index representing peak loading. Auto-detected if None.

relaxstr

Relaxation formulation (‘SOCP’ or ‘SDP’).

solverstr

Solver backend (e.g., ‘CLARABEL’, ‘SCS’).

Returns:

dict

The ‘Rescue Plan’ mapping each contingency to optimal Battery/Inverter setpoints.

fourpace.pfa.Validate_N1(grid: Grid, rescue_plan: dict | None = None, tol: float = 1e-06, max_iter: int = 100)[source]

Physical Verification Auditor for N-1 Constraints.

Acts as a strict physics validation engine. It drops branches sequentially, applies the AI-generated emergency rescue plans (from SCOPF), and runs the strict non-linear Newton-Raphson AC load flow to ensure that line flows and voltage deviations are practically sound and do not trigger subsequent overloads.

Parameters:

gridGrid

The power system grid object to validate.

rescue_plandict, optional

A dictionary mapping branch outages to specific Battery/Inverter corrective actions.

tolfloat

Tolerance for the NR solver.

max_iterint

Maximum iterations for the NR solver.

fourpace.pfa.plan(grid: Grid, profile_df: DataFrame | None = None, path: str = 'settings.json', relax: str = 'SOCP', solver: str = 'SCS', tol: float = 1e-06, max_iter: int = 100)[source]

Executes a complete Time-Series Simulation and Master Plan.

This function wraps the MPOPF (to find the optimal economic dispatch schedules) and the Newton-Raphson solver (to validate the exact AC physics at each time step). The final results, including voltages, angles, and line flows, are exported to a JSON file.

Parameters:

gridGrid

The power system grid object.

profile_dfDataFrame, optional

Time-series data for the planning horizon.

pathstr

File path to export the resulting settings and states. Default is “settings.json”.

relaxstr

Relaxation method for the MPOPF (‘SOCP’ or ‘SDP’).

solverstr

Optimization backend solver.

tolfloat

Tolerance for the NR solver.

max_iterint

Maximum iterations for the NR solver.

Returns:

str

The JSON string containing the comprehensive simulation history.