powerio

Parse, transform, and emit power system data.

parse returns a module whose value is the typed power system object and whose diagnostics record what the parser found::

import powerio as pio

module = pio.parse("case9.m")
net = module.value
print(net.n_buses, net.base_mva)         # 9 100.0
matpower = pio.emit(module, "matpower")
emitted = pio.emit(module, "psse", "case9.raw")

B = net.calc_bprime_matrix()             # scipy.sparse, MATPOWER Bp
Y = net.calc_admittance_matrix()         # complex csr, G + jB
G = net.to_networkx()                    # networkx.Graph keyed by bus id

A PyPSA CSV directory parses to a network or a time series, depending on its declared snapshots and supported series files. A time series keeps its snapshot axis even when the values are identical. Optional powerio[pypsa-files] transports carry this electrical profile through PyPSA NetCDF and HDF5 files.

A source that defines a calculation parses to that calculation's typed value. Use isinstance(module.value, ...) to branch on the result type.

import powerio and the base parse and emit paths require no third party Python package. Matrix methods require SciPy and NumPy. Graph methods require NetworkX. Install them with powerio[matrix], powerio[graph], or powerio[all]. Missing extras raise ImportError.

   1"""Parse, transform, and emit power system data.
   2
   3``parse`` returns a module whose ``value`` is the typed power system object
   4and whose ``diagnostics`` record what the parser found::
   5
   6    import powerio as pio
   7
   8    module = pio.parse("case9.m")
   9    net = module.value
  10    print(net.n_buses, net.base_mva)         # 9 100.0
  11    matpower = pio.emit(module, "matpower")
  12    emitted = pio.emit(module, "psse", "case9.raw")
  13
  14    B = net.calc_bprime_matrix()             # scipy.sparse, MATPOWER Bp
  15    Y = net.calc_admittance_matrix()         # complex csr, G + jB
  16    G = net.to_networkx()                    # networkx.Graph keyed by bus id
  17
  18A PyPSA CSV directory parses to a network or a time series, depending on its
  19declared snapshots and supported series files. A time series keeps its
  20snapshot axis even when the values are identical. Optional ``powerio[pypsa-files]``
  21transports carry this electrical profile through PyPSA NetCDF and HDF5 files.
  22
  23A source that defines a calculation parses to that calculation's typed value.
  24Use ``isinstance(module.value, ...)`` to branch on the result type.
  25
  26``import powerio`` and the base parse and emit paths require no
  27third party Python package. Matrix methods require SciPy and NumPy. Graph
  28methods require NetworkX. Install them with ``powerio[matrix]``,
  29``powerio[graph]``, or ``powerio[all]``. Missing extras raise ``ImportError``.
  30"""
  31
  32from __future__ import annotations
  33
  34import importlib
  35import io as _io
  36import json as _json
  37import operator as _operator
  38import os as _os
  39from collections import namedtuple
  40from collections.abc import Mapping, Sequence
  41from dataclasses import dataclass
  42from typing import Any, Iterable, Optional, Union
  43
  44from . import _powerio
  45from ._guard import guard as _guard
  46from ._guard import guard_class as _guard_class
  47from ._powerio import (
  48    ActivePower,
  49    ApparentPower,
  50    CalculationUpdate,
  51    ComponentId,
  52    Diagnostic,
  53    NetworkUpdate,
  54    OperatingPointUpdate,
  55    PowerIODataError,
  56    PowerIOError,
  57    PowerIOParseError,
  58    ReactivePower,
  59    Residuals,
  60    ScucActiveReserveZone,
  61    ScucBranchSwitchingCost,
  62    ScucContingency,
  63    ScucDevice,
  64    ScucDeviceOutputs,
  65    ScucDevicePeriod,
  66    ScucEnergyCostBlock,
  67    ScucEnergyRequirement,
  68    ScucInitialCommitment,
  69    ScucInputs,
  70    ScucNetworkOutputs,
  71    ScucRampLimits,
  72    ScucReactiveCapability,
  73    ScucReactiveReserveZone,
  74    ScucReserveCosts,
  75    ScucReserveLimits,
  76    ScucShunt,
  77    ScucStartupCostAdjustment,
  78    ScucStartupLimit,
  79    ScucTransformerControl,
  80    ScucViolationCosts,
  81    SourceSpan,
  82    UpdateChange,
  83    UpdateReport,
  84    __version__,
  85)
  86from ._sincal import SincalBalancedReadOptions, _native_selections
  87from .collection import Collection, CollectionResult
  88
  89__all__ = [
  90    "AcOpfInstance",
  91    "AcOpfSolution",
  92    "AcOtsInstance",
  93    "AcOtsSolution",
  94    "AcPfInstance",
  95    "AcPfSolution",
  96    "AcScucInstance",
  97    "AcScucSolution",
  98    "ActivePower",
  99    "ApparentPower",
 100    "Artifact",
 101    "BalancedNetwork",
 102    "BusMerge",
 103    "CalculationUpdate",
 104    "Collection",
 105    "CollectionResult",
 106    "ComponentId",
 107    "ContingencySet",
 108    "DcOpfInstance",
 109    "DcOpfSolution",
 110    "DcPfInstance",
 111    "DcPfSolution",
 112    "Diagnostic",
 113    "EmitResult",
 114    "FormatInfo",
 115    "GeoLayer",
 116    "LinDist3FlowOpfInstance",
 117    "LinDist3FlowOpfSolution",
 118    "LinDist3FlowPfInstance",
 119    "LinDist3FlowPfSolution",
 120    "McAcOpfInstance",
 121    "McAcOpfSolution",
 122    "McAcPfInstance",
 123    "McAcPfSolution",
 124    "MonitoredSet",
 125    "MulticonductorNetwork",
 126    "NetworkUpdate",
 127    "OperatingPoint",
 128    "OperatingPointUpdate",
 129    "PioModule",
 130    "PowerIODataError",
 131    "PowerIOError",
 132    "PowerIOParseError",
 133    "ReactivePower",
 134    "Residuals",
 135    "Scenario",
 136    "ScenarioSet",
 137    "ScucActiveReserveZone",
 138    "ScucBranchSwitchingCost",
 139    "ScucContingency",
 140    "ScucDevice",
 141    "ScucDeviceOutputs",
 142    "ScucDevicePeriod",
 143    "ScucEnergyCostBlock",
 144    "ScucEnergyRequirement",
 145    "ScucInitialCommitment",
 146    "ScucInputs",
 147    "ScucNetworkOutputs",
 148    "ScucRampLimits",
 149    "ScucReactiveCapability",
 150    "ScucReactiveReserveZone",
 151    "ScucReserveCosts",
 152    "ScucReserveLimits",
 153    "ScucShunt",
 154    "ScucStartupCostAdjustment",
 155    "ScucStartupLimit",
 156    "ScucTransformerControl",
 157    "ScucViolationCosts",
 158    "SincalBalancedReadOptions",
 159    "SocwrOpfSolution",
 160    "SourceSpan",
 161    "SubsystemSet",
 162    "TimePoint",
 163    "TimeSeries",
 164    "UpdateChange",
 165    "UpdateReport",
 166    "__version__",
 167    "apply_bus_load_active_power",
 168    "apply_updates",
 169    "deserialize",
 170    "diagnostic_record",
 171    "diagnostic_records",
 172    "dist",
 173    "emit",
 174    "features",
 175    "from_ppc",
 176    "parse",
 177    "parse_geo",
 178    "resolve_format",
 179    "serialize",
 180    "versions",
 181]
 182
 183@dataclass(frozen=True)
 184class Artifact:
 185    """One artifact produced by :func:`emit` or :func:`serialize`.
 186
 187    ``data`` is set for an in-memory result. ``path`` is set after committing
 188    to a filesystem destination.
 189    """
 190
 191    name: str
 192    data: Optional[bytes]
 193    path: Optional[str]
 194
 195    @property
 196    def text(self) -> str:
 197        """Decode an in-memory UTF-8 artifact."""
 198        if self.data is None:
 199            raise ValueError("this artifact was committed to a destination")
 200        return self.data.decode("utf-8")
 201
 202
 203@dataclass(frozen=True)
 204class EmitResult:
 205    """Artifact inventory and diagnostics from an emission or serialization."""
 206
 207    artifacts: tuple[Artifact, ...]
 208    layout: str
 209    fidelity: str
 210    diagnostics: tuple[Diagnostic, ...]
 211
 212    @property
 213    def text(self) -> Optional[str]:
 214        """The sole UTF-8 memory artifact, or ``None`` for other inventories."""
 215        if len(self.artifacts) != 1 or self.artifacts[0].data is None:
 216            return None
 217        return self.artifacts[0].text
 218
 219FormatInfo = namedtuple(
 220    "FormatInfo", ["token", "extension", "is_directory", "can_emit"]
 221)
 222FormatInfo.__doc__ = """Canonical metadata returned by :func:`resolve_format`.
 223
 224``extension`` is the conventional filename suffix without a leading dot; it
 225can be compound and is ``None`` when a directory format has no primary case
 226file. ``can_emit`` reports whether a fresh universal emitter exists for the
 227format. It is not a promise for every concrete module value or a feature probe. A
 228false value neither promises nor forbids a same format retained source echo.
 229"""
 230
 231def _require(module: str, extra: str):
 232    """Import ``module`` or raise a clear ImportError naming the extra to install."""
 233    try:
 234        return importlib.import_module(module)
 235    except ImportError as exc:
 236        # Only rewrite "module is absent". A present-but-broken install (e.g. a
 237        # failed C-extension load) raises ImportError from a sub-import; let its
 238        # own traceback through instead of misdirecting the user to reinstall.
 239        if getattr(exc, "name", None) not in (module, module.split(".")[0]):
 240            raise
 241        raise ImportError(
 242            f"powerio needs {module!r} for this call; install it with "
 243            f"`pip install 'powerio[{extra}]'`"
 244        ) from exc
 245
 246
 247def _to_csr(coo):
 248    """Assemble a ``(data, row, col, shape)`` COO tuple into a csr_matrix."""
 249    sparse = _require("scipy.sparse", "matrix")
 250    data, row, col, shape = coo
 251    return sparse.coo_matrix((data, (row, col)), shape=shape).tocsr()
 252
 253
 254def _dc_angles(n_buses: int, voltage_angles):
 255    np = _require("numpy", "matrix")
 256    angles = np.asarray(voltage_angles, dtype=float)
 257    if angles.ndim != 1 or angles.shape[0] != n_buses:
 258        raise ValueError(
 259            f"voltage_angles must be a one dimensional array of length {n_buses}"
 260        )
 261    return np, angles
 262
 263
 264_BALANCED_DELEGATED_NAMES = frozenset(
 265    {
 266        "areas",
 267        "base_frequency",
 268        "base_mva",
 269        "branches",
 270        "buses",
 271        "detailed_connectivity",
 272        "generators",
 273        "hvdc",
 274        "is_radial",
 275        "loads",
 276        "n_areas",
 277        "n_branches",
 278        "n_buses",
 279        "n_generators",
 280        "n_hvdc",
 281        "n_islands",
 282        "n_lines",
 283        "n_loads",
 284        "n_shunts",
 285        "n_static_var_compensators",
 286        "n_storage",
 287        "n_substations",
 288        "n_switches",
 289        "n_transformers_3w",
 290        "name",
 291        "reference_bus_index",
 292        "reference_bus_indices",
 293        "shunts",
 294        "static_var_compensators",
 295        "source_format",
 296        "storage",
 297        "switches",
 298        "transformers_3w",
 299    }
 300)
 301
 302
 303@_guard_class
 304class BusMerge:
 305    """The result of :meth:`BalancedNetwork.merge_buses`.
 306
 307    ``network`` is the merged network. ``merged_buses`` maps every merged
 308    bus to the bus that now carries it, and ``groups`` lists each joined set
 309    as ``{"survivor", "members"}``. ``removed_branches`` and
 310    ``removed_switches`` describe every element the merge removed: its source
 311    ``row``, ``id``, ``from_id`` and ``to_id`` buses, ``survivor``, ``reason``
 312    (``"zero_impedance"``, ``"closed_switch"``, or ``"shorted"``), status, and
 313    ratings. ``branch_rows`` and ``switch_rows`` map each source row to its
 314    merged row, or ``None`` when removed, and ``charging_shunts`` lists the
 315    merged shunt rows that hold removed branches' equivalent admittances. ``diagnostics`` holds the merge's
 316    findings, which the merged network's module carries as well.
 317    """
 318
 319    def __init__(self, inner: "_powerio._BusMerge"):
 320        self._inner = inner
 321
 322    def __repr__(self) -> str:
 323        return repr(self._inner)
 324
 325    @property
 326    def network(self) -> "BalancedNetwork":
 327        return BalancedNetwork(self._inner.network)
 328
 329    @property
 330    def rule(self) -> str:
 331        return self._inner.rule
 332
 333    @property
 334    def merged_buses(self) -> dict[int, int]:
 335        return self._inner.merged_buses
 336
 337    @property
 338    def groups(self) -> list[dict[str, Any]]:
 339        return self._inner.groups
 340
 341    @property
 342    def removed_branches(self) -> list[dict[str, Any]]:
 343        return self._inner.removed_branches
 344
 345    @property
 346    def removed_switches(self) -> list[dict[str, Any]]:
 347        return self._inner.removed_switches
 348
 349    @property
 350    def branch_rows(self) -> list[Optional[int]]:
 351        return self._inner.branch_rows
 352
 353    @property
 354    def switch_rows(self) -> list[Optional[int]]:
 355        return self._inner.switch_rows
 356
 357    @property
 358    def charging_shunts(self) -> list[int]:
 359        return self._inner.charging_shunts
 360
 361    @property
 362    def diagnostics(self) -> list[Diagnostic]:
 363        return self._inner.diagnostics
 364
 365    def survivor(self, bus: int) -> int:
 366        """The bus that carries ``bus`` in the merged network."""
 367        return self._inner.survivor(bus)
 368
 369    def calc_removed_flows(
 370        self,
 371        branch_p_from: Any,
 372        branch_p_to: Any,
 373        *,
 374        generator_p: Any = None,
 375        transformer_3w_p: Any = None,
 376    ) -> dict[str, Any]:
 377        """Recover the active power on every removed element.
 378
 379        ``branch_p_from`` and ``branch_p_to`` are the power entering each
 380        merged network branch at its from and to ends; ``generator_p``
 381        replaces the stated generator outputs, and ``transformer_3w_p`` gives
 382        the power entering each three winding transformer winding from its
 383        bus, three values per transformer. Values are in the network's units
 384        (MW for a parsed network). The result has ``branches`` and
 385        ``switches``, one ``{"p_from", "method"}`` per removed element in the
 386        order of :attr:`removed_branches` and :attr:`removed_switches`, and
 387        ``diagnostics``. ``method`` is ``"tree"`` where Kirchhoff's current
 388        law fixes the flow, ``"reactance"`` on a loop split by reactance,
 389        ``"minimum_norm"`` on a loop of zero reactance elements, and
 390        ``"out_of_service"`` for an element that carries none.
 391        """
 392        return self._inner.calc_removed_flows(
 393            [float(p) for p in branch_p_from],
 394            [float(p) for p in branch_p_to],
 395            generator_p=None
 396            if generator_p is None
 397            else [float(p) for p in generator_p],
 398            transformer_3w_p=None
 399            if transformer_3w_p is None
 400            else [tuple(float(p) for p in row) for row in transformer_3w_p],
 401        )
 402
 403
 404@_guard_class
 405class BalancedNetwork:
 406    """A parsed balanced power network.
 407
 408    The data attributes (``buses``, ``branches``, ``generators``, ``loads``,
 409    ``shunts``) and reference bus queries delegate to the compiled handle; the
 410    matrix methods below return ``scipy.sparse`` objects. Parse and transform
 411    diagnostics belong to the owning :class:`PioModule`.
 412
 413    Errors: a bad file path raises the standard ``OSError`` subclass
 414    (``FileNotFoundError``); a malformed case raises :class:`PowerIOParseError`
 415    and an unmet calculation precondition (no generators, no reference bus) raises
 416    :class:`PowerIODataError`; both subclass :class:`PowerIOError`, so
 417    ``except PowerIOError`` catches either; an unknown
 418    ``scheme``/``formula``/``units`` string raises ``ValueError``.
 419    """
 420
 421    def __init__(self, inner: "_powerio._BalancedNetwork"):
 422        self._inner = inner
 423
 424    def __dir__(self):
 425        # The data attributes arrive through __getattr__, so name them here or
 426        # they stay invisible to tab completion.
 427        return sorted(set(super().__dir__()) | _BALANCED_DELEGATED_NAMES)
 428
 429    def __getattr__(self, name: str):
 430        # Reached only when normal lookup misses, so the matrix methods below
 431        # win. Guard underscore names so a lookup before _inner exists raises
 432        # AttributeError instead of recursing forever.
 433        if name not in _BALANCED_DELEGATED_NAMES:
 434            raise AttributeError(
 435                f"{type(self).__name__!r} object has no attribute {name!r}"
 436            )
 437        value = getattr(self._inner, name)
 438        # A native handle is immutable; scalar counts need no repeated FFI
 439        # call. A collection entry update replaces the handle and clears them.
 440        if name.startswith("n_"):
 441            self.__dict__[name] = value
 442        return value
 443
 444    def __repr__(self) -> str:
 445        # The inner handle's __repr__ already renders the public ``BalancedNetwork(...)``
 446        # form, so this is a straight delegate.
 447        return repr(self._inner)
 448
 449    def component_counts(self) -> dict[str, int]:
 450        """Count native lines, generators, loads, and substations.
 451
 452        Lines exclude transformer branches. Loads include equivalent injections
 453        represented as loads. Substations count the source hierarchy, or zero
 454        when the format supplies no hierarchy. No Python table rows are built.
 455        Raises ValueError for normalized networks, whose unity taps no longer
 456        distinguish lines from transformers. Count the source network instead.
 457        """
 458        return self._inner.component_counts()
 459
 460    def calc_connectivity_report(self) -> dict[str, Any]:
 461        """Calculate the in-service topology summary."""
 462        return self._inner.calc_connectivity_report()
 463
 464    def calc_stated_state_mismatch(
 465        self,
 466        *,
 467        top_k: int = 20,
 468        hvdc: str = "fixed_injection",
 469        low_impedance_threshold: float = 1e-3,
 470        merge_zero_impedance: bool = False,
 471        lcc_reactive_power: str = "converter_model",
 472    ) -> dict[str, Any]:
 473        """Evaluate every bus's AC balance at the voltages the case stores.
 474
 475        Each device sits at its stated output: generators at ``pg``/``qg``,
 476        loads through their voltage model at the stored magnitude, shunts at
 477        their stated admittance, and HVDC lines as fixed injections (or not,
 478        with ``hvdc="ignore"``). A bus mismatch is the power the network draws
 479        at the stored voltages minus the stated injection, MW and MVAr, so an
 480        injection equal to it closes the bus.
 481
 482        The result holds per bus columns in analysis bus order (``bus_ids``,
 483        ``island``, ``p_mw``, ``q_mvar``, and ``flags``, the attached
 484        equipment a residual is traced to), ``islands`` totals largest first,
 485        ``top`` (row indices of the largest mismatches), the totals, and
 486        ``diagnostics`` (a warning per LCC line that kept its stated reactive
 487        powers because its converter record reaches no operating point).
 488        ``merge_zero_impedance`` first merges the buses joined by in-service
 489        zero-impedance branches, whose flows the stored voltages cannot
 490        determine; without it such a branch raises. A closed switch joining
 491        two buses also raises (``BUILD.SWITCH.CLOSED``); merge it first with
 492        ``merge_buses(closed_switches=True)``. ``lcc_reactive_power``
 493        selects where a PSS/E two-terminal converter's reactive demand comes
 494        from: its bridge equations at the stored voltages
 495        (``"converter_model"``) or the line's stated reactive powers
 496        (``"stated"``).
 497        """
 498        return self._inner.calc_stated_state_mismatch(
 499            top_k=top_k,
 500            hvdc=hvdc,
 501            low_impedance_threshold=low_impedance_threshold,
 502            merge_zero_impedance=merge_zero_impedance,
 503            lcc_reactive_power=lcc_reactive_power,
 504        )
 505
 506    def calc_stated_branch_flows(self) -> dict[str, Any]:
 507        """Calculate the power entering every branch end at the stored voltages.
 508
 509        Columns follow analysis branch order: every branch row, then the three
 510        windings of each in-service three-winding transformer, as ``sources``
 511        states. Powers are MW and MVAr; an out-of-service branch carries zero.
 512        """
 513        return self._inner.calc_stated_branch_flows()
 514
 515    def to_geo_layer(self) -> dict[str, Any]:
 516        """Transform coordinates to a canonical GeoJSON FeatureCollection.
 517
 518        A case without coordinates produces an empty feature collection.
 519        """
 520        return _json.loads(self._inner.to_geo_layer_json())
 521
 522    def apply_geo_layer(
 523        self, text: str, name_hint: Optional[str] = None
 524    ) -> tuple["BalancedNetwork", dict[str, Any]]:
 525        """Apply a geographic sidecar and return ``(placed, report)``.
 526
 527        ``text`` is any form :func:`parse_geo` accepts; this case is
 528        unchanged. The report carries ``matched_buses``, ``matched_branches``,
 529        ``unmatched_features``, ``unlocated_buses``, ``unlocated_branches``,
 530        and ``notes``. The two unlocated counts cover the whole case when the
 531        pass ends, so a layer that matched nothing reads apart from a case
 532        that needed nothing. The placed copy drops the retained source text,
 533        so a same-format emission re-serializes.
 534        """
 535        inner, report = self._inner.apply_geo_layer(text, name_hint)
 536        return BalancedNetwork(inner), report
 537
 538    def resolve_contingencies(self, text: str) -> dict[str, Any]:
 539        """Read PSS/E contingency text and bind every case to this network.
 540
 541        ``text`` is the content of a ``.con`` file, such as
 542        ``parse("cases.con").value.text``. The result carries ``cases``,
 543        ``resolved``, ``unresolved``, and ``unrecognized_statements`` as
 544        counts; ``case_results``, one entry per case in the file's order with
 545        its ``name``, whether it ``resolved``, the ``components`` it bound to,
 546        and the actions that bound to nothing as ``{"action", "reason"}``; and
 547        ``diagnostics``, the reader's notes on statements it kept as text.
 548
 549        Each component states the ``type`` naming the table, the ``row`` it
 550        occupies there, the element's own ``in_service`` flag, and the ``id``
 551        the network states for it. ``id`` is ``None`` when the network states
 552        no identity for that row; ``type`` and ``row`` name the element either
 553        way.
 554
 555        Binding reports rather than refuses, so a case naming an element this
 556        network does not hold is counted unresolved and listed.
 557        """
 558        return self._inner.resolve_contingencies(text)
 559
 560    def expand_contingencies(
 561        self, con_text: str, sub_text: str
 562    ) -> tuple[str, list[Diagnostic]]:
 563        """Turn automatic contingency specifications into explicit cases.
 564
 565        ``con_text`` and ``sub_text`` are the contents of a ``.con`` and a
 566        ``.sub`` file. A specification such as ``SINGLE BRANCH IN SUBSYSTEM
 567        'A1'`` states a rule, so expanding it needs both the network and the
 568        subsystem the ``.sub`` file names. Returns the expanded ``.con`` text,
 569        which states every outage explicitly, and the notes from the two
 570        readers followed by the expansion's own notes. Only elements this
 571        network states in service expand into cases.
 572        """
 573        return self._inner.expand_contingencies(con_text, sub_text)
 574
 575    def select_subsystem_buses(self, sub_text: str, name: str) -> list[int]:
 576        """The bus numbers one named subsystem of ``sub_text`` selects.
 577
 578        ``sub_text`` is the content of a ``.sub`` file. The numbers come back
 579        in ascending order. A name the file does not state raises
 580        ``ValueError``.
 581        """
 582        return self._inner.select_subsystem_buses(sub_text, name)
 583
 584    # --- matrix calculations (scipy.sparse) -----------------------------
 585
 586    def calc_bprime_matrix(
 587        self, scheme: str = "bx", *, skip_zero_impedance: bool = False
 588    ):
 589        """MATPOWER FDPF Bp matrix. ``scheme`` is ``"bx"`` or ``"xb"``.
 590
 591        ``skip_zero_impedance=False`` refuses a zero impedance branch
 592        (``r`` and ``x`` both zero); pass ``True`` to drop it instead.
 593        """
 594        return _to_csr(
 595            self._inner.bprime(scheme, skip_zero_impedance=skip_zero_impedance)
 596        )
 597
 598    def calc_incidence_matrix(
 599        self, formula: str = "series_susceptance", *, skip_zero_impedance: bool = False
 600    ):
 601        """Return PowerModels incidence ``A`` (branches by buses).
 602
 603        Rows are the in service, non self loop branches in table order
 604        (three winding transformer windings follow the branches); columns
 605        are every bus in table order. :meth:`calc_dc_index_map` names both
 606        axes. ``skip_zero_impedance=False`` refuses a zero impedance branch;
 607        ``True`` drops it from the branch axis.
 608        """
 609        return _to_csr(
 610            self._inner.calc_incidence_matrix(
 611                formula, skip_zero_impedance=skip_zero_impedance
 612            )
 613        )
 614
 615    def calc_branch_susceptances(
 616        self, formula: str = "series_susceptance", *, skip_zero_impedance: bool = False
 617    ):
 618        """Return per branch susceptances over the branch axis of
 619        :meth:`calc_dc_index_map`."""
 620        np = _require("numpy", "matrix")
 621        return np.asarray(
 622            self._inner.calc_branch_susceptances(
 623                formula, skip_zero_impedance=skip_zero_impedance
 624            ),
 625            dtype=float,
 626        )
 627
 628    def calc_branch_flow_matrix(
 629        self, formula: str = "series_susceptance", *, skip_zero_impedance: bool = False
 630    ):
 631        """Return ``Bf = diag(b) A`` as a CSR matrix (branches by buses)."""
 632        return _to_csr(
 633            self._inner.calc_branch_flow_matrix(
 634                formula, skip_zero_impedance=skip_zero_impedance
 635            )
 636        )
 637
 638    def calc_bus_susceptance_matrix(
 639        self, formula: str = "series_susceptance", *, skip_zero_impedance: bool = False
 640    ):
 641        """Return ``B = A.T diag(b) A`` as a CSR matrix (buses by buses)."""
 642        return _to_csr(
 643            self._inner.calc_bus_susceptance_matrix(
 644                formula, skip_zero_impedance=skip_zero_impedance
 645            )
 646        )
 647
 648    def calc_branch_phase_shift_injection(
 649        self, formula: str = "series_susceptance", *, skip_zero_impedance: bool = False
 650    ):
 651        """Return ``b * shift`` over the branch axis."""
 652        np = _require("numpy", "matrix")
 653        return np.asarray(
 654            self._inner.calc_branch_phase_shift_injection(
 655                formula, skip_zero_impedance=skip_zero_impedance
 656            ),
 657            dtype=float,
 658        )
 659
 660    def calc_bus_phase_shift_injection(
 661        self, formula: str = "series_susceptance", *, skip_zero_impedance: bool = False
 662    ):
 663        """Return ``A.T @ (b * shift)`` over the bus axis."""
 664        np = _require("numpy", "matrix")
 665        return np.asarray(
 666            self._inner.calc_bus_phase_shift_injection(
 667                formula, skip_zero_impedance=skip_zero_impedance
 668            ),
 669            dtype=float,
 670        )
 671
 672    def calc_branch_flow_dc(
 673        self,
 674        voltage_angles,
 675        formula: str = "series_susceptance",
 676        *,
 677        skip_zero_impedance: bool = False,
 678    ):
 679        """Compute ``-Bf @ va + b * shift`` over the branch axis."""
 680        np, angles = _dc_angles(self.n_buses, voltage_angles)
 681        return np.asarray(
 682            self._inner.calc_branch_flow_dc(
 683                angles.tolist(), formula, skip_zero_impedance=skip_zero_impedance
 684            ),
 685            dtype=float,
 686        )
 687
 688    def calc_bus_injection_dc(
 689        self,
 690        voltage_angles,
 691        formula: str = "series_susceptance",
 692        *,
 693        skip_zero_impedance: bool = False,
 694    ):
 695        """Compute ``-B @ va + p_shift`` over the bus axis."""
 696        np, angles = _dc_angles(self.n_buses, voltage_angles)
 697        return np.asarray(
 698            self._inner.calc_bus_injection_dc(
 699                angles.tolist(), formula, skip_zero_impedance=skip_zero_impedance
 700            ),
 701            dtype=float,
 702        )
 703
 704    def calc_dc_index_map(
 705        self, formula: str = "series_susceptance", *, skip_zero_impedance: bool = False
 706    ) -> dict[str, Any]:
 707        """Return the axes every DC calculation shares.
 708
 709        ``bus_ids`` maps a bus axis row to the source bus id (every bus, in
 710        table order). ``branch_rows`` maps a branch axis row to the position
 711        in the branch table (three winding transformer windings follow the
 712        branches) and ``branch_ids`` to the stable identity, the branch uid
 713        when the source states one and ``branches:<row>`` otherwise; out of
 714        service branches and self loops have no row. ``skipped_branch_rows``
 715        lists the zero impedance branches dropped under
 716        ``skip_zero_impedance=True`` and is empty otherwise. The same
 717        selection applies to :meth:`calc_ptdf` rows and :meth:`calc_lodf`.
 718        """
 719        return self._inner.calc_dc_index_map(
 720            formula, skip_zero_impedance=skip_zero_impedance
 721        )
 722
 723    def calc_bdoubleprime_matrix(
 724        self, scheme: str = "bx", *, skip_zero_impedance: bool = False
 725    ):
 726        """MATPOWER FDPF Bpp matrix. ``scheme`` is ``"bx"`` or ``"xb"``.
 727        ``skip_zero_impedance`` as in :meth:`calc_bprime_matrix`.
 728        """
 729        return _to_csr(
 730            self._inner.bdoubleprime(scheme, skip_zero_impedance=skip_zero_impedance)
 731        )
 732
 733    def calc_lacpf_matrix(
 734        self,
 735        *,
 736        include_taps: bool = True,
 737        include_shifts: bool = True,
 738        skip_zero_impedance: bool = False,
 739    ):
 740        """LACPF 2n×2n block ``[[G, -B], [-B, -G]]``. ``skip_zero_impedance``
 741        as in :meth:`calc_bprime_matrix`."""
 742        return _to_csr(
 743            self._inner.lacpf(
 744                include_taps=include_taps,
 745                include_shifts=include_shifts,
 746                skip_zero_impedance=skip_zero_impedance,
 747            )
 748        )
 749
 750    def calc_adjacency_matrix(self):
 751        """0/1 bus adjacency matrix."""
 752        return _to_csr(self._inner.adjacency())
 753
 754    def calc_admittance_matrix(
 755        self,
 756        *,
 757        include_taps: bool = True,
 758        include_shifts: bool = True,
 759        skip_zero_impedance: bool = False,
 760    ):
 761        """``Y_bus = G + jB`` as a complex csr_matrix. ``skip_zero_impedance``
 762        as in :meth:`calc_bprime_matrix`."""
 763        g, b = self._inner.ybus_parts(
 764            include_taps=include_taps,
 765            include_shifts=include_shifts,
 766            skip_zero_impedance=skip_zero_impedance,
 767        )
 768        g, b = _to_csr(g), _to_csr(b)
 769        return (g + 1j * b).tocsr()
 770
 771    def calc_ptdf(self, formula: str = "series_susceptance", solver: str = "auto"):
 772        """DC PTDF (m×n). ``formula`` is ``"series_susceptance"``,
 773        ``"tap_adjusted_reactance"``, ``"reactance_only"``,
 774        ``"tap_adjusted_series_susceptance"``, or
 775        ``"series_susceptance_no_phase_shift"``.
 776
 777        ``solver`` is ``"auto"``, ``"dense"``, or ``"sparse"``. ``"auto"``
 778        uses the dense factorization on small cases and the sparse Cholesky
 779        path on large ones, the same policy as the CLI.
 780        """
 781        return _to_csr(self._inner.ptdf(formula, solver))
 782
 783    def calc_lodf(self, formula: str = "series_susceptance", solver: str = "auto"):
 784        """DC LODF (m×m). ``formula`` and ``solver`` as in :meth:`calc_ptdf`."""
 785        return _to_csr(self._inner.lodf(formula, solver))
 786
 787    def calc_weighted_laplacian(
 788        self,
 789        formula: str = "series_susceptance",
 790    ):
 791        """Weighted Laplacian ``L = -B``. ``formula`` as in :meth:`calc_ptdf`."""
 792        return _to_csr(self._inner.weighted_laplacian(formula))
 793
 794    def merge_buses(
 795        self,
 796        *,
 797        closed_switches: bool = True,
 798        zero_impedance: Optional[str] = None,
 799        threshold: Optional[float] = None,
 800        charging: str = "fold",
 801    ) -> "BusMerge":
 802        """Merge the buses closed switches and zero impedance branches join.
 803
 804        ``closed_switches`` merges the two buses of every closed switch.
 805        ``zero_impedance`` selects the branches merged as well: ``None``
 806        merges none, ``"exact"`` merges ``r == 0`` and ``x == 0``,
 807        ``"psse"`` merges non-transformer branches with ``r == 0`` and
 808        ``|x| <= threshold`` (PSS/E zero impedance lines; the threshold
 809        defaults to the ``THRSHZ`` the case states), and ``"impedance"``
 810        merges non-transformer branches with ``|r + jx| <= threshold``.
 811
 812        Each joined set keeps one bus: its reference bus, else a bus with an
 813        in-service generator, else a bus a generator regulates, smallest id
 814        first. Every element moves onto it. The merged elements and any
 815        branch the merge shorts are removed and listed with their source rows
 816        and ratings. ``charging="fold"`` turns each removed branch's line
 817        charging and line shunts, including tap scaling, into a fixed shunt
 818        at the survivor. ``"drop"`` discards only terminal charging. Both
 819        choices preserve the series equivalent of a bypassed transformer.
 820        An ideal transformer with a nonunity tap or phase shift cannot be
 821        bypassed and raises an error. This network is unchanged.
 822
 823        Raises :class:`PowerIODataError` for a threshold that is negative or
 824        not finite, or for ``"psse"`` with no threshold when the case states
 825        none; an unknown rule name raises ``ValueError``.
 826        """
 827        return BusMerge(
 828            self._inner.merge_buses(
 829                closed_switches=closed_switches,
 830                zero_impedance=zero_impedance,
 831                threshold=threshold,
 832                charging=charging,
 833            )
 834        )
 835
 836    def to_normalized(
 837        self,
 838        *,
 839        clamp_angle_bounds: bool = False,
 840        angle_bound_pad: Optional[float] = None,
 841        closed_switches: str = "merge",
 842        island_references: str = "stated",
 843    ) -> "BalancedNetwork":
 844        """Return a normalized copy with per unit power and radian angles.
 845
 846        The result removes out of service elements, preserves source bus IDs,
 847        and normalizes bus types. It carries no retained source, so
 848        :func:`powerio.emit` produces a grid exchange representation from the
 849        derived module. Raises
 850        :class:`PowerIODataError` if the network cannot be
 851        normalized (no reference bus can be chosen, or a non-positive base MVA).
 852
 853        ``clamp_angle_bounds=True`` applies the PowerModels angle difference
 854        bound repair: limits at or beyond ``+/-pi/2`` and zero/zero windows
 855        become ``[-angle_bound_pad, angle_bound_pad]``. A repair that would
 856        invert the interval widens to that same window. The default pad is
 857        1.0472 radians.
 858
 859        The default ``closed_switches="merge"`` merges the buses closed
 860        switches join first, as :meth:`merge_buses` does with
 861        ``closed_switches=True``, since the matrix and DC calculations model
 862        no switches. ``"keep"`` leaves the switches as data, and ``"refuse"``
 863        raises :class:`PowerIODataError` with code ``BUILD.SWITCH.CLOSED``.
 864        ``"merge"`` also raises that error when the merge cannot complete,
 865        for example across two windings of one three winding transformer.
 866        The error names the original switch row and endpoints; no partial
 867        normalized network is returned.
 868
 869        ``island_references="per_island"`` gives every island one reference
 870        bus: an island that states none takes the bus of its largest ``pmax``
 871        in-service generator, an island stating several keeps one, and an
 872        island no in-service generator supplies is left out. The default
 873        ``"stated"`` keeps the case's references and designates one only when
 874        none survives.
 875        """
 876        if (
 877            not clamp_angle_bounds
 878            and angle_bound_pad is None
 879            and closed_switches == "merge"
 880            and island_references == "stated"
 881        ):
 882            return BalancedNetwork(self._inner.to_normalized())
 883        return BalancedNetwork(
 884            self._inner.to_normalized_with_options(
 885                clamp_angle_bounds=clamp_angle_bounds,
 886                angle_bound_pad=angle_bound_pad,
 887                closed_switches=closed_switches,
 888                island_references=island_references,
 889            )
 890        )
 891
 892    def to_ppc(self):
 893        """PYPOWER case dict (``ppc``) with MATPOWER-style numpy tables.
 894
 895        Values are emitted as the model holds them, so a case read from a
 896        file carries MW, MVAr, and degrees. A network from
 897        :meth:`to_normalized` holds per unit and radians, and those are what
 898        its tables carry — PYPOWER reads a ppc dict as MW and degrees, so
 899        build this from the raw network unless the consumer expects per unit.
 900
 901        Loads and shunts are summed onto their bus in the
 902        ``PD``/``QD``/``GS``/``BS`` columns, the same aggregation as the
 903        MATPOWER emitter. The bus table has no per element status
 904        column, so an element the model marks out of service still
 905        contributes its value, and a de-energized bus is carried as type 4.
 906        ``gencost`` is present only when every generator carries cost data,
 907        because MATPOWER requires cost rows for all generators or none.
 908        :func:`from_ppc` reads the tables back.
 909
 910        Infinite branch ratings become PYPOWER's zero (no bound). A real
 911        zero rating raises ``ValueError`` because those tables cannot state
 912        a zero flow bound.
 913        """
 914        np = _require("numpy", "matrix")
 915        buses = self._inner.buses
 916        bus = np.array(
 917            [
 918                (
 919                    b["id"],
 920                    _PPC_BUS_TYPE.get(b["kind"], 1.0),
 921                    0.0,
 922                    0.0,
 923                    0.0,
 924                    0.0,
 925                    b["area"],
 926                    b["vm"],
 927                    b["va"],
 928                    b["base_kv"],
 929                    b["zone"],
 930                    b["vmax"],
 931                    b["vmin"],
 932                )
 933                for b in buses
 934            ],
 935            dtype=float,
 936        ).reshape(len(buses), 13)
 937        bus[:, 2], bus[:, 3], bus[:, 4], bus[:, 5] = _bus_sums(
 938            np, buses, self._inner.loads, self._inner.shunts
 939        )
 940
 941        # The capability and ramp columns past PMIN are an OPF extension that a
 942        # source need not carry. Widen to the full 21 only when a generator
 943        # actually states one: a table of zeros there reads back as eleven
 944        # explicit zero limits, which a ramp aware solver takes as a generator
 945        # that cannot move.
 946        gens = self._inner.generators
 947        caps = [g["caps"] for g in gens]
 948        width = 21 if any(c is not None for row in caps for c in row) else 10
 949        gen = np.array(
 950            [
 951                [
 952                    g["bus"],
 953                    g["pg"],
 954                    g["qg"],
 955                    g["qmax"],
 956                    g["qmin"],
 957                    g["vg"],
 958                    g["mbase"],
 959                    float(g["in_service"]),
 960                    g["pmax"],
 961                    g["pmin"],
 962                ]
 963                + ([0.0 if c is None else c for c in row] if width == 21 else [])
 964                for g, row in zip(gens, caps, strict=True)
 965            ],
 966            dtype=float,
 967        ).reshape(len(gens), width)
 968
 969        branches = self._inner.branches
 970
 971        def ppc_rating(rating):
 972            if rating == 0.0:
 973                raise ValueError("PYPOWER's zero means no bound; it cannot represent a zero branch rating")
 974            return 0.0 if rating == float("inf") else rating
 975
 976        branch = np.array(
 977            [
 978                (
 979                    br["from_id"],
 980                    br["to_id"],
 981                    br["r"],
 982                    br["x"],
 983                    br["b"],
 984                    ppc_rating(br["rate_a"]),
 985                    ppc_rating(br["rate_b"]),
 986                    ppc_rating(br["rate_c"]),
 987                    br["tap"],
 988                    br["shift"],
 989                    float(br["in_service"]),
 990                    br["angmin"],
 991                    br["angmax"],
 992                )
 993                for br in branches
 994            ],
 995            dtype=float,
 996        ).reshape(len(branches), 13)
 997
 998        ppc = {
 999            "version": "2",
1000            "baseMVA": float(self._inner.base_mva),
1001            "bus": bus,
1002            "gen": gen,
1003            "branch": branch,
1004        }
1005
1006        # Coefficients sit left-aligned after ncost, padded to the widest
1007        # row, which is the layout PYPOWER's own loadcase produces.
1008        costs = [g["cost"] for g in gens]
1009        if costs and all(c is not None for c in costs):
1010            gencost = np.zeros((len(costs), 4 + max(len(c["coeffs"]) for c in costs)))
1011            for i, c in enumerate(costs):
1012                gencost[i, :4] = (
1013                    c["model"],
1014                    c["startup"],
1015                    c["shutdown"],
1016                    c["ncost"],
1017                )
1018                gencost[i, 4 : 4 + len(c["coeffs"])] = c["coeffs"]
1019            ppc["gencost"] = gencost
1020        return ppc
1021
1022    def to_networkx(self):
1023        """Undirected networkx graph keyed by bus id.
1024
1025        In-service branches become edges carrying ``branch`` (index), ``r``,
1026        ``x``, and ``b``.
1027        """
1028        nx = _require("networkx", "graph")
1029        g = nx.Graph()
1030        g.add_nodes_from(bus["id"] for bus in self._inner.buses)
1031        for k, br in enumerate(self._inner.branches):
1032            if br["in_service"]:
1033                g.add_edge(
1034                    br["from_id"],
1035                    br["to_id"],
1036                    branch=k,
1037                    r=br["r"],
1038                    x=br["x"],
1039                    b=br["b"],
1040                )
1041        return g
1042
1043
1044@_guard
1045def resolve_format(name: str) -> Optional[FormatInfo]:
1046    """Resolve a format token or common alias to its canonical metadata."""
1047    resolved = _powerio.resolve_format(name)
1048    return None if resolved is None else FormatInfo(*resolved)
1049
1050
1051@_guard
1052def parse_geo(text: str, name_hint: Optional[str] = None) -> dict[str, Any]:
1053    """Tolerantly read a geographic sidecar and return its canonical form.
1054
1055    Accepts headerless buscoords CSV, aliased CSV/JSON records, and GeoJSON
1056    Point/LineString features. Returns ``{"geojson": <FeatureCollection dict>,
1057    "diagnostics": [...]}``; ``name_hint`` (a file name) picks CSV against JSON
1058    when the content alone is ambiguous. Input with no usable coordinates
1059    raises :class:`PowerIOParseError`.
1060    """
1061    parsed = _powerio.parse_geo(text, name_hint)
1062    parsed["geojson"] = _json.loads(parsed["geojson"])
1063    return parsed
1064
1065
1066# powerio bus kind -> MATPOWER/PYPOWER BUS_TYPE code.
1067def _bus_sums(np, buses, loads, shunts):
1068    """Per bus `(pd, qd, gs, bs)` in bus order.
1069
1070    :meth:`BalancedNetwork.to_ppc` folds the element
1071    tables onto their bus the way the Rust indexed analysis view does. This is
1072    that fold, once.
1073    """
1074    row_of = {b["id"]: i for i, b in enumerate(buses)}
1075    pd, qd, gs, bs = (np.zeros(len(buses), dtype=float) for _ in range(4))
1076    for load in loads:
1077        i = row_of.get(load["bus"])
1078        if i is not None:
1079            pd[i] += load["p"]
1080            qd[i] += load["q"]
1081    for shunt in shunts:
1082        i = row_of.get(shunt["bus"])
1083        if i is not None:
1084            gs[i] += shunt["g"]
1085            bs[i] += shunt["b"]
1086    return pd, qd, gs, bs
1087
1088
1089_PPC_BUS_TYPE = {"PQ": 1.0, "PV": 2.0, "REF": 3.0, "ISOLATED": 4.0}
1090
1091# MATPOWER case-input table widths. PYPOWER result tables append columns
1092# (LAM_P, MU_*) past these; from_ppc drops them.
1093_PPC_INPUT_WIDTH = {"bus": 13, "gen": 21, "branch": 13}
1094
1095# Columns a table must carry, which is what the MATPOWER reader requires. The
1096# gen table's capability and ramp columns are an OPF extension, so a 10 column
1097# gen table is a complete case and passes through at its own width; padding it
1098# would hand the reader eleven explicit zero limits the source never stated. A
1099# bus or branch row below 13 is truncated data, and zero padding it would
1100# invent a bus at 0 p.u. and 0 kV, so it is refused here as the reader refuses
1101# it in a `.m` file.
1102_PPC_MIN_WIDTH = {"bus": 13, "gen": 10, "branch": 13}
1103
1104
1105def _ppc_rows(name, table):
1106    """The table's rows as float lists, trimmed to the MATPOWER input width."""
1107    width = _PPC_INPUT_WIDTH.get(name)
1108    minimum = _PPC_MIN_WIDTH.get(name)
1109    out = []
1110    for i, row in enumerate(table):
1111        try:
1112            vals = [float(v) for v in row]
1113        except TypeError as e:
1114            raise ValueError(
1115                f"ppc table {name!r} row {i} is not a sequence of numbers: "
1116                f"pass a 2-D array, one row per element"
1117            ) from e
1118        except ValueError as e:
1119            raise ValueError(
1120                f"ppc table {name!r} row {i} has a non-numeric value: {e}"
1121            ) from e
1122        if minimum is not None and len(vals) < minimum:
1123            raise ValueError(
1124                f"ppc table {name!r} row {i} has {len(vals)} columns; "
1125                f"MATPOWER requires at least {minimum}"
1126            )
1127        out.append(vals[:width] if width is not None else vals)
1128    return out
1129
1130
1131def _ppc_to_matpower_text(ppc) -> str:
1132    missing = [k for k in ("baseMVA", "bus", "gen", "branch") if k not in ppc]
1133    if missing:
1134        raise ValueError(f"ppc dict is missing required keys: {missing}")
1135    lines = [
1136        "function mpc = from_ppc",
1137        f"mpc.version = '{ppc.get('version', '2')}';",
1138        f"mpc.baseMVA = {float(ppc['baseMVA'])!r};",
1139    ]
1140    names = ["bus", "gen", "branch"] + (["gencost"] if "gencost" in ppc else [])
1141    for name in names:
1142        rows = _ppc_rows(name, ppc[name])
1143        lines.append(f"mpc.{name} = [")
1144        for vals in rows:
1145            lines.append("  " + "  ".join(repr(v) for v in vals) + ";")
1146        lines.append("];")
1147    return "\n".join(lines) + "\n"
1148
1149
1150@_guard
1151def from_ppc(ppc) -> BalancedNetwork:
1152    """Case from a PYPOWER dict (``ppc``); the inverse of :meth:`BalancedNetwork.to_ppc`.
1153
1154    The tables route through the MATPOWER reader, so the semantics match a
1155    ``.m`` case exactly: bus ``PD``/``QD`` become loads, ``GS``/``BS`` become
1156    shunts, and ``gencost`` is read when present. Result columns past the
1157    MATPOWER input widths are dropped. A 10 column ``gen`` table (the layout
1158    without the OPF capability columns) passes through at its own width, so
1159    the generators come back with no capability limits rather than eleven
1160    zero ones. Raises :class:`ValueError` when a required table is absent,
1161    when a ``bus`` or ``branch`` row is below its 13 column width, when a row
1162    is not a sequence of numbers, or when a cell is not numeric; the message
1163    names the table and the row.
1164    """
1165    value = parse(
1166        _io.StringIO(_ppc_to_matpower_text(ppc)),
1167        format="matpower",
1168        name="from_ppc.m",
1169    ).value
1170    assert isinstance(value, BalancedNetwork)
1171    return value
1172
1173
1174from . import dist  # noqa: E402  (needs EmitResult defined above)
1175
1176MulticonductorNetwork = dist.MulticonductorNetwork
1177
1178
1179@_guard
1180def versions() -> Any:
1181    """Return the PowerIO release, the PowerIO IR identity, and BMOPF schema.
1182
1183    ``powerio_ir`` is ``{"schema": "pio-ir", "version": <release>}``: the
1184    release whose schema the documents this build writes follow.
1185    ``bmopf_schema`` is the ``$id`` of the one BMOPF schema PowerIO writes.
1186    """
1187    return _json.loads(_powerio.versions_json())
1188
1189
1190class _TypedValue:
1191    """Typed view rooted in its owning :class:`PioModule`."""
1192
1193    __slots__ = ("module", "_collection_entry")
1194
1195    def __init__(self, module: "PioModule") -> None:
1196        self.module = module
1197        self._collection_entry = None
1198
1199    def __repr__(self) -> str:
1200        return f"{type(self).__name__}()"
1201
1202
1203@dataclass(frozen=True)
1204class TimePoint:
1205    label: str
1206    duration_seconds: Optional[float] = None
1207
1208
1209@dataclass(frozen=True)
1210class Scenario:
1211    id: str
1212    probability: Optional[float] = None
1213
1214
1215@dataclass(frozen=True)
1216class _CollectionEntry:
1217    root: "PioModule"
1218    time_index: Optional[int] = None
1219    scenario_id: Optional[str] = None
1220
1221
1222def _bind_collection_entry(
1223    value: Any,
1224    location: _CollectionEntry,
1225) -> Any:
1226    value._collection_entry = location
1227    return value
1228
1229
1230@_guard_class
1231class TimeSeries(_TypedValue, Sequence):
1232    """Values of one type ordered in time."""
1233
1234    def __init__(
1235        self,
1236        values: Sequence[Any],
1237        *,
1238        time_points: Sequence[TimePoint],
1239    ) -> None:
1240        if isinstance(values, (str, bytes, bytearray)) or not isinstance(
1241            values, Sequence
1242        ):
1243            raise TypeError("TimeSeries values must be a sequence of PowerIO values")
1244        if not isinstance(time_points, Sequence):
1245            raise TypeError("time_points must be a sequence of TimePoint values")
1246        points = tuple(time_points)
1247        if not all(isinstance(point, TimePoint) for point in points):
1248            raise TypeError("time_points must contain only TimePoint values")
1249        modules = [PioModule.from_value(value)._inner for value in values]
1250        inner = _powerio._PioModule._from_time_series(
1251            modules,
1252            [(point.label, point.duration_seconds) for point in points],
1253        )
1254        super().__init__(PioModule(inner))
1255
1256    @classmethod
1257    def _from_module(cls, module: "PioModule") -> "TimeSeries":
1258        value = object.__new__(cls)
1259        _TypedValue.__init__(value, module)
1260        return value
1261
1262    @property
1263    def time_points(self) -> tuple[TimePoint, ...]:
1264        return tuple(TimePoint(*point) for point in self.module._inner._time_series_points())
1265
1266    def __len__(self) -> int:
1267        return self.module._inner._time_series_len()
1268
1269    def __getitem__(self, index):
1270        if isinstance(index, slice):
1271            return [self[position] for position in range(*index.indices(len(self)))]
1272        try:
1273            position = _operator.index(index)
1274        except TypeError:
1275            raise TypeError("time series indices must be integers") from None
1276        if position < 0:
1277            position += len(self)
1278        if position < 0 or position >= len(self):
1279            raise IndexError("time series index out of range")
1280        current = self._collection_entry or _CollectionEntry(self.module)
1281        if current.time_index is not None:
1282            raise TypeError("nested TimeSeries values are not supported")
1283        value = PioModule(self.module._inner._time_series_get(position)).value
1284        return _bind_collection_entry(
1285            value,
1286            _CollectionEntry(
1287                root=current.root,
1288                time_index=position,
1289                scenario_id=current.scenario_id,
1290            ),
1291        )
1292
1293    def __iter__(self):
1294        return (self[position] for position in range(len(self)))
1295
1296
1297@_guard_class
1298class ScenarioSet(_TypedValue, Mapping):
1299    """Named alternatives of one type, with optional probabilities."""
1300
1301    def __init__(
1302        self,
1303        values: Mapping[str, Any],
1304        *,
1305        probabilities: Optional[Mapping[str, float]] = None,
1306    ) -> None:
1307        if not isinstance(values, Mapping):
1308            raise TypeError("ScenarioSet values must be a mapping from IDs to values")
1309        if probabilities is not None and not isinstance(probabilities, Mapping):
1310            raise TypeError("probabilities must be a mapping from scenario IDs to numbers")
1311        ids = list(values)
1312        modules = [PioModule.from_value(values[id])._inner for id in ids]
1313        inner = _powerio._PioModule._from_scenario_set(
1314            modules,
1315            ids,
1316            None if probabilities is None else dict(probabilities),
1317        )
1318        super().__init__(PioModule(inner))
1319
1320    @classmethod
1321    def _from_module(cls, module: "PioModule") -> "ScenarioSet":
1322        value = object.__new__(cls)
1323        _TypedValue.__init__(value, module)
1324        return value
1325
1326    @property
1327    def scenarios(self) -> tuple[Scenario, ...]:
1328        return tuple(Scenario(*entry) for entry in self.module._inner._scenario_entries())
1329
1330    def __len__(self) -> int:
1331        return len(self.scenarios)
1332
1333    def __iter__(self):
1334        return (scenario.id for scenario in self.scenarios)
1335
1336    def __contains__(self, scenario: object) -> bool:
1337        return isinstance(scenario, str) and any(
1338            entry.id == scenario for entry in self.scenarios
1339        )
1340
1341    def __getitem__(self, scenario: str) -> Any:
1342        if not isinstance(scenario, str):
1343            raise TypeError("scenario keys must be strings")
1344        if scenario not in self:
1345            raise KeyError(scenario)
1346        current = self._collection_entry or _CollectionEntry(self.module)
1347        if current.scenario_id is not None:
1348            raise TypeError("nested ScenarioSet values are not supported")
1349        value = PioModule(self.module._inner._scenario_get(scenario)).value
1350        return _bind_collection_entry(
1351            value,
1352            _CollectionEntry(
1353                root=current.root,
1354                time_index=current.time_index,
1355                scenario_id=scenario,
1356            ),
1357        )
1358
1359
1360@_guard_class
1361class OperatingPoint(_TypedValue):
1362    """A possibly partial assignment over fixed equipment identities."""
1363
1364    @property
1365    def network(self) -> "BalancedNetwork":
1366        """The balanced network this operating point is stated over.
1367
1368        The point's own values are applied to the returned copy, so it is the
1369        network a solver receives for this entry; the collection's shared
1370        base network is not changed. A multiconductor operating point raises
1371        :class:`PowerIOError`.
1372
1373        Net bus injection quantities have no balanced network field, so they
1374        are dropped here and the property reports nothing. Emit the
1375        collection when you need that omission reported: `emit` warns
1376        `EMIT.OPERATING_POINT.DATA_OMITTED` for the same point.
1377        """
1378        return BalancedNetwork(self.module._inner._operating_point_network())
1379
1380
1381@_guard_class
1382class _BalancedCalculation(_TypedValue):
1383    """A calculation over one shared balanced network."""
1384
1385    @property
1386    def network(self) -> BalancedNetwork:
1387        """The balanced network used by this calculation."""
1388        return BalancedNetwork(self.module._inner._balanced_calculation_network())
1389
1390
1391@_guard_class
1392class _MulticonductorCalculation(_TypedValue):
1393    """A calculation over one shared multiconductor network."""
1394
1395    @property
1396    def network(self) -> MulticonductorNetwork:
1397        """The multiconductor network used by this calculation."""
1398        return MulticonductorNetwork(
1399            self.module._inner._multiconductor_calculation_network()
1400        )
1401
1402
1403@_guard_class
1404class _CalculationSolution(_TypedValue):
1405    """A solution that retains the exact typed instance it solves."""
1406
1407    @property
1408    def instance(self) -> _TypedValue:
1409        """The calculation instance solved by this result."""
1410        return PioModule(self.module._inner._calculation_solution_instance()).value
1411
1412
1413class DcPfInstance(_BalancedCalculation):
1414    """A DC power flow calculation instance."""
1415
1416
1417class AcPfInstance(_BalancedCalculation):
1418    """An AC power flow calculation instance."""
1419
1420
1421class DcOpfInstance(_BalancedCalculation):
1422    """A DC optimal power flow calculation instance."""
1423
1424
1425class AcOpfInstance(_BalancedCalculation):
1426    """An AC optimal power flow calculation instance."""
1427
1428
1429def _branch_statuses(closed: Sequence[bool]) -> list[bool]:
1430    """A final branch status vector as a list of booleans, in branch order."""
1431    if isinstance(closed, (str, bytes)):
1432        raise TypeError("branch statuses are a sequence of booleans")
1433    return list(closed)
1434
1435
1436@_guard_class
1437class AcOtsInstance(_BalancedCalculation):
1438    """An AC optimal transmission switching calculation instance.
1439
1440    Its network holds every candidate branch at its initial status.
1441    """
1442
1443    @property
1444    def options(self) -> dict[str, Any]:
1445        """The switching options as stated, spelled as the keyword arguments of
1446        :meth:`PioModule.to_ac_ots_instance`: ``switchable`` (``"all"``,
1447        ``"none"``, or a list of branch identities), ``switching_costs``
1448        (``{id: (open_cost, close_cost)}``), ``islanding``, ``max_open``,
1449        ``max_switched``, ``current_limits``, and ``stated_current_limits``
1450        (``{id: (from_pu, to_pu)}``, ``None`` for an unbounded side).
1451        """
1452        return self.module._inner._ac_ots_options()
1453
1454    @property
1455    def branches(self) -> list[dict[str, Any]]:
1456        """One row per physical branch, in branch table order: ``id``,
1457        ``initial_closed``, ``switchable``, ``switching_cost`` (``(open_cost,
1458        close_cost)``, or ``None`` when no cost is stated and the branch
1459        switches at zero cost), ``stated_current`` (the stated ``(from_pu,
1460        to_pu)`` limits), and ``current`` (the limits that apply under the
1461        current limit policy). ``None`` in a limit pair is unbounded.
1462        """
1463        return self.module._inner._ac_ots_branches()
1464
1465    def validate_topology(self, closed: Sequence[bool]) -> float:
1466        """Check a final topology and return its switching cost.
1467
1468        ``closed`` holds one boolean per branch, in branch table order. The
1469        check covers the length, the branches that cannot switch, the
1470        ``max_open`` and ``max_switched`` budgets, and the islanding policy;
1471        it does not certify AC feasibility. A refused topology raises
1472        :class:`PowerIOError` with code ``BUILD.INSTANCE.TOPOLOGY_INVALID``.
1473        """
1474        return self.module._inner._ac_ots_validate_topology(_branch_statuses(closed))
1475
1476    def fix_topology(
1477        self, closed: Sequence[bool]
1478    ) -> tuple["AcOpfInstance", list[Diagnostic]]:
1479        """The AC optimal power flow over a final topology.
1480
1481        Every branch row stays in the network with its final status. The
1482        switching options, current limits, and switching cost term are not
1483        part of the AC optimal power flow; the returned diagnostics report
1484        each one dropped, and the instance's module carries them too. The
1485        topology is checked as :meth:`validate_topology` checks it.
1486        """
1487        inner, diagnostics = self.module._inner._ac_ots_fix_topology(
1488            _branch_statuses(closed)
1489        )
1490        return PioModule(inner).value, list(diagnostics)
1491
1492
1493class McAcPfInstance(_MulticonductorCalculation):
1494    """A multiconductor AC power flow calculation instance."""
1495
1496
1497@_guard_class
1498class LinDist3FlowPfInstance(_MulticonductorCalculation):
1499    """A fixed-dispatch LinDist3Flow power-flow instance."""
1500
1501    @property
1502    def metadata(self) -> dict[str, Any]:
1503        """Node/conductor axes, preparation actions, and reference phasors."""
1504        return self.module._inner._lindist3flow_metadata()
1505
1506
1507@_guard_class
1508class LinDist3FlowOpfInstance(_MulticonductorCalculation):
1509    """A radial fixed-reference multiconductor linear OPF instance."""
1510
1511    @property
1512    def metadata(self) -> dict[str, Any]:
1513        """Node and conductor axes, roots, and reference phasors in volts/radians."""
1514        return self.module._inner._lindist3flow_metadata()
1515
1516
1517class McAcOpfInstance(_MulticonductorCalculation):
1518    """A multiconductor AC optimal power flow calculation instance."""
1519
1520
1521@_guard_class
1522class AcScucInstance(_BalancedCalculation):
1523    """An AC security constrained unit commitment calculation instance."""
1524
1525    @property
1526    def inputs(self) -> ScucInputs:
1527        """Scheduling, reserve, and contingency inputs."""
1528        return self.module._inner._ac_scuc_inputs()
1529
1530
1531class DcPfSolution(_BalancedCalculation, _CalculationSolution):
1532    """A DC power flow solution."""
1533
1534
1535class AcPfSolution(_BalancedCalculation, _CalculationSolution):
1536    """An AC power flow solution."""
1537
1538
1539class DcOpfSolution(_BalancedCalculation, _CalculationSolution):
1540    """A DC optimal power flow solution."""
1541
1542
1543class AcOpfSolution(_BalancedCalculation, _CalculationSolution):
1544    """An AC optimal power flow solution."""
1545
1546
1547@_guard_class
1548class AcOtsSolution(_BalancedCalculation, _CalculationSolution):
1549    """An AC optimal transmission switching result.
1550
1551    Its network is the instance's network, with the initial branch statuses;
1552    :meth:`solved_network` gives the network with the final statuses and
1553    solved values.
1554    """
1555
1556    @classmethod
1557    def from_ac_opf_solution(
1558        cls,
1559        instance: AcOtsInstance,
1560        closed: Sequence[bool],
1561        solution: "AcOpfSolution",
1562    ) -> "AcOtsSolution":
1563        """Attach the AC optimal power flow solution computed on
1564        ``instance.fix_topology(closed)``.
1565
1566        The topology is checked as :meth:`AcOtsInstance.validate_topology`
1567        checks it, the solution must answer exactly the fixed-topology problem
1568        (its network, objective, and constraint selections), and open branches
1569        must carry no flow. Residuals and optimality are not checked. The
1570        result's module carries the instance module's records.
1571        """
1572        if not isinstance(instance, AcOtsInstance):
1573            raise TypeError("instance must be a powerio.AcOtsInstance")
1574        if not isinstance(solution, AcOpfSolution):
1575            raise TypeError("solution must be a powerio.AcOpfSolution")
1576        inner = instance.module._inner._ac_ots_solution(
1577            _branch_statuses(closed), solution.module._inner
1578        )
1579        return PioModule(inner).value
1580
1581    @property
1582    def branch_closed(self) -> list[bool]:
1583        """The final branch statuses, in branch table order."""
1584        return self.module._inner._ac_ots_solution_branch_closed()
1585
1586    @property
1587    def switching_cost(self) -> float:
1588        """The cost of the status changes against the initial topology."""
1589        return self.module._inner._ac_ots_solution_summary()[0]
1590
1591    @property
1592    def branches_open(self) -> int:
1593        """The number of branches open in the final topology."""
1594        return self.module._inner._ac_ots_solution_summary()[1]
1595
1596    @property
1597    def branches_switched(self) -> int:
1598        """The number of branches whose final status differs from the initial one."""
1599        return self.module._inner._ac_ots_solution_summary()[2]
1600
1601    @property
1602    def objective(self) -> float:
1603        """The AC solution's objective, plus the switching cost when the
1604        instance's objective states the switching cost term."""
1605        return self.module._inner._ac_ots_solution_summary()[3]
1606
1607    def solved_network(self) -> "PioModule":
1608        """The balanced network this result states: the final branch statuses
1609        with the solved bus voltages, generator dispatch, and branch flows
1610        applied, ready for :func:`emit`. The C ABI's
1611        ``pio_ac_ots_solution_materialize`` and PowerIO.jl's
1612        ``materialize_ac_ots_solution`` return the same network."""
1613        return PioModule(self.module._inner._ac_ots_solved_network())
1614
1615
1616class SocwrOpfSolution(_BalancedCalculation, _CalculationSolution):
1617    """A PowerModels SOCWR relaxation solution and objective lower bound."""
1618
1619
1620class McAcPfSolution(_MulticonductorCalculation, _CalculationSolution):
1621    """A multiconductor AC power flow solution."""
1622
1623
1624@_guard_class
1625class LinDist3FlowPfSolution(_MulticonductorCalculation, _CalculationSolution):
1626    """Fixed-dispatch LinDist3Flow values and monitored SI line limits."""
1627
1628    @property
1629    def termination(self) -> str:
1630        """How the calculation ended."""
1631        return self.module._inner._lindist3flow_solution_termination()
1632
1633    @property
1634    def limit_checks(self) -> list[dict[str, Any]]:
1635        """Monitored line ratings, values, loading ratios, and overload flags."""
1636        return self.module._inner._lindist3flow_limit_checks()
1637
1638    def __getitem__(self, quantity: str) -> list[float]:
1639        """Copy one named primal column in its physical instance order."""
1640        return self.module._inner._lindist3flow_solution_values(quantity)
1641
1642
1643@_guard_class
1644class LinDist3FlowOpfSolution(_MulticonductorCalculation, _CalculationSolution):
1645    """LinDist3Flow primal values in squared volts, watts, and vars."""
1646
1647    @property
1648    def termination(self) -> str:
1649        """How the calculation ended."""
1650        return self.module._inner._lindist3flow_solution_termination()
1651
1652    @property
1653    def objective(self) -> float:
1654        """The reported objective value."""
1655        return self.module._inner._lindist3flow_solution_objective()
1656
1657    def __getitem__(self, quantity: str) -> list[float]:
1658        """Copy one named primal column in its physical instance order."""
1659        return self.module._inner._lindist3flow_solution_values(quantity)
1660
1661
1662class McAcOpfSolution(_MulticonductorCalculation, _CalculationSolution):
1663    """A multiconductor AC optimal power flow solution."""
1664
1665
1666@_guard_class
1667class AcScucSolution(_BalancedCalculation, _CalculationSolution):
1668    """An AC security constrained unit commitment solution."""
1669
1670    @property
1671    def termination(self) -> str:
1672        """How the calculation ended."""
1673        return self.module._inner._ac_scuc_solution_termination()
1674
1675    @property
1676    def residuals(self) -> Residuals:
1677        """Reported active and reactive power balance residuals."""
1678        return self.module._inner._ac_scuc_solution_residuals()
1679
1680    @property
1681    def producer(self) -> Optional[str]:
1682        """Producer or solver identity, when recorded."""
1683        return self.module._inner._ac_scuc_solution_producer()
1684
1685    @property
1686    def network_outputs(self) -> ScucNetworkOutputs:
1687        """Per interval network outputs."""
1688        return self.module._inner._ac_scuc_solution_network_outputs()
1689
1690    @property
1691    def device_outputs(self) -> ScucDeviceOutputs:
1692        """Per interval dispatchable device outputs."""
1693        return self.module._inner._ac_scuc_solution_device_outputs()
1694
1695    @property
1696    def objective(self) -> Optional[float]:
1697        """Reported objective value, when present."""
1698        return self.module._inner._ac_scuc_solution_objective()
1699
1700
1701@_guard_class
1702class GeoLayer(_TypedValue):
1703    """A standalone geographic document: element points and routes keyed by
1704    element identity, in one coordinate space.
1705
1706    :func:`parse` returns it for the canonical ``.geo.json``, GeoJSON, aliased
1707    CSV or JSON records, headerless buscoords CSV, and a PowerWorld ``.pwd``
1708    display. :func:`powerio.emit` writes the canonical document as
1709    ``geo-json``, and :func:`serialize` carries the layer through PowerIO IR.
1710    Place a layer onto a case with
1711    ``network.apply_geo_layer(layer.geojson)``.
1712    """
1713
1714    @property
1715    def geojson(self) -> str:
1716        """The canonical ``.geo.json`` document for this layer."""
1717        result = emit(self.module, "geo-json")
1718        data = result.artifacts[0].data
1719        if data is None:
1720            raise ValueError("the layer emission returned no artifact bytes")
1721        return data.decode("utf-8")
1722
1723
1724def _emitted_text(module: "PioModule[Any]", format: str) -> str:
1725    """Emit ``module`` under one token and decode the single UTF-8 artifact."""
1726    result = emit(module, format)
1727    data = result.artifacts[0].data
1728    if data is None:
1729        raise ValueError(f"the {format} emission returned no artifact bytes")
1730    return data.decode("utf-8")
1731
1732
1733@_guard_class
1734class ContingencySet(_TypedValue):
1735    """A PSS/E contingency description file: the cases to run, the automatic
1736    specifications that state cases by rule, and the ``SKIP`` rules.
1737
1738    :func:`parse` returns it for a ``.con`` file or for text declared as
1739    ``psse-con``, :func:`powerio.emit` writes it back under that token, and
1740    :func:`serialize` carries it through PowerIO IR. Bind a set to a case with
1741    ``network.resolve_contingencies(cases.text)`` and turn its automatic
1742    specifications into explicit cases with
1743    ``network.expand_contingencies(cases.text, groups.text)``.
1744    """
1745
1746    @property
1747    def text(self) -> str:
1748        """The ``.con`` text for this set."""
1749        return _emitted_text(self.module, "psse-con")
1750
1751
1752@_guard_class
1753class SubsystemSet(_TypedValue):
1754    """A PSS/E subsystem description file: the named bus groups a contingency
1755    run and a monitored element file draw on.
1756
1757    :func:`parse` returns it for a ``.sub`` file or for text declared as
1758    ``psse-sub``, and ``network.select_subsystem_buses(groups.text, name)``
1759    names the buses one subsystem selects.
1760    """
1761
1762    @property
1763    def text(self) -> str:
1764        """The ``.sub`` text for this set."""
1765        return _emitted_text(self.module, "psse-sub")
1766
1767
1768@_guard_class
1769class MonitoredSet(_TypedValue):
1770    """A PSS/E monitored element file: the branches, interfaces, and voltage
1771    scopes a contingency run reports on.
1772
1773    :func:`parse` returns it for a ``.mon`` file or for text declared as
1774    ``psse-mon``.
1775    """
1776
1777    @property
1778    def text(self) -> str:
1779        """The ``.mon`` text for this set."""
1780        return _emitted_text(self.module, "psse-mon")
1781
1782
1783_VALUE_CLASSES: dict[str, type[_TypedValue]] = {
1784    "powerio.ContingencySet": ContingencySet,
1785    "powerio.GeoLayer": GeoLayer,
1786    "powerio.MonitoredSet": MonitoredSet,
1787    "powerio.SubsystemSet": SubsystemSet,
1788    "powerio.OperatingPoint<powerio.BalancedNetwork>": OperatingPoint,
1789    "powerio.OperatingPoint<powerio.MulticonductorNetwork>": OperatingPoint,
1790    "powerio.DcPfInstance": DcPfInstance,
1791    "powerio.AcPfInstance": AcPfInstance,
1792    "powerio.DcOpfInstance": DcOpfInstance,
1793    "powerio.AcOpfInstance": AcOpfInstance,
1794    "powerio.AcOtsInstance": AcOtsInstance,
1795    "powerio.McAcPfInstance": McAcPfInstance,
1796    "powerio.McAcOpfInstance": McAcOpfInstance,
1797    "powerio.LinDist3FlowPfInstance": LinDist3FlowPfInstance,
1798    "powerio.LinDist3FlowOpfInstance": LinDist3FlowOpfInstance,
1799    "powerio.AcScucInstance": AcScucInstance,
1800    "powerio.DcPfSolution": DcPfSolution,
1801    "powerio.AcPfSolution": AcPfSolution,
1802    "powerio.DcOpfSolution": DcOpfSolution,
1803    "powerio.AcOpfSolution": AcOpfSolution,
1804    "powerio.AcOtsSolution": AcOtsSolution,
1805    "powerio.SocwrOpfSolution": SocwrOpfSolution,
1806    "powerio.McAcPfSolution": McAcPfSolution,
1807    "powerio.McAcOpfSolution": McAcOpfSolution,
1808    "powerio.LinDist3FlowPfSolution": LinDist3FlowPfSolution,
1809    "powerio.LinDist3FlowOpfSolution": LinDist3FlowOpfSolution,
1810    "powerio.AcScucSolution": AcScucSolution,
1811}
1812
1813
1814@_guard_class
1815class PioModule:
1816    """One typed value with diagnostics, producer, sources, source mappings,
1817    history, and extensions.
1818    """
1819
1820    def __init__(self, inner: "_powerio._PioModule"):
1821        self._inner = inner
1822
1823    def sever_source(self) -> "PioModule":
1824        """Copy this module without retained input bytes, forcing fresh emission.
1825
1826        The original module is unchanged. Values, diagnostics, source
1827        descriptors, and history are preserved; preparing the copy has a cost
1828        separate from emission.
1829        """
1830        return PioModule(self._inner.sever_source())
1831
1832    @classmethod
1833    def from_value(cls, value: Any) -> "PioModule":
1834        """Wrap an existing typed value without serializing it."""
1835        if isinstance(value, BalancedNetwork):
1836            return cls(_powerio._PioModule.from_balanced_network(value._inner))
1837        if isinstance(value, dist.MulticonductorNetwork):
1838            return cls(_powerio._PioModule.from_multiconductor_network(value._inner))
1839        if isinstance(value, _TypedValue):
1840            location = value._collection_entry
1841            inner = value.module._inner
1842            if location is not None:
1843                inner = location.root._inner
1844                if location.scenario_id is not None:
1845                    inner = inner._scenario_get(location.scenario_id)
1846                if location.time_index is not None:
1847                    inner = inner._time_series_get(location.time_index)
1848            return cls(inner._copy())
1849        raise TypeError("PioModule.from_value expects a typed PowerIO value")
1850
1851    @property
1852    def value(self) -> Any:
1853        """The contained typed value."""
1854        type_name = self._inner._type_name
1855        if type_name == "powerio.BalancedNetwork":
1856            return BalancedNetwork(self._inner.as_balanced_network())
1857        if type_name == "powerio.MulticonductorNetwork":
1858            return dist.MulticonductorNetwork(self._inner.as_multiconductor_network())
1859        if type_name.startswith("powerio.TimeSeries<"):
1860            return TimeSeries._from_module(self)
1861        if type_name.startswith("powerio.ScenarioSet<"):
1862            return ScenarioSet._from_module(self)
1863        value_class = _VALUE_CLASSES.get(type_name)
1864        if value_class is None:
1865            raise RuntimeError(f"this binding has no Python class for {type_name}")
1866        return value_class(self)
1867
1868    @property
1869    def type_name(self) -> str:
1870        """The canonical structural name of the contained value, such as
1871        ``powerio.OperatingPoint<powerio.BalancedNetwork>``. The C ABI and
1872        PowerIO IR name the same type with the same string.
1873        """
1874        return str(self._inner._type_name)
1875
1876    @property
1877    def diagnostics(self) -> list[Diagnostic]:
1878        """The diagnostics stored on this module, in encounter order."""
1879        return list(self._inner.diagnostics)
1880
1881    @property
1882    def extension_keys(self) -> list[str]:
1883        """The namespaces of the extensions this module carries, sorted."""
1884        return list(self._inner._extension_keys)
1885
1886    def extension(self, namespace: str) -> Any:
1887        """The JSON value stored under ``namespace``, or ``None``.
1888
1889        Only that value is decoded; the module is not serialized.
1890        """
1891        text = self._inner._extension_json(namespace)
1892        return None if text is None else _json.loads(text)
1893
1894    def with_extension(self, namespace: str, value: Any) -> "PioModule":
1895        """A copy of this module carrying ``value`` under ``namespace``.
1896
1897        ``value`` must be JSON serializable. The copy keeps the typed value,
1898        diagnostics, sources, and history without serializing them; an
1899        extension already stored under ``namespace`` is replaced. The original
1900        module is unchanged.
1901        """
1902        return PioModule(self._inner._with_extension_json(namespace, _json.dumps(value)))
1903
1904    def to_balanced_report(self, base_mva: float = 100.0) -> Any:
1905        """Report whether a multiconductor network can become balanced."""
1906        return _json.loads(self._inner.lowering_readiness_json(base_mva))
1907
1908    def to_balanced(self, base_mva: float = 100.0) -> "PioModule":
1909        """Transform a multiconductor network to a balanced module."""
1910        return PioModule(self._inner.lower_to_balanced(base_mva))
1911
1912    def to_dc_pf_instance(self) -> "PioModule":
1913        """Build a DC power flow instance from a balanced network module."""
1914        return PioModule(self._inner._to_dc_pf_instance())
1915
1916    def to_ac_pf_instance(self) -> "PioModule":
1917        """Build an AC power flow instance from a balanced network module."""
1918        return PioModule(self._inner._to_ac_pf_instance())
1919
1920    def to_dc_opf_instance(self) -> "PioModule":
1921        """Build a DC optimal power flow instance from a balanced network module."""
1922        return PioModule(self._inner._to_dc_opf_instance())
1923
1924    def to_ac_opf_instance(self) -> "PioModule":
1925        """Build an AC optimal power flow instance from a balanced network module."""
1926        return PioModule(self._inner._to_ac_opf_instance())
1927
1928    def to_ac_ots_instance(
1929        self,
1930        *,
1931        switchable: Union[str, Sequence[str], None] = None,
1932        switching_costs: Optional[Mapping[str, tuple[float, float]]] = None,
1933        islanding: Optional[str] = None,
1934        max_open: Optional[int] = None,
1935        max_switched: Optional[int] = None,
1936        current_limits: Optional[str] = None,
1937        stated_current_limits: Optional[
1938            Mapping[str, tuple[Optional[float], Optional[float]]]
1939        ] = None,
1940    ) -> "PioModule":
1941        """Build an AC optimal transmission switching instance from a balanced
1942        network, AC optimal power flow, or AC optimal transmission switching
1943        module.
1944
1945        With no option, this gives the default instance: every initially
1946        in-service branch may switch, at zero cost, islanding is forbidden,
1947        there is no budget and no current limit, and the objective gains the
1948        switching cost term. An AC optimal transmission switching module comes
1949        back unchanged.
1950
1951        Any option makes the options explicit, as the C ABI's options struct
1952        and PowerIO.jl's ``AcOtsOptions`` do, and an option not given takes
1953        its explicit default:
1954
1955        - ``switchable``: ``"all"`` (the default, which includes initially
1956          open branches), ``"none"``, or a list of branch identities.
1957        - ``switching_costs``: ``{branch_id: (open_cost, close_cost)}``; a
1958          branch with no entry switches at zero cost.
1959        - ``islanding``: ``"forbidden"`` (the default) or ``"allowed"``.
1960        - ``max_open``: the most branches open in the final topology,
1961          counting fixed open rows; ``None`` is no budget.
1962        - ``max_switched``: the most status changes; ``None`` is no budget.
1963        - ``current_limits``: ``"skip"`` (the default), ``"stated"``, or
1964          ``"derive_from_rate_a"``.
1965        - ``stated_current_limits``: ``{branch_id: (from_pu, to_pu)}``, per
1966          unit; ``None`` on a side is unbounded.
1967
1968        The base problem and objective are kept, and the objective gains the
1969        switching cost term once. Refused options raise
1970        :class:`PowerIOError` with code
1971        ``BUILD.INSTANCE.SWITCHING_OPTIONS_INVALID``; an unknown policy name
1972        raises :class:`ValueError`.
1973        """
1974        if (
1975            switchable is None
1976            and switching_costs is None
1977            and islanding is None
1978            and max_open is None
1979            and max_switched is None
1980            and current_limits is None
1981            and stated_current_limits is None
1982        ):
1983            return PioModule(self._inner._to_ac_ots_instance())
1984        if switchable is None:
1985            selection, identities = "all", []
1986        elif isinstance(switchable, str):
1987            selection, identities = switchable, []
1988        else:
1989            selection, identities = "only", [str(identity) for identity in switchable]
1990        for name, budget in (("max_open", max_open), ("max_switched", max_switched)):
1991            if budget is not None and (
1992                isinstance(budget, bool) or not isinstance(budget, int) or budget < 0
1993            ):
1994                raise ValueError(f"{name} must be a nonnegative integer or None")
1995        costs = [
1996            (str(identity), float(open_cost), float(close_cost))
1997            for identity, (open_cost, close_cost) in (switching_costs or {}).items()
1998        ]
1999        limits = [
2000            (
2001                str(identity),
2002                None if from_pu is None else float(from_pu),
2003                None if to_pu is None else float(to_pu),
2004            )
2005            for identity, (from_pu, to_pu) in (stated_current_limits or {}).items()
2006        ]
2007        return PioModule(
2008            self._inner._to_ac_ots_instance_with_options(
2009                selection,
2010                identities,
2011                costs,
2012                "forbidden" if islanding is None else islanding,
2013                max_open,
2014                max_switched,
2015                "skip" if current_limits is None else current_limits,
2016                limits,
2017            )
2018        )
2019
2020    def to_mc_ac_pf_instance(self) -> "PioModule":
2021        """Build a multiconductor AC power flow instance from a network module."""
2022        return PioModule(self._inner._to_mc_ac_pf_instance())
2023
2024    def to_mc_ac_opf_instance(self) -> "PioModule":
2025        """Build a multiconductor AC optimal power flow instance from a network module."""
2026        return PioModule(self._inner._to_mc_ac_opf_instance())
2027
2028    def to_lindist3flow_opf_instance(self) -> "PioModule":
2029        """Build a LinDist3Flow optimal power flow instance from a network module."""
2030        return PioModule(self._inner._to_lindist3flow_opf_instance())
2031
2032    def to_lindist3flow_pf_instance(self) -> "PioModule":
2033        """Build a fixed-dispatch LinDist3Flow instance from a network module."""
2034        return PioModule(self._inner._to_lindist3flow_pf_instance())
2035
2036    def __repr__(self) -> str:
2037        return repr(self._inner)
2038
2039
2040def _selected_collection_value(location: _CollectionEntry) -> Any:
2041    value = location.root.value
2042    time_index = location.time_index
2043    scenario_id = location.scenario_id
2044    while time_index is not None or scenario_id is not None:
2045        if isinstance(value, TimeSeries) and time_index is not None:
2046            value = value[time_index]
2047            time_index = None
2048        elif isinstance(value, ScenarioSet) and scenario_id is not None:
2049            value = value[scenario_id]
2050            scenario_id = None
2051        elif time_index is not None:
2052            raise TypeError("the selected value is not a TimeSeries")
2053        else:
2054            raise TypeError("the selected value is not a ScenarioSet")
2055    return value
2056
2057
2058def _refresh_collection_entry(target: Any, location: _CollectionEntry) -> None:
2059    refreshed = _selected_collection_value(location)
2060    if type(refreshed) is not type(target):
2061        raise RuntimeError("a collection update changed the entry type")
2062    if isinstance(target, BalancedNetwork):
2063        target._inner = refreshed._inner
2064        # Counts cached from the replaced handle may no longer hold, for
2065        # example the island count after a branch status update.
2066        for name in [name for name in vars(target) if name.startswith("n_")]:
2067            del target.__dict__[name]
2068    elif isinstance(target, dist.MulticonductorNetwork):
2069        target._inner = refreshed._inner
2070    elif isinstance(target, _TypedValue):
2071        target.module = refreshed.module
2072        target._collection_entry = refreshed._collection_entry
2073    else:
2074        raise TypeError("the selected value does not support typed updates")
2075
2076
2077@_guard
2078def apply_updates(
2079    target: Any,
2080    updates: Union[
2081        Iterable[OperatingPointUpdate],
2082        Iterable[NetworkUpdate],
2083        Iterable[CalculationUpdate],
2084    ],
2085) -> UpdateReport:
2086    """Validate and apply one batch of typed updates atomically.
2087
2088    ``updates`` contains one update class: :class:`OperatingPointUpdate`,
2089    :class:`NetworkUpdate`, or :class:`CalculationUpdate`. Values are absolute
2090    replacements and power quantities carry their units in the typed value.
2091    ``target`` is a module or a value obtained by indexing a :class:`TimeSeries`
2092    or :class:`ScenarioSet`. If validation fails, the module is unchanged.
2093    """
2094    batch = list(updates)
2095    if isinstance(target, PioModule):
2096        return target._inner._apply_updates(batch)
2097    location = getattr(target, "_collection_entry", None)
2098    if not isinstance(location, _CollectionEntry):
2099        raise TypeError(
2100            "target must be a PioModule or a TimeSeries/ScenarioSet entry"
2101        )
2102    report = location.root._inner._apply_collection_updates(
2103        batch,
2104        time_index=location.time_index,
2105        scenario_id=location.scenario_id,
2106    )
2107    _refresh_collection_entry(target, location)
2108    return report
2109
2110
2111@_guard
2112def apply_bus_load_active_power(
2113    module: PioModule,
2114    bus_id: int,
2115    total: ActivePower,
2116    *,
2117    allocation: str = "proportional_to_current_active_power",
2118) -> UpdateReport:
2119    """Replace aggregate bus demand through an explicit PowerIO allocation rule.
2120
2121    ``"proportional_to_current_active_power"`` preserves each participating
2122    load's current share. ``"equal"`` gives every participating load the same
2123    share, including when their current aggregate demand is zero. PowerIO
2124    requires stable load IDs and reports each load changed.
2125    """
2126    if not isinstance(module, PioModule):
2127        raise TypeError("module must be a PioModule")
2128    if not isinstance(total, ActivePower):
2129        raise TypeError("total must be an ActivePower")
2130    return module._inner._apply_bus_load_active_power(
2131        bus_id,
2132        total,
2133        allocation=allocation,
2134    )
2135
2136
2137def _path_from_source(source: Any) -> Optional[str]:
2138    if isinstance(source, str):
2139        return source
2140    if isinstance(source, (bytes, bytearray, memoryview)):
2141        return None
2142    try:
2143        path = _os.fspath(source)
2144    except TypeError:
2145        return None
2146    if isinstance(path, bytes):
2147        raise TypeError("a path-like source must return str, not bytes")
2148    return path
2149
2150
2151def _memory_from_source(source: Any, name: Optional[str]) -> tuple[bytes, str]:
2152    if isinstance(source, (bytes, bytearray, memoryview)):
2153        data = bytes(source)
2154    else:
2155        read = getattr(source, "read", None)
2156        if read is None:
2157            raise TypeError(
2158                "source must be a path, file object, or bytes-like object"
2159            )
2160        data = read()
2161        if isinstance(data, str):
2162            data = data.encode("utf-8")
2163        elif isinstance(data, (bytes, bytearray, memoryview)):
2164            data = bytes(data)
2165        else:
2166            raise TypeError("source.read() must return str or bytes-like data")
2167    if name is None:
2168        candidate = getattr(source, "name", None)
2169        try:
2170            candidate = _os.fspath(candidate) if candidate is not None else None
2171        except TypeError:
2172            candidate = None
2173        name = candidate if isinstance(candidate, str) else "<memory>"
2174    if not isinstance(name, str):
2175        raise TypeError("name must be a string")
2176    return data, name
2177
2178
2179@_guard
2180def parse(
2181    source: Any,
2182    *,
2183    format: Optional[str] = None,
2184    name: Optional[str] = None,
2185    sincal_multiconductor: Optional[dist.SincalReadOptions] = None,
2186    sincal_balanced: Optional[SincalBalancedReadOptions] = None,
2187    acquisition_root: Optional[Any] = None,
2188    named_buffers: Optional[Mapping[str, bytes]] = None,
2189) -> PioModule:
2190    """Parse a path, file object, or bytes-like source.
2191
2192    A string is always a path. Pass raw text through ``io.StringIO`` or
2193    another file object. ``sincal_multiconductor`` requires explicit format
2194    ``sincal-multiconductor``; ``sincal_balanced`` requires ``sincal-balanced``.
2195    File companions stay beneath the file's parent,
2196    or an explicitly selected ``acquisition_root``. Memory sources use only
2197    ``named_buffers`` and never acquire companions from the filesystem.
2198    """
2199    from . import _sienna_files
2200    if format is not None and format in _sienna_files.FORMATS:
2201        if sincal_balanced is not None or sincal_multiconductor is not None:
2202            raise ValueError("SINCAL options do not apply to Sienna bundles")
2203        return _sienna_files.parse(source, format, name=name, acquisition_root=acquisition_root, named_buffers=named_buffers)
2204    from . import _pypsa_files
2205    binary_format = _pypsa_files.detect(source, format)
2206    if binary_format is not None:
2207        if named_buffers is not None or acquisition_root is not None or sincal_balanced is not None or sincal_multiconductor is not None:
2208            raise ValueError("PyPSA binary containers are standalone sources")
2209        if name is not None and _path_from_source(source) is not None:
2210            raise ValueError("name is only valid for memory and file object sources")
2211        return _pypsa_files.parse(source, binary_format, name=name)
2212    balanced_selection, selection = _native_selections(sincal_balanced, sincal_multiconductor)
2213    path = _path_from_source(source)
2214    if path is not None:
2215        if name is not None:
2216            raise ValueError("name is only valid for memory and file object sources")
2217        if named_buffers is not None:
2218            raise ValueError("named_buffers applies only to memory and file object sources")
2219        root = _path_from_source(acquisition_root) if acquisition_root is not None else None
2220        if acquisition_root is not None and root is None:
2221            raise TypeError("acquisition_root must be a path")
2222        return PioModule(_powerio._PioModule._parse_path(path, format, selection, root, balanced_selection))
2223    if acquisition_root is not None:
2224        raise ValueError("acquisition_root applies only to path sources")
2225    buffers = None
2226    if named_buffers is not None:
2227        if not isinstance(named_buffers, Mapping):
2228            raise TypeError("named_buffers must map relative names to bytes-like data")
2229        buffers = []
2230        for buffer_name, buffer_data in named_buffers.items():
2231            if not isinstance(buffer_name, str) or not isinstance(buffer_data, (bytes, bytearray, memoryview)):
2232                raise TypeError("named_buffers must map relative names to bytes-like data")
2233            buffers.append((buffer_name, bytes(buffer_data)))
2234    data, source_name = _memory_from_source(source, name)
2235    return PioModule(_powerio._PioModule._parse_memory(data, source_name, format, selection, buffers, balanced_selection))
2236
2237
2238def _result_from_native(result: dict[str, Any]) -> EmitResult:
2239    return EmitResult(
2240        artifacts=tuple(Artifact(**artifact) for artifact in result["artifacts"]),
2241        layout=result["layout"],
2242        fidelity=result["fidelity"],
2243        diagnostics=tuple(result["diagnostics"]),
2244    )
2245
2246
2247def _emit_to_destination(
2248    module: PioModule,
2249    destination: Optional[Any],
2250    memory_call: Any,
2251    path_call: Any,
2252) -> EmitResult:
2253    if not isinstance(module, PioModule):
2254        raise TypeError("module must be a PioModule")
2255    if destination is None:
2256        return _result_from_native(memory_call())
2257    path = _path_from_source(destination)
2258    if path is not None:
2259        return _result_from_native(path_call(path))
2260    write = getattr(destination, "write", None)
2261    if write is None:
2262        raise TypeError("destination must be a path or writable file object")
2263    result = _result_from_native(memory_call())
2264    if result.layout != "file" or len(result.artifacts) != 1:
2265        raise ValueError("a directory emission requires a path destination")
2266    data = result.artifacts[0].data
2267    if data is None:
2268        raise ValueError("the emission returned no artifact bytes to write")
2269    # A text mode stream takes str and a binary one takes bytes. Ask a real
2270    # stream which it is rather than writing bytes and retrying on TypeError:
2271    # a TypeError raised inside the stream's own write would otherwise trigger
2272    # a second, partially duplicated write. A duck typed sink states neither,
2273    # so it keeps the retry.
2274    if isinstance(destination, _io.TextIOBase) or isinstance(
2275        getattr(destination, "encoding", None), str
2276    ):
2277        write(data.decode("utf-8"))
2278    elif isinstance(destination, (_io.RawIOBase, _io.BufferedIOBase)):
2279        write(data)
2280    else:
2281        try:
2282            write(data)
2283        except TypeError:
2284            write(data.decode("utf-8"))
2285    return result
2286
2287
2288@_guard
2289def emit(module: PioModule, format: str, destination: Optional[Any] = None) -> EmitResult:
2290    """Emit a module as one grid exchange format."""
2291    from . import _sienna_files
2292    if format is not None and format in _sienna_files.FORMATS:
2293        return _sienna_files.emit(module, format, destination)
2294    from . import _pypsa_files
2295    if format in _pypsa_files.FORMATS:
2296        if not isinstance(module, PioModule):
2297            raise TypeError("module must be a PioModule")
2298        return _pypsa_files.emit(module, format, destination)
2299    return _emit_to_destination(
2300        module,
2301        destination,
2302        lambda: module._inner._emit_memory(format),
2303        lambda path: module._inner._emit_path(format, path),
2304    )
2305
2306
2307@_guard
2308def serialize(module: PioModule, destination: Optional[Any] = None) -> EmitResult:
2309    """Serialize a module as PowerIO IR."""
2310    return _emit_to_destination(
2311        module,
2312        destination,
2313        module._inner._serialize_memory,
2314        module._inner._serialize_path,
2315    )
2316
2317
2318@_guard
2319def deserialize(source: Any) -> PioModule:
2320    """Deserialize PowerIO IR from a path, file object, or bytes-like source."""
2321    path = _path_from_source(source)
2322    if path is not None:
2323        return PioModule(_powerio._PioModule._deserialize_path(path))
2324    data, _ = _memory_from_source(source, None)
2325    return PioModule(_powerio._PioModule._deserialize_memory(data))
2326
2327
2328@_guard
2329def features() -> dict[str, bool]:
2330    """The build-time features compiled into this powerio installation.
2331
2332    ``matrix``, ``dist``, and ``prob`` are unconditional dependencies of the
2333    extension and are always ``True``. ``gridfm`` reports whether GridFM
2334    Parquet parsing and emission were compiled in; the published wheel
2335    includes them, while a custom source build can omit them.
2336    """
2337    return {
2338        "matrix": True,
2339        "gridfm": bool(getattr(_powerio, "_has_gridfm", False)),
2340        "dist": True,
2341        "prob": True,
2342    }
2343
2344
2345@_guard
2346def diagnostic_record(diagnostic: Diagnostic) -> dict[str, Any]:
2347    """One diagnostic as a JSON-ready dictionary.
2348
2349    ``code``, ``severity``, ``message``, and ``target`` are always present, in
2350    that order. ``id``, ``suggested_action``, and ``related`` follow when the
2351    diagnostic sets them, ``details`` when it is not ``None``, and ``spans``
2352    as ``source``, ``byte_start``, ``byte_end`` dictionaries when the
2353    diagnostic carries at least one span.
2354    """
2355    record: dict[str, Any] = {
2356        "code": diagnostic.code,
2357        "severity": diagnostic.severity,
2358        "message": diagnostic.message,
2359        "target": diagnostic.target,
2360    }
2361    if diagnostic.id:
2362        record["id"] = diagnostic.id
2363    if diagnostic.suggested_action:
2364        record["suggested_action"] = diagnostic.suggested_action
2365    if diagnostic.related:
2366        record["related"] = list(diagnostic.related)
2367    if diagnostic.details is not None:
2368        record["details"] = diagnostic.details
2369    if diagnostic.spans:
2370        record["spans"] = [
2371            {
2372                "source": span.source,
2373                "byte_start": span.byte_start,
2374                "byte_end": span.byte_end,
2375            }
2376            for span in diagnostic.spans
2377        ]
2378    return record
2379
2380
2381@_guard
2382def diagnostic_records(diagnostics: Iterable[Diagnostic]) -> list[dict[str, Any]]:
2383    """Every diagnostic as a JSON-ready dictionary, in the order given."""
2384    return [diagnostic_record(item) for item in diagnostics]
class AcOpfInstance(_BalancedCalculation):
1426class AcOpfInstance(_BalancedCalculation):
1427    """An AC optimal power flow calculation instance."""

An AC optimal power flow calculation instance.

class AcOpfSolution(_BalancedCalculation, _CalculationSolution):
1544class AcOpfSolution(_BalancedCalculation, _CalculationSolution):
1545    """An AC optimal power flow solution."""

An AC optimal power flow solution.

class AcOtsInstance(_BalancedCalculation):
1437@_guard_class
1438class AcOtsInstance(_BalancedCalculation):
1439    """An AC optimal transmission switching calculation instance.
1440
1441    Its network holds every candidate branch at its initial status.
1442    """
1443
1444    @property
1445    def options(self) -> dict[str, Any]:
1446        """The switching options as stated, spelled as the keyword arguments of
1447        :meth:`PioModule.to_ac_ots_instance`: ``switchable`` (``"all"``,
1448        ``"none"``, or a list of branch identities), ``switching_costs``
1449        (``{id: (open_cost, close_cost)}``), ``islanding``, ``max_open``,
1450        ``max_switched``, ``current_limits``, and ``stated_current_limits``
1451        (``{id: (from_pu, to_pu)}``, ``None`` for an unbounded side).
1452        """
1453        return self.module._inner._ac_ots_options()
1454
1455    @property
1456    def branches(self) -> list[dict[str, Any]]:
1457        """One row per physical branch, in branch table order: ``id``,
1458        ``initial_closed``, ``switchable``, ``switching_cost`` (``(open_cost,
1459        close_cost)``, or ``None`` when no cost is stated and the branch
1460        switches at zero cost), ``stated_current`` (the stated ``(from_pu,
1461        to_pu)`` limits), and ``current`` (the limits that apply under the
1462        current limit policy). ``None`` in a limit pair is unbounded.
1463        """
1464        return self.module._inner._ac_ots_branches()
1465
1466    def validate_topology(self, closed: Sequence[bool]) -> float:
1467        """Check a final topology and return its switching cost.
1468
1469        ``closed`` holds one boolean per branch, in branch table order. The
1470        check covers the length, the branches that cannot switch, the
1471        ``max_open`` and ``max_switched`` budgets, and the islanding policy;
1472        it does not certify AC feasibility. A refused topology raises
1473        :class:`PowerIOError` with code ``BUILD.INSTANCE.TOPOLOGY_INVALID``.
1474        """
1475        return self.module._inner._ac_ots_validate_topology(_branch_statuses(closed))
1476
1477    def fix_topology(
1478        self, closed: Sequence[bool]
1479    ) -> tuple["AcOpfInstance", list[Diagnostic]]:
1480        """The AC optimal power flow over a final topology.
1481
1482        Every branch row stays in the network with its final status. The
1483        switching options, current limits, and switching cost term are not
1484        part of the AC optimal power flow; the returned diagnostics report
1485        each one dropped, and the instance's module carries them too. The
1486        topology is checked as :meth:`validate_topology` checks it.
1487        """
1488        inner, diagnostics = self.module._inner._ac_ots_fix_topology(
1489            _branch_statuses(closed)
1490        )
1491        return PioModule(inner).value, list(diagnostics)

An AC optimal transmission switching calculation instance.

Its network holds every candidate branch at its initial status.

options: powerio.AcOtsOptions
1444    @property
1445    def options(self) -> dict[str, Any]:
1446        """The switching options as stated, spelled as the keyword arguments of
1447        :meth:`PioModule.to_ac_ots_instance`: ``switchable`` (``"all"``,
1448        ``"none"``, or a list of branch identities), ``switching_costs``
1449        (``{id: (open_cost, close_cost)}``), ``islanding``, ``max_open``,
1450        ``max_switched``, ``current_limits``, and ``stated_current_limits``
1451        (``{id: (from_pu, to_pu)}``, ``None`` for an unbounded side).
1452        """
1453        return self.module._inner._ac_ots_options()

The switching options as stated, spelled as the keyword arguments of PioModule.to_ac_ots_instance(): switchable ("all", "none", or a list of branch identities), switching_costs ({id: (open_cost, close_cost)}), islanding, max_open, max_switched, current_limits, and stated_current_limits ({id: (from_pu, to_pu)}, None for an unbounded side).

branches: List[powerio.AcOtsBranch]
1455    @property
1456    def branches(self) -> list[dict[str, Any]]:
1457        """One row per physical branch, in branch table order: ``id``,
1458        ``initial_closed``, ``switchable``, ``switching_cost`` (``(open_cost,
1459        close_cost)``, or ``None`` when no cost is stated and the branch
1460        switches at zero cost), ``stated_current`` (the stated ``(from_pu,
1461        to_pu)`` limits), and ``current`` (the limits that apply under the
1462        current limit policy). ``None`` in a limit pair is unbounded.
1463        """
1464        return self.module._inner._ac_ots_branches()

One row per physical branch, in branch table order: id, initial_closed, switchable, switching_cost ((open_cost, close_cost), or None when no cost is stated and the branch switches at zero cost), stated_current (the stated (from_pu, to_pu) limits), and current (the limits that apply under the current limit policy). None in a limit pair is unbounded.

def validate_topology(self, closed: Sequence[bool]) -> float:
1466    def validate_topology(self, closed: Sequence[bool]) -> float:
1467        """Check a final topology and return its switching cost.
1468
1469        ``closed`` holds one boolean per branch, in branch table order. The
1470        check covers the length, the branches that cannot switch, the
1471        ``max_open`` and ``max_switched`` budgets, and the islanding policy;
1472        it does not certify AC feasibility. A refused topology raises
1473        :class:`PowerIOError` with code ``BUILD.INSTANCE.TOPOLOGY_INVALID``.
1474        """
1475        return self.module._inner._ac_ots_validate_topology(_branch_statuses(closed))

Check a final topology and return its switching cost.

closed holds one boolean per branch, in branch table order. The check covers the length, the branches that cannot switch, the max_open and max_switched budgets, and the islanding policy; it does not certify AC feasibility. A refused topology raises PowerIOError with code BUILD.INSTANCE.TOPOLOGY_INVALID.

def fix_topology( self, closed: Sequence[bool]) -> Tuple[AcOpfInstance, List[Diagnostic]]:
1477    def fix_topology(
1478        self, closed: Sequence[bool]
1479    ) -> tuple["AcOpfInstance", list[Diagnostic]]:
1480        """The AC optimal power flow over a final topology.
1481
1482        Every branch row stays in the network with its final status. The
1483        switching options, current limits, and switching cost term are not
1484        part of the AC optimal power flow; the returned diagnostics report
1485        each one dropped, and the instance's module carries them too. The
1486        topology is checked as :meth:`validate_topology` checks it.
1487        """
1488        inner, diagnostics = self.module._inner._ac_ots_fix_topology(
1489            _branch_statuses(closed)
1490        )
1491        return PioModule(inner).value, list(diagnostics)

The AC optimal power flow over a final topology.

Every branch row stays in the network with its final status. The switching options, current limits, and switching cost term are not part of the AC optimal power flow; the returned diagnostics report each one dropped, and the instance's module carries them too. The topology is checked as validate_topology() checks it.

class AcOtsSolution(_BalancedCalculation, _CalculationSolution):
1548@_guard_class
1549class AcOtsSolution(_BalancedCalculation, _CalculationSolution):
1550    """An AC optimal transmission switching result.
1551
1552    Its network is the instance's network, with the initial branch statuses;
1553    :meth:`solved_network` gives the network with the final statuses and
1554    solved values.
1555    """
1556
1557    @classmethod
1558    def from_ac_opf_solution(
1559        cls,
1560        instance: AcOtsInstance,
1561        closed: Sequence[bool],
1562        solution: "AcOpfSolution",
1563    ) -> "AcOtsSolution":
1564        """Attach the AC optimal power flow solution computed on
1565        ``instance.fix_topology(closed)``.
1566
1567        The topology is checked as :meth:`AcOtsInstance.validate_topology`
1568        checks it, the solution must answer exactly the fixed-topology problem
1569        (its network, objective, and constraint selections), and open branches
1570        must carry no flow. Residuals and optimality are not checked. The
1571        result's module carries the instance module's records.
1572        """
1573        if not isinstance(instance, AcOtsInstance):
1574            raise TypeError("instance must be a powerio.AcOtsInstance")
1575        if not isinstance(solution, AcOpfSolution):
1576            raise TypeError("solution must be a powerio.AcOpfSolution")
1577        inner = instance.module._inner._ac_ots_solution(
1578            _branch_statuses(closed), solution.module._inner
1579        )
1580        return PioModule(inner).value
1581
1582    @property
1583    def branch_closed(self) -> list[bool]:
1584        """The final branch statuses, in branch table order."""
1585        return self.module._inner._ac_ots_solution_branch_closed()
1586
1587    @property
1588    def switching_cost(self) -> float:
1589        """The cost of the status changes against the initial topology."""
1590        return self.module._inner._ac_ots_solution_summary()[0]
1591
1592    @property
1593    def branches_open(self) -> int:
1594        """The number of branches open in the final topology."""
1595        return self.module._inner._ac_ots_solution_summary()[1]
1596
1597    @property
1598    def branches_switched(self) -> int:
1599        """The number of branches whose final status differs from the initial one."""
1600        return self.module._inner._ac_ots_solution_summary()[2]
1601
1602    @property
1603    def objective(self) -> float:
1604        """The AC solution's objective, plus the switching cost when the
1605        instance's objective states the switching cost term."""
1606        return self.module._inner._ac_ots_solution_summary()[3]
1607
1608    def solved_network(self) -> "PioModule":
1609        """The balanced network this result states: the final branch statuses
1610        with the solved bus voltages, generator dispatch, and branch flows
1611        applied, ready for :func:`emit`. The C ABI's
1612        ``pio_ac_ots_solution_materialize`` and PowerIO.jl's
1613        ``materialize_ac_ots_solution`` return the same network."""
1614        return PioModule(self.module._inner._ac_ots_solved_network())

An AC optimal transmission switching result.

Its network is the instance's network, with the initial branch statuses; solved_network() gives the network with the final statuses and solved values.

@classmethod
def from_ac_opf_solution( cls, instance: AcOtsInstance, closed: Sequence[bool], solution: AcOpfSolution) -> AcOtsSolution:
1557    @classmethod
1558    def from_ac_opf_solution(
1559        cls,
1560        instance: AcOtsInstance,
1561        closed: Sequence[bool],
1562        solution: "AcOpfSolution",
1563    ) -> "AcOtsSolution":
1564        """Attach the AC optimal power flow solution computed on
1565        ``instance.fix_topology(closed)``.
1566
1567        The topology is checked as :meth:`AcOtsInstance.validate_topology`
1568        checks it, the solution must answer exactly the fixed-topology problem
1569        (its network, objective, and constraint selections), and open branches
1570        must carry no flow. Residuals and optimality are not checked. The
1571        result's module carries the instance module's records.
1572        """
1573        if not isinstance(instance, AcOtsInstance):
1574            raise TypeError("instance must be a powerio.AcOtsInstance")
1575        if not isinstance(solution, AcOpfSolution):
1576            raise TypeError("solution must be a powerio.AcOpfSolution")
1577        inner = instance.module._inner._ac_ots_solution(
1578            _branch_statuses(closed), solution.module._inner
1579        )
1580        return PioModule(inner).value

Attach the AC optimal power flow solution computed on instance.fix_topology(closed).

The topology is checked as AcOtsInstance.validate_topology() checks it, the solution must answer exactly the fixed-topology problem (its network, objective, and constraint selections), and open branches must carry no flow. Residuals and optimality are not checked. The result's module carries the instance module's records.

branch_closed: List[bool]
1582    @property
1583    def branch_closed(self) -> list[bool]:
1584        """The final branch statuses, in branch table order."""
1585        return self.module._inner._ac_ots_solution_branch_closed()

The final branch statuses, in branch table order.

switching_cost: float
1587    @property
1588    def switching_cost(self) -> float:
1589        """The cost of the status changes against the initial topology."""
1590        return self.module._inner._ac_ots_solution_summary()[0]

The cost of the status changes against the initial topology.

branches_open: int
1592    @property
1593    def branches_open(self) -> int:
1594        """The number of branches open in the final topology."""
1595        return self.module._inner._ac_ots_solution_summary()[1]

The number of branches open in the final topology.

branches_switched: int
1597    @property
1598    def branches_switched(self) -> int:
1599        """The number of branches whose final status differs from the initial one."""
1600        return self.module._inner._ac_ots_solution_summary()[2]

The number of branches whose final status differs from the initial one.

objective: float
1602    @property
1603    def objective(self) -> float:
1604        """The AC solution's objective, plus the switching cost when the
1605        instance's objective states the switching cost term."""
1606        return self.module._inner._ac_ots_solution_summary()[3]

The AC solution's objective, plus the switching cost when the instance's objective states the switching cost term.

def solved_network(self) -> PioModule[BalancedNetwork]:
1608    def solved_network(self) -> "PioModule":
1609        """The balanced network this result states: the final branch statuses
1610        with the solved bus voltages, generator dispatch, and branch flows
1611        applied, ready for :func:`emit`. The C ABI's
1612        ``pio_ac_ots_solution_materialize`` and PowerIO.jl's
1613        ``materialize_ac_ots_solution`` return the same network."""
1614        return PioModule(self.module._inner._ac_ots_solved_network())

The balanced network this result states: the final branch statuses with the solved bus voltages, generator dispatch, and branch flows applied, ready for emit(). The C ABI's pio_ac_ots_solution_materialize and PowerIO.jl's materialize_ac_ots_solution return the same network.

class AcPfInstance(_BalancedCalculation):
1418class AcPfInstance(_BalancedCalculation):
1419    """An AC power flow calculation instance."""

An AC power flow calculation instance.

class AcPfSolution(_BalancedCalculation, _CalculationSolution):
1536class AcPfSolution(_BalancedCalculation, _CalculationSolution):
1537    """An AC power flow solution."""

An AC power flow solution.

class AcScucInstance(_BalancedCalculation):
1522@_guard_class
1523class AcScucInstance(_BalancedCalculation):
1524    """An AC security constrained unit commitment calculation instance."""
1525
1526    @property
1527    def inputs(self) -> ScucInputs:
1528        """Scheduling, reserve, and contingency inputs."""
1529        return self.module._inner._ac_scuc_inputs()

An AC security constrained unit commitment calculation instance.

inputs: ScucInputs
1526    @property
1527    def inputs(self) -> ScucInputs:
1528        """Scheduling, reserve, and contingency inputs."""
1529        return self.module._inner._ac_scuc_inputs()

Scheduling, reserve, and contingency inputs.

class AcScucSolution(_BalancedCalculation, _CalculationSolution):
1667@_guard_class
1668class AcScucSolution(_BalancedCalculation, _CalculationSolution):
1669    """An AC security constrained unit commitment solution."""
1670
1671    @property
1672    def termination(self) -> str:
1673        """How the calculation ended."""
1674        return self.module._inner._ac_scuc_solution_termination()
1675
1676    @property
1677    def residuals(self) -> Residuals:
1678        """Reported active and reactive power balance residuals."""
1679        return self.module._inner._ac_scuc_solution_residuals()
1680
1681    @property
1682    def producer(self) -> Optional[str]:
1683        """Producer or solver identity, when recorded."""
1684        return self.module._inner._ac_scuc_solution_producer()
1685
1686    @property
1687    def network_outputs(self) -> ScucNetworkOutputs:
1688        """Per interval network outputs."""
1689        return self.module._inner._ac_scuc_solution_network_outputs()
1690
1691    @property
1692    def device_outputs(self) -> ScucDeviceOutputs:
1693        """Per interval dispatchable device outputs."""
1694        return self.module._inner._ac_scuc_solution_device_outputs()
1695
1696    @property
1697    def objective(self) -> Optional[float]:
1698        """Reported objective value, when present."""
1699        return self.module._inner._ac_scuc_solution_objective()

An AC security constrained unit commitment solution.

termination: Literal['converged', 'iteration_limit', 'infeasible', 'unbounded', 'failed', 'not_reported']
1671    @property
1672    def termination(self) -> str:
1673        """How the calculation ended."""
1674        return self.module._inner._ac_scuc_solution_termination()

How the calculation ended.

residuals: Residuals
1676    @property
1677    def residuals(self) -> Residuals:
1678        """Reported active and reactive power balance residuals."""
1679        return self.module._inner._ac_scuc_solution_residuals()

Reported active and reactive power balance residuals.

producer: Optional[str]
1681    @property
1682    def producer(self) -> Optional[str]:
1683        """Producer or solver identity, when recorded."""
1684        return self.module._inner._ac_scuc_solution_producer()

Producer or solver identity, when recorded.

network_outputs: ScucNetworkOutputs
1686    @property
1687    def network_outputs(self) -> ScucNetworkOutputs:
1688        """Per interval network outputs."""
1689        return self.module._inner._ac_scuc_solution_network_outputs()

Per interval network outputs.

device_outputs: ScucDeviceOutputs
1691    @property
1692    def device_outputs(self) -> ScucDeviceOutputs:
1693        """Per interval dispatchable device outputs."""
1694        return self.module._inner._ac_scuc_solution_device_outputs()

Per interval dispatchable device outputs.

objective: Optional[float]
1696    @property
1697    def objective(self) -> Optional[float]:
1698        """Reported objective value, when present."""
1699        return self.module._inner._ac_scuc_solution_objective()

Reported objective value, when present.

class ActivePower:
def watts(value):
def megawatts(value):
value
unit
class ApparentPower:
def volt_amperes(value):
def megavolt_amperes(value):
value
unit
@dataclass(frozen=True)
class Artifact:
184@dataclass(frozen=True)
185class Artifact:
186    """One artifact produced by :func:`emit` or :func:`serialize`.
187
188    ``data`` is set for an in-memory result. ``path`` is set after committing
189    to a filesystem destination.
190    """
191
192    name: str
193    data: Optional[bytes]
194    path: Optional[str]
195
196    @property
197    def text(self) -> str:
198        """Decode an in-memory UTF-8 artifact."""
199        if self.data is None:
200            raise ValueError("this artifact was committed to a destination")
201        return self.data.decode("utf-8")

One artifact produced by emit() or serialize().

data is set for an in-memory result. path is set after committing to a filesystem destination.

Artifact(name: str, data: Optional[bytes], path: Optional[str])
name: str
data: Optional[bytes]
path: Optional[str]
text: str
196    @property
197    def text(self) -> str:
198        """Decode an in-memory UTF-8 artifact."""
199        if self.data is None:
200            raise ValueError("this artifact was committed to a destination")
201        return self.data.decode("utf-8")

Decode an in-memory UTF-8 artifact.

class BalancedNetwork:
 405@_guard_class
 406class BalancedNetwork:
 407    """A parsed balanced power network.
 408
 409    The data attributes (``buses``, ``branches``, ``generators``, ``loads``,
 410    ``shunts``) and reference bus queries delegate to the compiled handle; the
 411    matrix methods below return ``scipy.sparse`` objects. Parse and transform
 412    diagnostics belong to the owning :class:`PioModule`.
 413
 414    Errors: a bad file path raises the standard ``OSError`` subclass
 415    (``FileNotFoundError``); a malformed case raises :class:`PowerIOParseError`
 416    and an unmet calculation precondition (no generators, no reference bus) raises
 417    :class:`PowerIODataError`; both subclass :class:`PowerIOError`, so
 418    ``except PowerIOError`` catches either; an unknown
 419    ``scheme``/``formula``/``units`` string raises ``ValueError``.
 420    """
 421
 422    def __init__(self, inner: "_powerio._BalancedNetwork"):
 423        self._inner = inner
 424
 425    def __dir__(self):
 426        # The data attributes arrive through __getattr__, so name them here or
 427        # they stay invisible to tab completion.
 428        return sorted(set(super().__dir__()) | _BALANCED_DELEGATED_NAMES)
 429
 430    def __getattr__(self, name: str):
 431        # Reached only when normal lookup misses, so the matrix methods below
 432        # win. Guard underscore names so a lookup before _inner exists raises
 433        # AttributeError instead of recursing forever.
 434        if name not in _BALANCED_DELEGATED_NAMES:
 435            raise AttributeError(
 436                f"{type(self).__name__!r} object has no attribute {name!r}"
 437            )
 438        value = getattr(self._inner, name)
 439        # A native handle is immutable; scalar counts need no repeated FFI
 440        # call. A collection entry update replaces the handle and clears them.
 441        if name.startswith("n_"):
 442            self.__dict__[name] = value
 443        return value
 444
 445    def __repr__(self) -> str:
 446        # The inner handle's __repr__ already renders the public ``BalancedNetwork(...)``
 447        # form, so this is a straight delegate.
 448        return repr(self._inner)
 449
 450    def component_counts(self) -> dict[str, int]:
 451        """Count native lines, generators, loads, and substations.
 452
 453        Lines exclude transformer branches. Loads include equivalent injections
 454        represented as loads. Substations count the source hierarchy, or zero
 455        when the format supplies no hierarchy. No Python table rows are built.
 456        Raises ValueError for normalized networks, whose unity taps no longer
 457        distinguish lines from transformers. Count the source network instead.
 458        """
 459        return self._inner.component_counts()
 460
 461    def calc_connectivity_report(self) -> dict[str, Any]:
 462        """Calculate the in-service topology summary."""
 463        return self._inner.calc_connectivity_report()
 464
 465    def calc_stated_state_mismatch(
 466        self,
 467        *,
 468        top_k: int = 20,
 469        hvdc: str = "fixed_injection",
 470        low_impedance_threshold: float = 1e-3,
 471        merge_zero_impedance: bool = False,
 472        lcc_reactive_power: str = "converter_model",
 473    ) -> dict[str, Any]:
 474        """Evaluate every bus's AC balance at the voltages the case stores.
 475
 476        Each device sits at its stated output: generators at ``pg``/``qg``,
 477        loads through their voltage model at the stored magnitude, shunts at
 478        their stated admittance, and HVDC lines as fixed injections (or not,
 479        with ``hvdc="ignore"``). A bus mismatch is the power the network draws
 480        at the stored voltages minus the stated injection, MW and MVAr, so an
 481        injection equal to it closes the bus.
 482
 483        The result holds per bus columns in analysis bus order (``bus_ids``,
 484        ``island``, ``p_mw``, ``q_mvar``, and ``flags``, the attached
 485        equipment a residual is traced to), ``islands`` totals largest first,
 486        ``top`` (row indices of the largest mismatches), the totals, and
 487        ``diagnostics`` (a warning per LCC line that kept its stated reactive
 488        powers because its converter record reaches no operating point).
 489        ``merge_zero_impedance`` first merges the buses joined by in-service
 490        zero-impedance branches, whose flows the stored voltages cannot
 491        determine; without it such a branch raises. A closed switch joining
 492        two buses also raises (``BUILD.SWITCH.CLOSED``); merge it first with
 493        ``merge_buses(closed_switches=True)``. ``lcc_reactive_power``
 494        selects where a PSS/E two-terminal converter's reactive demand comes
 495        from: its bridge equations at the stored voltages
 496        (``"converter_model"``) or the line's stated reactive powers
 497        (``"stated"``).
 498        """
 499        return self._inner.calc_stated_state_mismatch(
 500            top_k=top_k,
 501            hvdc=hvdc,
 502            low_impedance_threshold=low_impedance_threshold,
 503            merge_zero_impedance=merge_zero_impedance,
 504            lcc_reactive_power=lcc_reactive_power,
 505        )
 506
 507    def calc_stated_branch_flows(self) -> dict[str, Any]:
 508        """Calculate the power entering every branch end at the stored voltages.
 509
 510        Columns follow analysis branch order: every branch row, then the three
 511        windings of each in-service three-winding transformer, as ``sources``
 512        states. Powers are MW and MVAr; an out-of-service branch carries zero.
 513        """
 514        return self._inner.calc_stated_branch_flows()
 515
 516    def to_geo_layer(self) -> dict[str, Any]:
 517        """Transform coordinates to a canonical GeoJSON FeatureCollection.
 518
 519        A case without coordinates produces an empty feature collection.
 520        """
 521        return _json.loads(self._inner.to_geo_layer_json())
 522
 523    def apply_geo_layer(
 524        self, text: str, name_hint: Optional[str] = None
 525    ) -> tuple["BalancedNetwork", dict[str, Any]]:
 526        """Apply a geographic sidecar and return ``(placed, report)``.
 527
 528        ``text`` is any form :func:`parse_geo` accepts; this case is
 529        unchanged. The report carries ``matched_buses``, ``matched_branches``,
 530        ``unmatched_features``, ``unlocated_buses``, ``unlocated_branches``,
 531        and ``notes``. The two unlocated counts cover the whole case when the
 532        pass ends, so a layer that matched nothing reads apart from a case
 533        that needed nothing. The placed copy drops the retained source text,
 534        so a same-format emission re-serializes.
 535        """
 536        inner, report = self._inner.apply_geo_layer(text, name_hint)
 537        return BalancedNetwork(inner), report
 538
 539    def resolve_contingencies(self, text: str) -> dict[str, Any]:
 540        """Read PSS/E contingency text and bind every case to this network.
 541
 542        ``text`` is the content of a ``.con`` file, such as
 543        ``parse("cases.con").value.text``. The result carries ``cases``,
 544        ``resolved``, ``unresolved``, and ``unrecognized_statements`` as
 545        counts; ``case_results``, one entry per case in the file's order with
 546        its ``name``, whether it ``resolved``, the ``components`` it bound to,
 547        and the actions that bound to nothing as ``{"action", "reason"}``; and
 548        ``diagnostics``, the reader's notes on statements it kept as text.
 549
 550        Each component states the ``type`` naming the table, the ``row`` it
 551        occupies there, the element's own ``in_service`` flag, and the ``id``
 552        the network states for it. ``id`` is ``None`` when the network states
 553        no identity for that row; ``type`` and ``row`` name the element either
 554        way.
 555
 556        Binding reports rather than refuses, so a case naming an element this
 557        network does not hold is counted unresolved and listed.
 558        """
 559        return self._inner.resolve_contingencies(text)
 560
 561    def expand_contingencies(
 562        self, con_text: str, sub_text: str
 563    ) -> tuple[str, list[Diagnostic]]:
 564        """Turn automatic contingency specifications into explicit cases.
 565
 566        ``con_text`` and ``sub_text`` are the contents of a ``.con`` and a
 567        ``.sub`` file. A specification such as ``SINGLE BRANCH IN SUBSYSTEM
 568        'A1'`` states a rule, so expanding it needs both the network and the
 569        subsystem the ``.sub`` file names. Returns the expanded ``.con`` text,
 570        which states every outage explicitly, and the notes from the two
 571        readers followed by the expansion's own notes. Only elements this
 572        network states in service expand into cases.
 573        """
 574        return self._inner.expand_contingencies(con_text, sub_text)
 575
 576    def select_subsystem_buses(self, sub_text: str, name: str) -> list[int]:
 577        """The bus numbers one named subsystem of ``sub_text`` selects.
 578
 579        ``sub_text`` is the content of a ``.sub`` file. The numbers come back
 580        in ascending order. A name the file does not state raises
 581        ``ValueError``.
 582        """
 583        return self._inner.select_subsystem_buses(sub_text, name)
 584
 585    # --- matrix calculations (scipy.sparse) -----------------------------
 586
 587    def calc_bprime_matrix(
 588        self, scheme: str = "bx", *, skip_zero_impedance: bool = False
 589    ):
 590        """MATPOWER FDPF Bp matrix. ``scheme`` is ``"bx"`` or ``"xb"``.
 591
 592        ``skip_zero_impedance=False`` refuses a zero impedance branch
 593        (``r`` and ``x`` both zero); pass ``True`` to drop it instead.
 594        """
 595        return _to_csr(
 596            self._inner.bprime(scheme, skip_zero_impedance=skip_zero_impedance)
 597        )
 598
 599    def calc_incidence_matrix(
 600        self, formula: str = "series_susceptance", *, skip_zero_impedance: bool = False
 601    ):
 602        """Return PowerModels incidence ``A`` (branches by buses).
 603
 604        Rows are the in service, non self loop branches in table order
 605        (three winding transformer windings follow the branches); columns
 606        are every bus in table order. :meth:`calc_dc_index_map` names both
 607        axes. ``skip_zero_impedance=False`` refuses a zero impedance branch;
 608        ``True`` drops it from the branch axis.
 609        """
 610        return _to_csr(
 611            self._inner.calc_incidence_matrix(
 612                formula, skip_zero_impedance=skip_zero_impedance
 613            )
 614        )
 615
 616    def calc_branch_susceptances(
 617        self, formula: str = "series_susceptance", *, skip_zero_impedance: bool = False
 618    ):
 619        """Return per branch susceptances over the branch axis of
 620        :meth:`calc_dc_index_map`."""
 621        np = _require("numpy", "matrix")
 622        return np.asarray(
 623            self._inner.calc_branch_susceptances(
 624                formula, skip_zero_impedance=skip_zero_impedance
 625            ),
 626            dtype=float,
 627        )
 628
 629    def calc_branch_flow_matrix(
 630        self, formula: str = "series_susceptance", *, skip_zero_impedance: bool = False
 631    ):
 632        """Return ``Bf = diag(b) A`` as a CSR matrix (branches by buses)."""
 633        return _to_csr(
 634            self._inner.calc_branch_flow_matrix(
 635                formula, skip_zero_impedance=skip_zero_impedance
 636            )
 637        )
 638
 639    def calc_bus_susceptance_matrix(
 640        self, formula: str = "series_susceptance", *, skip_zero_impedance: bool = False
 641    ):
 642        """Return ``B = A.T diag(b) A`` as a CSR matrix (buses by buses)."""
 643        return _to_csr(
 644            self._inner.calc_bus_susceptance_matrix(
 645                formula, skip_zero_impedance=skip_zero_impedance
 646            )
 647        )
 648
 649    def calc_branch_phase_shift_injection(
 650        self, formula: str = "series_susceptance", *, skip_zero_impedance: bool = False
 651    ):
 652        """Return ``b * shift`` over the branch axis."""
 653        np = _require("numpy", "matrix")
 654        return np.asarray(
 655            self._inner.calc_branch_phase_shift_injection(
 656                formula, skip_zero_impedance=skip_zero_impedance
 657            ),
 658            dtype=float,
 659        )
 660
 661    def calc_bus_phase_shift_injection(
 662        self, formula: str = "series_susceptance", *, skip_zero_impedance: bool = False
 663    ):
 664        """Return ``A.T @ (b * shift)`` over the bus axis."""
 665        np = _require("numpy", "matrix")
 666        return np.asarray(
 667            self._inner.calc_bus_phase_shift_injection(
 668                formula, skip_zero_impedance=skip_zero_impedance
 669            ),
 670            dtype=float,
 671        )
 672
 673    def calc_branch_flow_dc(
 674        self,
 675        voltage_angles,
 676        formula: str = "series_susceptance",
 677        *,
 678        skip_zero_impedance: bool = False,
 679    ):
 680        """Compute ``-Bf @ va + b * shift`` over the branch axis."""
 681        np, angles = _dc_angles(self.n_buses, voltage_angles)
 682        return np.asarray(
 683            self._inner.calc_branch_flow_dc(
 684                angles.tolist(), formula, skip_zero_impedance=skip_zero_impedance
 685            ),
 686            dtype=float,
 687        )
 688
 689    def calc_bus_injection_dc(
 690        self,
 691        voltage_angles,
 692        formula: str = "series_susceptance",
 693        *,
 694        skip_zero_impedance: bool = False,
 695    ):
 696        """Compute ``-B @ va + p_shift`` over the bus axis."""
 697        np, angles = _dc_angles(self.n_buses, voltage_angles)
 698        return np.asarray(
 699            self._inner.calc_bus_injection_dc(
 700                angles.tolist(), formula, skip_zero_impedance=skip_zero_impedance
 701            ),
 702            dtype=float,
 703        )
 704
 705    def calc_dc_index_map(
 706        self, formula: str = "series_susceptance", *, skip_zero_impedance: bool = False
 707    ) -> dict[str, Any]:
 708        """Return the axes every DC calculation shares.
 709
 710        ``bus_ids`` maps a bus axis row to the source bus id (every bus, in
 711        table order). ``branch_rows`` maps a branch axis row to the position
 712        in the branch table (three winding transformer windings follow the
 713        branches) and ``branch_ids`` to the stable identity, the branch uid
 714        when the source states one and ``branches:<row>`` otherwise; out of
 715        service branches and self loops have no row. ``skipped_branch_rows``
 716        lists the zero impedance branches dropped under
 717        ``skip_zero_impedance=True`` and is empty otherwise. The same
 718        selection applies to :meth:`calc_ptdf` rows and :meth:`calc_lodf`.
 719        """
 720        return self._inner.calc_dc_index_map(
 721            formula, skip_zero_impedance=skip_zero_impedance
 722        )
 723
 724    def calc_bdoubleprime_matrix(
 725        self, scheme: str = "bx", *, skip_zero_impedance: bool = False
 726    ):
 727        """MATPOWER FDPF Bpp matrix. ``scheme`` is ``"bx"`` or ``"xb"``.
 728        ``skip_zero_impedance`` as in :meth:`calc_bprime_matrix`.
 729        """
 730        return _to_csr(
 731            self._inner.bdoubleprime(scheme, skip_zero_impedance=skip_zero_impedance)
 732        )
 733
 734    def calc_lacpf_matrix(
 735        self,
 736        *,
 737        include_taps: bool = True,
 738        include_shifts: bool = True,
 739        skip_zero_impedance: bool = False,
 740    ):
 741        """LACPF 2n×2n block ``[[G, -B], [-B, -G]]``. ``skip_zero_impedance``
 742        as in :meth:`calc_bprime_matrix`."""
 743        return _to_csr(
 744            self._inner.lacpf(
 745                include_taps=include_taps,
 746                include_shifts=include_shifts,
 747                skip_zero_impedance=skip_zero_impedance,
 748            )
 749        )
 750
 751    def calc_adjacency_matrix(self):
 752        """0/1 bus adjacency matrix."""
 753        return _to_csr(self._inner.adjacency())
 754
 755    def calc_admittance_matrix(
 756        self,
 757        *,
 758        include_taps: bool = True,
 759        include_shifts: bool = True,
 760        skip_zero_impedance: bool = False,
 761    ):
 762        """``Y_bus = G + jB`` as a complex csr_matrix. ``skip_zero_impedance``
 763        as in :meth:`calc_bprime_matrix`."""
 764        g, b = self._inner.ybus_parts(
 765            include_taps=include_taps,
 766            include_shifts=include_shifts,
 767            skip_zero_impedance=skip_zero_impedance,
 768        )
 769        g, b = _to_csr(g), _to_csr(b)
 770        return (g + 1j * b).tocsr()
 771
 772    def calc_ptdf(self, formula: str = "series_susceptance", solver: str = "auto"):
 773        """DC PTDF (m×n). ``formula`` is ``"series_susceptance"``,
 774        ``"tap_adjusted_reactance"``, ``"reactance_only"``,
 775        ``"tap_adjusted_series_susceptance"``, or
 776        ``"series_susceptance_no_phase_shift"``.
 777
 778        ``solver`` is ``"auto"``, ``"dense"``, or ``"sparse"``. ``"auto"``
 779        uses the dense factorization on small cases and the sparse Cholesky
 780        path on large ones, the same policy as the CLI.
 781        """
 782        return _to_csr(self._inner.ptdf(formula, solver))
 783
 784    def calc_lodf(self, formula: str = "series_susceptance", solver: str = "auto"):
 785        """DC LODF (m×m). ``formula`` and ``solver`` as in :meth:`calc_ptdf`."""
 786        return _to_csr(self._inner.lodf(formula, solver))
 787
 788    def calc_weighted_laplacian(
 789        self,
 790        formula: str = "series_susceptance",
 791    ):
 792        """Weighted Laplacian ``L = -B``. ``formula`` as in :meth:`calc_ptdf`."""
 793        return _to_csr(self._inner.weighted_laplacian(formula))
 794
 795    def merge_buses(
 796        self,
 797        *,
 798        closed_switches: bool = True,
 799        zero_impedance: Optional[str] = None,
 800        threshold: Optional[float] = None,
 801        charging: str = "fold",
 802    ) -> "BusMerge":
 803        """Merge the buses closed switches and zero impedance branches join.
 804
 805        ``closed_switches`` merges the two buses of every closed switch.
 806        ``zero_impedance`` selects the branches merged as well: ``None``
 807        merges none, ``"exact"`` merges ``r == 0`` and ``x == 0``,
 808        ``"psse"`` merges non-transformer branches with ``r == 0`` and
 809        ``|x| <= threshold`` (PSS/E zero impedance lines; the threshold
 810        defaults to the ``THRSHZ`` the case states), and ``"impedance"``
 811        merges non-transformer branches with ``|r + jx| <= threshold``.
 812
 813        Each joined set keeps one bus: its reference bus, else a bus with an
 814        in-service generator, else a bus a generator regulates, smallest id
 815        first. Every element moves onto it. The merged elements and any
 816        branch the merge shorts are removed and listed with their source rows
 817        and ratings. ``charging="fold"`` turns each removed branch's line
 818        charging and line shunts, including tap scaling, into a fixed shunt
 819        at the survivor. ``"drop"`` discards only terminal charging. Both
 820        choices preserve the series equivalent of a bypassed transformer.
 821        An ideal transformer with a nonunity tap or phase shift cannot be
 822        bypassed and raises an error. This network is unchanged.
 823
 824        Raises :class:`PowerIODataError` for a threshold that is negative or
 825        not finite, or for ``"psse"`` with no threshold when the case states
 826        none; an unknown rule name raises ``ValueError``.
 827        """
 828        return BusMerge(
 829            self._inner.merge_buses(
 830                closed_switches=closed_switches,
 831                zero_impedance=zero_impedance,
 832                threshold=threshold,
 833                charging=charging,
 834            )
 835        )
 836
 837    def to_normalized(
 838        self,
 839        *,
 840        clamp_angle_bounds: bool = False,
 841        angle_bound_pad: Optional[float] = None,
 842        closed_switches: str = "merge",
 843        island_references: str = "stated",
 844    ) -> "BalancedNetwork":
 845        """Return a normalized copy with per unit power and radian angles.
 846
 847        The result removes out of service elements, preserves source bus IDs,
 848        and normalizes bus types. It carries no retained source, so
 849        :func:`powerio.emit` produces a grid exchange representation from the
 850        derived module. Raises
 851        :class:`PowerIODataError` if the network cannot be
 852        normalized (no reference bus can be chosen, or a non-positive base MVA).
 853
 854        ``clamp_angle_bounds=True`` applies the PowerModels angle difference
 855        bound repair: limits at or beyond ``+/-pi/2`` and zero/zero windows
 856        become ``[-angle_bound_pad, angle_bound_pad]``. A repair that would
 857        invert the interval widens to that same window. The default pad is
 858        1.0472 radians.
 859
 860        The default ``closed_switches="merge"`` merges the buses closed
 861        switches join first, as :meth:`merge_buses` does with
 862        ``closed_switches=True``, since the matrix and DC calculations model
 863        no switches. ``"keep"`` leaves the switches as data, and ``"refuse"``
 864        raises :class:`PowerIODataError` with code ``BUILD.SWITCH.CLOSED``.
 865        ``"merge"`` also raises that error when the merge cannot complete,
 866        for example across two windings of one three winding transformer.
 867        The error names the original switch row and endpoints; no partial
 868        normalized network is returned.
 869
 870        ``island_references="per_island"`` gives every island one reference
 871        bus: an island that states none takes the bus of its largest ``pmax``
 872        in-service generator, an island stating several keeps one, and an
 873        island no in-service generator supplies is left out. The default
 874        ``"stated"`` keeps the case's references and designates one only when
 875        none survives.
 876        """
 877        if (
 878            not clamp_angle_bounds
 879            and angle_bound_pad is None
 880            and closed_switches == "merge"
 881            and island_references == "stated"
 882        ):
 883            return BalancedNetwork(self._inner.to_normalized())
 884        return BalancedNetwork(
 885            self._inner.to_normalized_with_options(
 886                clamp_angle_bounds=clamp_angle_bounds,
 887                angle_bound_pad=angle_bound_pad,
 888                closed_switches=closed_switches,
 889                island_references=island_references,
 890            )
 891        )
 892
 893    def to_ppc(self):
 894        """PYPOWER case dict (``ppc``) with MATPOWER-style numpy tables.
 895
 896        Values are emitted as the model holds them, so a case read from a
 897        file carries MW, MVAr, and degrees. A network from
 898        :meth:`to_normalized` holds per unit and radians, and those are what
 899        its tables carry — PYPOWER reads a ppc dict as MW and degrees, so
 900        build this from the raw network unless the consumer expects per unit.
 901
 902        Loads and shunts are summed onto their bus in the
 903        ``PD``/``QD``/``GS``/``BS`` columns, the same aggregation as the
 904        MATPOWER emitter. The bus table has no per element status
 905        column, so an element the model marks out of service still
 906        contributes its value, and a de-energized bus is carried as type 4.
 907        ``gencost`` is present only when every generator carries cost data,
 908        because MATPOWER requires cost rows for all generators or none.
 909        :func:`from_ppc` reads the tables back.
 910
 911        Infinite branch ratings become PYPOWER's zero (no bound). A real
 912        zero rating raises ``ValueError`` because those tables cannot state
 913        a zero flow bound.
 914        """
 915        np = _require("numpy", "matrix")
 916        buses = self._inner.buses
 917        bus = np.array(
 918            [
 919                (
 920                    b["id"],
 921                    _PPC_BUS_TYPE.get(b["kind"], 1.0),
 922                    0.0,
 923                    0.0,
 924                    0.0,
 925                    0.0,
 926                    b["area"],
 927                    b["vm"],
 928                    b["va"],
 929                    b["base_kv"],
 930                    b["zone"],
 931                    b["vmax"],
 932                    b["vmin"],
 933                )
 934                for b in buses
 935            ],
 936            dtype=float,
 937        ).reshape(len(buses), 13)
 938        bus[:, 2], bus[:, 3], bus[:, 4], bus[:, 5] = _bus_sums(
 939            np, buses, self._inner.loads, self._inner.shunts
 940        )
 941
 942        # The capability and ramp columns past PMIN are an OPF extension that a
 943        # source need not carry. Widen to the full 21 only when a generator
 944        # actually states one: a table of zeros there reads back as eleven
 945        # explicit zero limits, which a ramp aware solver takes as a generator
 946        # that cannot move.
 947        gens = self._inner.generators
 948        caps = [g["caps"] for g in gens]
 949        width = 21 if any(c is not None for row in caps for c in row) else 10
 950        gen = np.array(
 951            [
 952                [
 953                    g["bus"],
 954                    g["pg"],
 955                    g["qg"],
 956                    g["qmax"],
 957                    g["qmin"],
 958                    g["vg"],
 959                    g["mbase"],
 960                    float(g["in_service"]),
 961                    g["pmax"],
 962                    g["pmin"],
 963                ]
 964                + ([0.0 if c is None else c for c in row] if width == 21 else [])
 965                for g, row in zip(gens, caps, strict=True)
 966            ],
 967            dtype=float,
 968        ).reshape(len(gens), width)
 969
 970        branches = self._inner.branches
 971
 972        def ppc_rating(rating):
 973            if rating == 0.0:
 974                raise ValueError("PYPOWER's zero means no bound; it cannot represent a zero branch rating")
 975            return 0.0 if rating == float("inf") else rating
 976
 977        branch = np.array(
 978            [
 979                (
 980                    br["from_id"],
 981                    br["to_id"],
 982                    br["r"],
 983                    br["x"],
 984                    br["b"],
 985                    ppc_rating(br["rate_a"]),
 986                    ppc_rating(br["rate_b"]),
 987                    ppc_rating(br["rate_c"]),
 988                    br["tap"],
 989                    br["shift"],
 990                    float(br["in_service"]),
 991                    br["angmin"],
 992                    br["angmax"],
 993                )
 994                for br in branches
 995            ],
 996            dtype=float,
 997        ).reshape(len(branches), 13)
 998
 999        ppc = {
1000            "version": "2",
1001            "baseMVA": float(self._inner.base_mva),
1002            "bus": bus,
1003            "gen": gen,
1004            "branch": branch,
1005        }
1006
1007        # Coefficients sit left-aligned after ncost, padded to the widest
1008        # row, which is the layout PYPOWER's own loadcase produces.
1009        costs = [g["cost"] for g in gens]
1010        if costs and all(c is not None for c in costs):
1011            gencost = np.zeros((len(costs), 4 + max(len(c["coeffs"]) for c in costs)))
1012            for i, c in enumerate(costs):
1013                gencost[i, :4] = (
1014                    c["model"],
1015                    c["startup"],
1016                    c["shutdown"],
1017                    c["ncost"],
1018                )
1019                gencost[i, 4 : 4 + len(c["coeffs"])] = c["coeffs"]
1020            ppc["gencost"] = gencost
1021        return ppc
1022
1023    def to_networkx(self):
1024        """Undirected networkx graph keyed by bus id.
1025
1026        In-service branches become edges carrying ``branch`` (index), ``r``,
1027        ``x``, and ``b``.
1028        """
1029        nx = _require("networkx", "graph")
1030        g = nx.Graph()
1031        g.add_nodes_from(bus["id"] for bus in self._inner.buses)
1032        for k, br in enumerate(self._inner.branches):
1033            if br["in_service"]:
1034                g.add_edge(
1035                    br["from_id"],
1036                    br["to_id"],
1037                    branch=k,
1038                    r=br["r"],
1039                    x=br["x"],
1040                    b=br["b"],
1041                )
1042        return g

A parsed balanced power network.

The data attributes (buses, branches, generators, loads, shunts) and reference bus queries delegate to the compiled handle; the matrix methods below return scipy.sparse objects. Parse and transform diagnostics belong to the owning PioModule.

Errors: a bad file path raises the standard OSError subclass (FileNotFoundError); a malformed case raises PowerIOParseError and an unmet calculation precondition (no generators, no reference bus) raises PowerIODataError; both subclass PowerIOError, so except PowerIOError catches either; an unknown scheme/formula/units string raises ValueError.

BalancedNetwork(inner: Any)
422    def __init__(self, inner: "_powerio._BalancedNetwork"):
423        self._inner = inner
def component_counts(self) -> dict[str, int]:
450    def component_counts(self) -> dict[str, int]:
451        """Count native lines, generators, loads, and substations.
452
453        Lines exclude transformer branches. Loads include equivalent injections
454        represented as loads. Substations count the source hierarchy, or zero
455        when the format supplies no hierarchy. No Python table rows are built.
456        Raises ValueError for normalized networks, whose unity taps no longer
457        distinguish lines from transformers. Count the source network instead.
458        """
459        return self._inner.component_counts()

Count native lines, generators, loads, and substations.

Lines exclude transformer branches. Loads include equivalent injections represented as loads. Substations count the source hierarchy, or zero when the format supplies no hierarchy. No Python table rows are built. Raises ValueError for normalized networks, whose unity taps no longer distinguish lines from transformers. Count the source network instead.

def calc_connectivity_report(self) -> Dict[str, Any]:
461    def calc_connectivity_report(self) -> dict[str, Any]:
462        """Calculate the in-service topology summary."""
463        return self._inner.calc_connectivity_report()

Calculate the in-service topology summary.

def calc_stated_state_mismatch( self, *, top_k: int = Ellipsis, hvdc: str = Ellipsis, low_impedance_threshold: float = Ellipsis, merge_zero_impedance: bool = Ellipsis, lcc_reactive_power: str = Ellipsis) -> Dict[str, Any]:
465    def calc_stated_state_mismatch(
466        self,
467        *,
468        top_k: int = 20,
469        hvdc: str = "fixed_injection",
470        low_impedance_threshold: float = 1e-3,
471        merge_zero_impedance: bool = False,
472        lcc_reactive_power: str = "converter_model",
473    ) -> dict[str, Any]:
474        """Evaluate every bus's AC balance at the voltages the case stores.
475
476        Each device sits at its stated output: generators at ``pg``/``qg``,
477        loads through their voltage model at the stored magnitude, shunts at
478        their stated admittance, and HVDC lines as fixed injections (or not,
479        with ``hvdc="ignore"``). A bus mismatch is the power the network draws
480        at the stored voltages minus the stated injection, MW and MVAr, so an
481        injection equal to it closes the bus.
482
483        The result holds per bus columns in analysis bus order (``bus_ids``,
484        ``island``, ``p_mw``, ``q_mvar``, and ``flags``, the attached
485        equipment a residual is traced to), ``islands`` totals largest first,
486        ``top`` (row indices of the largest mismatches), the totals, and
487        ``diagnostics`` (a warning per LCC line that kept its stated reactive
488        powers because its converter record reaches no operating point).
489        ``merge_zero_impedance`` first merges the buses joined by in-service
490        zero-impedance branches, whose flows the stored voltages cannot
491        determine; without it such a branch raises. A closed switch joining
492        two buses also raises (``BUILD.SWITCH.CLOSED``); merge it first with
493        ``merge_buses(closed_switches=True)``. ``lcc_reactive_power``
494        selects where a PSS/E two-terminal converter's reactive demand comes
495        from: its bridge equations at the stored voltages
496        (``"converter_model"``) or the line's stated reactive powers
497        (``"stated"``).
498        """
499        return self._inner.calc_stated_state_mismatch(
500            top_k=top_k,
501            hvdc=hvdc,
502            low_impedance_threshold=low_impedance_threshold,
503            merge_zero_impedance=merge_zero_impedance,
504            lcc_reactive_power=lcc_reactive_power,
505        )

Evaluate every bus's AC balance at the voltages the case stores.

Each device sits at its stated output: generators at pg/qg, loads through their voltage model at the stored magnitude, shunts at their stated admittance, and HVDC lines as fixed injections (or not, with hvdc="ignore"). A bus mismatch is the power the network draws at the stored voltages minus the stated injection, MW and MVAr, so an injection equal to it closes the bus.

The result holds per bus columns in analysis bus order (bus_ids, island, p_mw, q_mvar, and flags, the attached equipment a residual is traced to), islands totals largest first, top (row indices of the largest mismatches), the totals, and diagnostics (a warning per LCC line that kept its stated reactive powers because its converter record reaches no operating point). merge_zero_impedance first merges the buses joined by in-service zero-impedance branches, whose flows the stored voltages cannot determine; without it such a branch raises. A closed switch joining two buses also raises (BUILD.SWITCH.CLOSED); merge it first with merge_buses(closed_switches=True). lcc_reactive_power selects where a PSS/E two-terminal converter's reactive demand comes from: its bridge equations at the stored voltages ("converter_model") or the line's stated reactive powers ("stated").

def calc_stated_branch_flows(self) -> Dict[str, Any]:
507    def calc_stated_branch_flows(self) -> dict[str, Any]:
508        """Calculate the power entering every branch end at the stored voltages.
509
510        Columns follow analysis branch order: every branch row, then the three
511        windings of each in-service three-winding transformer, as ``sources``
512        states. Powers are MW and MVAr; an out-of-service branch carries zero.
513        """
514        return self._inner.calc_stated_branch_flows()

Calculate the power entering every branch end at the stored voltages.

Columns follow analysis branch order: every branch row, then the three windings of each in-service three-winding transformer, as sources states. Powers are MW and MVAr; an out-of-service branch carries zero.

def to_geo_layer(self) -> Dict[str, Any]:
516    def to_geo_layer(self) -> dict[str, Any]:
517        """Transform coordinates to a canonical GeoJSON FeatureCollection.
518
519        A case without coordinates produces an empty feature collection.
520        """
521        return _json.loads(self._inner.to_geo_layer_json())

Transform coordinates to a canonical GeoJSON FeatureCollection.

A case without coordinates produces an empty feature collection.

def apply_geo_layer( self, text: str, name_hint: Optional[str] = Ellipsis) -> Tuple[BalancedNetwork, Dict[str, Any]]:
523    def apply_geo_layer(
524        self, text: str, name_hint: Optional[str] = None
525    ) -> tuple["BalancedNetwork", dict[str, Any]]:
526        """Apply a geographic sidecar and return ``(placed, report)``.
527
528        ``text`` is any form :func:`parse_geo` accepts; this case is
529        unchanged. The report carries ``matched_buses``, ``matched_branches``,
530        ``unmatched_features``, ``unlocated_buses``, ``unlocated_branches``,
531        and ``notes``. The two unlocated counts cover the whole case when the
532        pass ends, so a layer that matched nothing reads apart from a case
533        that needed nothing. The placed copy drops the retained source text,
534        so a same-format emission re-serializes.
535        """
536        inner, report = self._inner.apply_geo_layer(text, name_hint)
537        return BalancedNetwork(inner), report

Apply a geographic sidecar and return (placed, report).

text is any form parse_geo() accepts; this case is unchanged. The report carries matched_buses, matched_branches, unmatched_features, unlocated_buses, unlocated_branches, and notes. The two unlocated counts cover the whole case when the pass ends, so a layer that matched nothing reads apart from a case that needed nothing. The placed copy drops the retained source text, so a same-format emission re-serializes.

def resolve_contingencies(self, text: str) -> Dict[str, Any]:
539    def resolve_contingencies(self, text: str) -> dict[str, Any]:
540        """Read PSS/E contingency text and bind every case to this network.
541
542        ``text`` is the content of a ``.con`` file, such as
543        ``parse("cases.con").value.text``. The result carries ``cases``,
544        ``resolved``, ``unresolved``, and ``unrecognized_statements`` as
545        counts; ``case_results``, one entry per case in the file's order with
546        its ``name``, whether it ``resolved``, the ``components`` it bound to,
547        and the actions that bound to nothing as ``{"action", "reason"}``; and
548        ``diagnostics``, the reader's notes on statements it kept as text.
549
550        Each component states the ``type`` naming the table, the ``row`` it
551        occupies there, the element's own ``in_service`` flag, and the ``id``
552        the network states for it. ``id`` is ``None`` when the network states
553        no identity for that row; ``type`` and ``row`` name the element either
554        way.
555
556        Binding reports rather than refuses, so a case naming an element this
557        network does not hold is counted unresolved and listed.
558        """
559        return self._inner.resolve_contingencies(text)

Read PSS/E contingency text and bind every case to this network.

text is the content of a .con file, such as parse("cases.con").value.text. The result carries cases, resolved, unresolved, and unrecognized_statements as counts; case_results, one entry per case in the file's order with its name, whether it resolved, the components it bound to, and the actions that bound to nothing as {"action", "reason"}; and diagnostics, the reader's notes on statements it kept as text.

Each component states the type naming the table, the row it occupies there, the element's own in_service flag, and the id the network states for it. id is None when the network states no identity for that row; type and row name the element either way.

Binding reports rather than refuses, so a case naming an element this network does not hold is counted unresolved and listed.

def expand_contingencies( self, con_text: str, sub_text: str) -> Tuple[str, List[Diagnostic]]:
561    def expand_contingencies(
562        self, con_text: str, sub_text: str
563    ) -> tuple[str, list[Diagnostic]]:
564        """Turn automatic contingency specifications into explicit cases.
565
566        ``con_text`` and ``sub_text`` are the contents of a ``.con`` and a
567        ``.sub`` file. A specification such as ``SINGLE BRANCH IN SUBSYSTEM
568        'A1'`` states a rule, so expanding it needs both the network and the
569        subsystem the ``.sub`` file names. Returns the expanded ``.con`` text,
570        which states every outage explicitly, and the notes from the two
571        readers followed by the expansion's own notes. Only elements this
572        network states in service expand into cases.
573        """
574        return self._inner.expand_contingencies(con_text, sub_text)

Turn automatic contingency specifications into explicit cases.

con_text and sub_text are the contents of a .con and a .sub file. A specification such as SINGLE BRANCH IN SUBSYSTEM 'A1' states a rule, so expanding it needs both the network and the subsystem the .sub file names. Returns the expanded .con text, which states every outage explicitly, and the notes from the two readers followed by the expansion's own notes. Only elements this network states in service expand into cases.

def select_subsystem_buses(self, sub_text: str, name: str) -> List[int]:
576    def select_subsystem_buses(self, sub_text: str, name: str) -> list[int]:
577        """The bus numbers one named subsystem of ``sub_text`` selects.
578
579        ``sub_text`` is the content of a ``.sub`` file. The numbers come back
580        in ascending order. A name the file does not state raises
581        ``ValueError``.
582        """
583        return self._inner.select_subsystem_buses(sub_text, name)

The bus numbers one named subsystem of sub_text selects.

sub_text is the content of a .sub file. The numbers come back in ascending order. A name the file does not state raises ValueError.

def calc_bprime_matrix( self, scheme: Literal['bx', 'xb'] = Ellipsis, *, skip_zero_impedance: bool = Ellipsis) -> Any:
587    def calc_bprime_matrix(
588        self, scheme: str = "bx", *, skip_zero_impedance: bool = False
589    ):
590        """MATPOWER FDPF Bp matrix. ``scheme`` is ``"bx"`` or ``"xb"``.
591
592        ``skip_zero_impedance=False`` refuses a zero impedance branch
593        (``r`` and ``x`` both zero); pass ``True`` to drop it instead.
594        """
595        return _to_csr(
596            self._inner.bprime(scheme, skip_zero_impedance=skip_zero_impedance)
597        )

MATPOWER FDPF Bp matrix. scheme is "bx" or "xb".

skip_zero_impedance=False refuses a zero impedance branch (r and x both zero); pass True to drop it instead.

def calc_incidence_matrix( self, formula: str = Ellipsis, *, skip_zero_impedance: bool = Ellipsis) -> Any:
599    def calc_incidence_matrix(
600        self, formula: str = "series_susceptance", *, skip_zero_impedance: bool = False
601    ):
602        """Return PowerModels incidence ``A`` (branches by buses).
603
604        Rows are the in service, non self loop branches in table order
605        (three winding transformer windings follow the branches); columns
606        are every bus in table order. :meth:`calc_dc_index_map` names both
607        axes. ``skip_zero_impedance=False`` refuses a zero impedance branch;
608        ``True`` drops it from the branch axis.
609        """
610        return _to_csr(
611            self._inner.calc_incidence_matrix(
612                formula, skip_zero_impedance=skip_zero_impedance
613            )
614        )

Return PowerModels incidence A (branches by buses).

Rows are the in service, non self loop branches in table order (three winding transformer windings follow the branches); columns are every bus in table order. calc_dc_index_map() names both axes. skip_zero_impedance=False refuses a zero impedance branch; True drops it from the branch axis.

def calc_branch_susceptances( self, formula: str = Ellipsis, *, skip_zero_impedance: bool = Ellipsis) -> Any:
616    def calc_branch_susceptances(
617        self, formula: str = "series_susceptance", *, skip_zero_impedance: bool = False
618    ):
619        """Return per branch susceptances over the branch axis of
620        :meth:`calc_dc_index_map`."""
621        np = _require("numpy", "matrix")
622        return np.asarray(
623            self._inner.calc_branch_susceptances(
624                formula, skip_zero_impedance=skip_zero_impedance
625            ),
626            dtype=float,
627        )

Return per branch susceptances over the branch axis of calc_dc_index_map().

def calc_branch_flow_matrix( self, formula: str = Ellipsis, *, skip_zero_impedance: bool = Ellipsis) -> Any:
629    def calc_branch_flow_matrix(
630        self, formula: str = "series_susceptance", *, skip_zero_impedance: bool = False
631    ):
632        """Return ``Bf = diag(b) A`` as a CSR matrix (branches by buses)."""
633        return _to_csr(
634            self._inner.calc_branch_flow_matrix(
635                formula, skip_zero_impedance=skip_zero_impedance
636            )
637        )

Return Bf = diag(b) A as a CSR matrix (branches by buses).

def calc_bus_susceptance_matrix( self, formula: str = Ellipsis, *, skip_zero_impedance: bool = Ellipsis) -> Any:
639    def calc_bus_susceptance_matrix(
640        self, formula: str = "series_susceptance", *, skip_zero_impedance: bool = False
641    ):
642        """Return ``B = A.T diag(b) A`` as a CSR matrix (buses by buses)."""
643        return _to_csr(
644            self._inner.calc_bus_susceptance_matrix(
645                formula, skip_zero_impedance=skip_zero_impedance
646            )
647        )

Return B = A.T diag(b) A as a CSR matrix (buses by buses).

def calc_branch_phase_shift_injection( self, formula: str = Ellipsis, *, skip_zero_impedance: bool = Ellipsis) -> Any:
649    def calc_branch_phase_shift_injection(
650        self, formula: str = "series_susceptance", *, skip_zero_impedance: bool = False
651    ):
652        """Return ``b * shift`` over the branch axis."""
653        np = _require("numpy", "matrix")
654        return np.asarray(
655            self._inner.calc_branch_phase_shift_injection(
656                formula, skip_zero_impedance=skip_zero_impedance
657            ),
658            dtype=float,
659        )

Return b * shift over the branch axis.

def calc_bus_phase_shift_injection( self, formula: str = Ellipsis, *, skip_zero_impedance: bool = Ellipsis) -> Any:
661    def calc_bus_phase_shift_injection(
662        self, formula: str = "series_susceptance", *, skip_zero_impedance: bool = False
663    ):
664        """Return ``A.T @ (b * shift)`` over the bus axis."""
665        np = _require("numpy", "matrix")
666        return np.asarray(
667            self._inner.calc_bus_phase_shift_injection(
668                formula, skip_zero_impedance=skip_zero_impedance
669            ),
670            dtype=float,
671        )

Return A.T @ (b * shift) over the bus axis.

def calc_branch_flow_dc( self, voltage_angles: Any, formula: str = Ellipsis, *, skip_zero_impedance: bool = Ellipsis) -> Any:
673    def calc_branch_flow_dc(
674        self,
675        voltage_angles,
676        formula: str = "series_susceptance",
677        *,
678        skip_zero_impedance: bool = False,
679    ):
680        """Compute ``-Bf @ va + b * shift`` over the branch axis."""
681        np, angles = _dc_angles(self.n_buses, voltage_angles)
682        return np.asarray(
683            self._inner.calc_branch_flow_dc(
684                angles.tolist(), formula, skip_zero_impedance=skip_zero_impedance
685            ),
686            dtype=float,
687        )

Compute -Bf @ va + b * shift over the branch axis.

def calc_bus_injection_dc( self, voltage_angles: Any, formula: str = Ellipsis, *, skip_zero_impedance: bool = Ellipsis) -> Any:
689    def calc_bus_injection_dc(
690        self,
691        voltage_angles,
692        formula: str = "series_susceptance",
693        *,
694        skip_zero_impedance: bool = False,
695    ):
696        """Compute ``-B @ va + p_shift`` over the bus axis."""
697        np, angles = _dc_angles(self.n_buses, voltage_angles)
698        return np.asarray(
699            self._inner.calc_bus_injection_dc(
700                angles.tolist(), formula, skip_zero_impedance=skip_zero_impedance
701            ),
702            dtype=float,
703        )

Compute -B @ va + p_shift over the bus axis.

def calc_dc_index_map( self, formula: str = Ellipsis, *, skip_zero_impedance: bool = Ellipsis) -> powerio.DcIndexMap:
705    def calc_dc_index_map(
706        self, formula: str = "series_susceptance", *, skip_zero_impedance: bool = False
707    ) -> dict[str, Any]:
708        """Return the axes every DC calculation shares.
709
710        ``bus_ids`` maps a bus axis row to the source bus id (every bus, in
711        table order). ``branch_rows`` maps a branch axis row to the position
712        in the branch table (three winding transformer windings follow the
713        branches) and ``branch_ids`` to the stable identity, the branch uid
714        when the source states one and ``branches:<row>`` otherwise; out of
715        service branches and self loops have no row. ``skipped_branch_rows``
716        lists the zero impedance branches dropped under
717        ``skip_zero_impedance=True`` and is empty otherwise. The same
718        selection applies to :meth:`calc_ptdf` rows and :meth:`calc_lodf`.
719        """
720        return self._inner.calc_dc_index_map(
721            formula, skip_zero_impedance=skip_zero_impedance
722        )

Return the axes every DC calculation shares.

bus_ids maps a bus axis row to the source bus id (every bus, in table order). branch_rows maps a branch axis row to the position in the branch table (three winding transformer windings follow the branches) and branch_ids to the stable identity, the branch uid when the source states one and branches:<row> otherwise; out of service branches and self loops have no row. skipped_branch_rows lists the zero impedance branches dropped under skip_zero_impedance=True and is empty otherwise. The same selection applies to calc_ptdf() rows and calc_lodf().

def calc_bdoubleprime_matrix( self, scheme: Literal['bx', 'xb'] = Ellipsis, *, skip_zero_impedance: bool = Ellipsis) -> Any:
724    def calc_bdoubleprime_matrix(
725        self, scheme: str = "bx", *, skip_zero_impedance: bool = False
726    ):
727        """MATPOWER FDPF Bpp matrix. ``scheme`` is ``"bx"`` or ``"xb"``.
728        ``skip_zero_impedance`` as in :meth:`calc_bprime_matrix`.
729        """
730        return _to_csr(
731            self._inner.bdoubleprime(scheme, skip_zero_impedance=skip_zero_impedance)
732        )

MATPOWER FDPF Bpp matrix. scheme is "bx" or "xb". skip_zero_impedance as in calc_bprime_matrix().

def calc_lacpf_matrix( self, *, include_taps: bool = Ellipsis, include_shifts: bool = Ellipsis, skip_zero_impedance: bool = Ellipsis) -> Any:
734    def calc_lacpf_matrix(
735        self,
736        *,
737        include_taps: bool = True,
738        include_shifts: bool = True,
739        skip_zero_impedance: bool = False,
740    ):
741        """LACPF 2n×2n block ``[[G, -B], [-B, -G]]``. ``skip_zero_impedance``
742        as in :meth:`calc_bprime_matrix`."""
743        return _to_csr(
744            self._inner.lacpf(
745                include_taps=include_taps,
746                include_shifts=include_shifts,
747                skip_zero_impedance=skip_zero_impedance,
748            )
749        )

LACPF 2n×2n block [[G, -B], [-B, -G]]. skip_zero_impedance as in calc_bprime_matrix().

def calc_adjacency_matrix(self) -> Any:
751    def calc_adjacency_matrix(self):
752        """0/1 bus adjacency matrix."""
753        return _to_csr(self._inner.adjacency())

0/1 bus adjacency matrix.

def calc_admittance_matrix( self, *, include_taps: bool = Ellipsis, include_shifts: bool = Ellipsis, skip_zero_impedance: bool = Ellipsis) -> Any:
755    def calc_admittance_matrix(
756        self,
757        *,
758        include_taps: bool = True,
759        include_shifts: bool = True,
760        skip_zero_impedance: bool = False,
761    ):
762        """``Y_bus = G + jB`` as a complex csr_matrix. ``skip_zero_impedance``
763        as in :meth:`calc_bprime_matrix`."""
764        g, b = self._inner.ybus_parts(
765            include_taps=include_taps,
766            include_shifts=include_shifts,
767            skip_zero_impedance=skip_zero_impedance,
768        )
769        g, b = _to_csr(g), _to_csr(b)
770        return (g + 1j * b).tocsr()

Y_bus = G + jB as a complex csr_matrix. skip_zero_impedance as in calc_bprime_matrix().

def calc_ptdf( self, formula: Literal['tap_adjusted_series_susceptance', 'series_susceptance_no_phase_shift', 'series_susceptance', 'tap_adjusted_reactance', 'reactance_only'] = Ellipsis, solver: Literal['auto', 'dense', 'sparse'] = Ellipsis) -> Any:
772    def calc_ptdf(self, formula: str = "series_susceptance", solver: str = "auto"):
773        """DC PTDF (m×n). ``formula`` is ``"series_susceptance"``,
774        ``"tap_adjusted_reactance"``, ``"reactance_only"``,
775        ``"tap_adjusted_series_susceptance"``, or
776        ``"series_susceptance_no_phase_shift"``.
777
778        ``solver`` is ``"auto"``, ``"dense"``, or ``"sparse"``. ``"auto"``
779        uses the dense factorization on small cases and the sparse Cholesky
780        path on large ones, the same policy as the CLI.
781        """
782        return _to_csr(self._inner.ptdf(formula, solver))

DC PTDF (m×n). formula is "series_susceptance", "tap_adjusted_reactance", "reactance_only", "tap_adjusted_series_susceptance", or "series_susceptance_no_phase_shift".

solver is "auto", "dense", or "sparse". "auto" uses the dense factorization on small cases and the sparse Cholesky path on large ones, the same policy as the CLI.

def calc_lodf( self, formula: Literal['tap_adjusted_series_susceptance', 'series_susceptance_no_phase_shift', 'series_susceptance', 'tap_adjusted_reactance', 'reactance_only'] = Ellipsis, solver: Literal['auto', 'dense', 'sparse'] = Ellipsis) -> Any:
784    def calc_lodf(self, formula: str = "series_susceptance", solver: str = "auto"):
785        """DC LODF (m×m). ``formula`` and ``solver`` as in :meth:`calc_ptdf`."""
786        return _to_csr(self._inner.lodf(formula, solver))

DC LODF (m×m). formula and solver as in calc_ptdf().

def calc_weighted_laplacian( self, formula: Literal['tap_adjusted_series_susceptance', 'series_susceptance_no_phase_shift', 'series_susceptance', 'tap_adjusted_reactance', 'reactance_only'] = Ellipsis) -> Any:
788    def calc_weighted_laplacian(
789        self,
790        formula: str = "series_susceptance",
791    ):
792        """Weighted Laplacian ``L = -B``. ``formula`` as in :meth:`calc_ptdf`."""
793        return _to_csr(self._inner.weighted_laplacian(formula))

Weighted Laplacian L = -B. formula as in calc_ptdf().

def merge_buses( self, *, closed_switches: bool = Ellipsis, zero_impedance: Optional[Literal['exact', 'psse', 'impedance']] = Ellipsis, threshold: Optional[float] = Ellipsis, charging: Literal['fold', 'drop'] = Ellipsis) -> BusMerge:
795    def merge_buses(
796        self,
797        *,
798        closed_switches: bool = True,
799        zero_impedance: Optional[str] = None,
800        threshold: Optional[float] = None,
801        charging: str = "fold",
802    ) -> "BusMerge":
803        """Merge the buses closed switches and zero impedance branches join.
804
805        ``closed_switches`` merges the two buses of every closed switch.
806        ``zero_impedance`` selects the branches merged as well: ``None``
807        merges none, ``"exact"`` merges ``r == 0`` and ``x == 0``,
808        ``"psse"`` merges non-transformer branches with ``r == 0`` and
809        ``|x| <= threshold`` (PSS/E zero impedance lines; the threshold
810        defaults to the ``THRSHZ`` the case states), and ``"impedance"``
811        merges non-transformer branches with ``|r + jx| <= threshold``.
812
813        Each joined set keeps one bus: its reference bus, else a bus with an
814        in-service generator, else a bus a generator regulates, smallest id
815        first. Every element moves onto it. The merged elements and any
816        branch the merge shorts are removed and listed with their source rows
817        and ratings. ``charging="fold"`` turns each removed branch's line
818        charging and line shunts, including tap scaling, into a fixed shunt
819        at the survivor. ``"drop"`` discards only terminal charging. Both
820        choices preserve the series equivalent of a bypassed transformer.
821        An ideal transformer with a nonunity tap or phase shift cannot be
822        bypassed and raises an error. This network is unchanged.
823
824        Raises :class:`PowerIODataError` for a threshold that is negative or
825        not finite, or for ``"psse"`` with no threshold when the case states
826        none; an unknown rule name raises ``ValueError``.
827        """
828        return BusMerge(
829            self._inner.merge_buses(
830                closed_switches=closed_switches,
831                zero_impedance=zero_impedance,
832                threshold=threshold,
833                charging=charging,
834            )
835        )

Merge the buses closed switches and zero impedance branches join.

closed_switches merges the two buses of every closed switch. zero_impedance selects the branches merged as well: None merges none, "exact" merges r == 0 and x == 0, "psse" merges non-transformer branches with r == 0 and |x| <= threshold (PSS/E zero impedance lines; the threshold defaults to the THRSHZ the case states), and "impedance" merges non-transformer branches with |r + jx| <= threshold.

Each joined set keeps one bus: its reference bus, else a bus with an in-service generator, else a bus a generator regulates, smallest id first. Every element moves onto it. The merged elements and any branch the merge shorts are removed and listed with their source rows and ratings. charging="fold" turns each removed branch's line charging and line shunts, including tap scaling, into a fixed shunt at the survivor. "drop" discards only terminal charging. Both choices preserve the series equivalent of a bypassed transformer. An ideal transformer with a nonunity tap or phase shift cannot be bypassed and raises an error. This network is unchanged.

Raises PowerIODataError for a threshold that is negative or not finite, or for "psse" with no threshold when the case states none; an unknown rule name raises ValueError.

def to_normalized( self, *, clamp_angle_bounds: bool = Ellipsis, angle_bound_pad: Optional[float] = Ellipsis, closed_switches: Literal['merge', 'refuse', 'keep'] = Ellipsis, island_references: Literal['stated', 'per_island'] = Ellipsis) -> BalancedNetwork:
837    def to_normalized(
838        self,
839        *,
840        clamp_angle_bounds: bool = False,
841        angle_bound_pad: Optional[float] = None,
842        closed_switches: str = "merge",
843        island_references: str = "stated",
844    ) -> "BalancedNetwork":
845        """Return a normalized copy with per unit power and radian angles.
846
847        The result removes out of service elements, preserves source bus IDs,
848        and normalizes bus types. It carries no retained source, so
849        :func:`powerio.emit` produces a grid exchange representation from the
850        derived module. Raises
851        :class:`PowerIODataError` if the network cannot be
852        normalized (no reference bus can be chosen, or a non-positive base MVA).
853
854        ``clamp_angle_bounds=True`` applies the PowerModels angle difference
855        bound repair: limits at or beyond ``+/-pi/2`` and zero/zero windows
856        become ``[-angle_bound_pad, angle_bound_pad]``. A repair that would
857        invert the interval widens to that same window. The default pad is
858        1.0472 radians.
859
860        The default ``closed_switches="merge"`` merges the buses closed
861        switches join first, as :meth:`merge_buses` does with
862        ``closed_switches=True``, since the matrix and DC calculations model
863        no switches. ``"keep"`` leaves the switches as data, and ``"refuse"``
864        raises :class:`PowerIODataError` with code ``BUILD.SWITCH.CLOSED``.
865        ``"merge"`` also raises that error when the merge cannot complete,
866        for example across two windings of one three winding transformer.
867        The error names the original switch row and endpoints; no partial
868        normalized network is returned.
869
870        ``island_references="per_island"`` gives every island one reference
871        bus: an island that states none takes the bus of its largest ``pmax``
872        in-service generator, an island stating several keeps one, and an
873        island no in-service generator supplies is left out. The default
874        ``"stated"`` keeps the case's references and designates one only when
875        none survives.
876        """
877        if (
878            not clamp_angle_bounds
879            and angle_bound_pad is None
880            and closed_switches == "merge"
881            and island_references == "stated"
882        ):
883            return BalancedNetwork(self._inner.to_normalized())
884        return BalancedNetwork(
885            self._inner.to_normalized_with_options(
886                clamp_angle_bounds=clamp_angle_bounds,
887                angle_bound_pad=angle_bound_pad,
888                closed_switches=closed_switches,
889                island_references=island_references,
890            )
891        )

Return a normalized copy with per unit power and radian angles.

The result removes out of service elements, preserves source bus IDs, and normalizes bus types. It carries no retained source, so powerio.emit() produces a grid exchange representation from the derived module. Raises PowerIODataError if the network cannot be normalized (no reference bus can be chosen, or a non-positive base MVA).

clamp_angle_bounds=True applies the PowerModels angle difference bound repair: limits at or beyond +/-pi/2 and zero/zero windows become [-angle_bound_pad, angle_bound_pad]. A repair that would invert the interval widens to that same window. The default pad is 1.0472 radians.

The default closed_switches="merge" merges the buses closed switches join first, as merge_buses() does with closed_switches=True, since the matrix and DC calculations model no switches. "keep" leaves the switches as data, and "refuse" raises PowerIODataError with code BUILD.SWITCH.CLOSED. "merge" also raises that error when the merge cannot complete, for example across two windings of one three winding transformer. The error names the original switch row and endpoints; no partial normalized network is returned.

island_references="per_island" gives every island one reference bus: an island that states none takes the bus of its largest pmax in-service generator, an island stating several keeps one, and an island no in-service generator supplies is left out. The default "stated" keeps the case's references and designates one only when none survives.

def to_ppc(self) -> Dict[str, Any]:
 893    def to_ppc(self):
 894        """PYPOWER case dict (``ppc``) with MATPOWER-style numpy tables.
 895
 896        Values are emitted as the model holds them, so a case read from a
 897        file carries MW, MVAr, and degrees. A network from
 898        :meth:`to_normalized` holds per unit and radians, and those are what
 899        its tables carry — PYPOWER reads a ppc dict as MW and degrees, so
 900        build this from the raw network unless the consumer expects per unit.
 901
 902        Loads and shunts are summed onto their bus in the
 903        ``PD``/``QD``/``GS``/``BS`` columns, the same aggregation as the
 904        MATPOWER emitter. The bus table has no per element status
 905        column, so an element the model marks out of service still
 906        contributes its value, and a de-energized bus is carried as type 4.
 907        ``gencost`` is present only when every generator carries cost data,
 908        because MATPOWER requires cost rows for all generators or none.
 909        :func:`from_ppc` reads the tables back.
 910
 911        Infinite branch ratings become PYPOWER's zero (no bound). A real
 912        zero rating raises ``ValueError`` because those tables cannot state
 913        a zero flow bound.
 914        """
 915        np = _require("numpy", "matrix")
 916        buses = self._inner.buses
 917        bus = np.array(
 918            [
 919                (
 920                    b["id"],
 921                    _PPC_BUS_TYPE.get(b["kind"], 1.0),
 922                    0.0,
 923                    0.0,
 924                    0.0,
 925                    0.0,
 926                    b["area"],
 927                    b["vm"],
 928                    b["va"],
 929                    b["base_kv"],
 930                    b["zone"],
 931                    b["vmax"],
 932                    b["vmin"],
 933                )
 934                for b in buses
 935            ],
 936            dtype=float,
 937        ).reshape(len(buses), 13)
 938        bus[:, 2], bus[:, 3], bus[:, 4], bus[:, 5] = _bus_sums(
 939            np, buses, self._inner.loads, self._inner.shunts
 940        )
 941
 942        # The capability and ramp columns past PMIN are an OPF extension that a
 943        # source need not carry. Widen to the full 21 only when a generator
 944        # actually states one: a table of zeros there reads back as eleven
 945        # explicit zero limits, which a ramp aware solver takes as a generator
 946        # that cannot move.
 947        gens = self._inner.generators
 948        caps = [g["caps"] for g in gens]
 949        width = 21 if any(c is not None for row in caps for c in row) else 10
 950        gen = np.array(
 951            [
 952                [
 953                    g["bus"],
 954                    g["pg"],
 955                    g["qg"],
 956                    g["qmax"],
 957                    g["qmin"],
 958                    g["vg"],
 959                    g["mbase"],
 960                    float(g["in_service"]),
 961                    g["pmax"],
 962                    g["pmin"],
 963                ]
 964                + ([0.0 if c is None else c for c in row] if width == 21 else [])
 965                for g, row in zip(gens, caps, strict=True)
 966            ],
 967            dtype=float,
 968        ).reshape(len(gens), width)
 969
 970        branches = self._inner.branches
 971
 972        def ppc_rating(rating):
 973            if rating == 0.0:
 974                raise ValueError("PYPOWER's zero means no bound; it cannot represent a zero branch rating")
 975            return 0.0 if rating == float("inf") else rating
 976
 977        branch = np.array(
 978            [
 979                (
 980                    br["from_id"],
 981                    br["to_id"],
 982                    br["r"],
 983                    br["x"],
 984                    br["b"],
 985                    ppc_rating(br["rate_a"]),
 986                    ppc_rating(br["rate_b"]),
 987                    ppc_rating(br["rate_c"]),
 988                    br["tap"],
 989                    br["shift"],
 990                    float(br["in_service"]),
 991                    br["angmin"],
 992                    br["angmax"],
 993                )
 994                for br in branches
 995            ],
 996            dtype=float,
 997        ).reshape(len(branches), 13)
 998
 999        ppc = {
1000            "version": "2",
1001            "baseMVA": float(self._inner.base_mva),
1002            "bus": bus,
1003            "gen": gen,
1004            "branch": branch,
1005        }
1006
1007        # Coefficients sit left-aligned after ncost, padded to the widest
1008        # row, which is the layout PYPOWER's own loadcase produces.
1009        costs = [g["cost"] for g in gens]
1010        if costs and all(c is not None for c in costs):
1011            gencost = np.zeros((len(costs), 4 + max(len(c["coeffs"]) for c in costs)))
1012            for i, c in enumerate(costs):
1013                gencost[i, :4] = (
1014                    c["model"],
1015                    c["startup"],
1016                    c["shutdown"],
1017                    c["ncost"],
1018                )
1019                gencost[i, 4 : 4 + len(c["coeffs"])] = c["coeffs"]
1020            ppc["gencost"] = gencost
1021        return ppc

PYPOWER case dict (ppc) with MATPOWER-style numpy tables.

Values are emitted as the model holds them, so a case read from a file carries MW, MVAr, and degrees. A network from to_normalized() holds per unit and radians, and those are what its tables carry — PYPOWER reads a ppc dict as MW and degrees, so build this from the raw network unless the consumer expects per unit.

Loads and shunts are summed onto their bus in the PD/QD/GS/BS columns, the same aggregation as the MATPOWER emitter. The bus table has no per element status column, so an element the model marks out of service still contributes its value, and a de-energized bus is carried as type 4. gencost is present only when every generator carries cost data, because MATPOWER requires cost rows for all generators or none. from_ppc() reads the tables back.

Infinite branch ratings become PYPOWER's zero (no bound). A real zero rating raises ValueError because those tables cannot state a zero flow bound.

def to_networkx(self) -> Any:
1023    def to_networkx(self):
1024        """Undirected networkx graph keyed by bus id.
1025
1026        In-service branches become edges carrying ``branch`` (index), ``r``,
1027        ``x``, and ``b``.
1028        """
1029        nx = _require("networkx", "graph")
1030        g = nx.Graph()
1031        g.add_nodes_from(bus["id"] for bus in self._inner.buses)
1032        for k, br in enumerate(self._inner.branches):
1033            if br["in_service"]:
1034                g.add_edge(
1035                    br["from_id"],
1036                    br["to_id"],
1037                    branch=k,
1038                    r=br["r"],
1039                    x=br["x"],
1040                    b=br["b"],
1041                )
1042        return g

Undirected networkx graph keyed by bus id.

In-service branches become edges carrying branch (index), r, x, and b.

class BusMerge:
304@_guard_class
305class BusMerge:
306    """The result of :meth:`BalancedNetwork.merge_buses`.
307
308    ``network`` is the merged network. ``merged_buses`` maps every merged
309    bus to the bus that now carries it, and ``groups`` lists each joined set
310    as ``{"survivor", "members"}``. ``removed_branches`` and
311    ``removed_switches`` describe every element the merge removed: its source
312    ``row``, ``id``, ``from_id`` and ``to_id`` buses, ``survivor``, ``reason``
313    (``"zero_impedance"``, ``"closed_switch"``, or ``"shorted"``), status, and
314    ratings. ``branch_rows`` and ``switch_rows`` map each source row to its
315    merged row, or ``None`` when removed, and ``charging_shunts`` lists the
316    merged shunt rows that hold removed branches' equivalent admittances. ``diagnostics`` holds the merge's
317    findings, which the merged network's module carries as well.
318    """
319
320    def __init__(self, inner: "_powerio._BusMerge"):
321        self._inner = inner
322
323    def __repr__(self) -> str:
324        return repr(self._inner)
325
326    @property
327    def network(self) -> "BalancedNetwork":
328        return BalancedNetwork(self._inner.network)
329
330    @property
331    def rule(self) -> str:
332        return self._inner.rule
333
334    @property
335    def merged_buses(self) -> dict[int, int]:
336        return self._inner.merged_buses
337
338    @property
339    def groups(self) -> list[dict[str, Any]]:
340        return self._inner.groups
341
342    @property
343    def removed_branches(self) -> list[dict[str, Any]]:
344        return self._inner.removed_branches
345
346    @property
347    def removed_switches(self) -> list[dict[str, Any]]:
348        return self._inner.removed_switches
349
350    @property
351    def branch_rows(self) -> list[Optional[int]]:
352        return self._inner.branch_rows
353
354    @property
355    def switch_rows(self) -> list[Optional[int]]:
356        return self._inner.switch_rows
357
358    @property
359    def charging_shunts(self) -> list[int]:
360        return self._inner.charging_shunts
361
362    @property
363    def diagnostics(self) -> list[Diagnostic]:
364        return self._inner.diagnostics
365
366    def survivor(self, bus: int) -> int:
367        """The bus that carries ``bus`` in the merged network."""
368        return self._inner.survivor(bus)
369
370    def calc_removed_flows(
371        self,
372        branch_p_from: Any,
373        branch_p_to: Any,
374        *,
375        generator_p: Any = None,
376        transformer_3w_p: Any = None,
377    ) -> dict[str, Any]:
378        """Recover the active power on every removed element.
379
380        ``branch_p_from`` and ``branch_p_to`` are the power entering each
381        merged network branch at its from and to ends; ``generator_p``
382        replaces the stated generator outputs, and ``transformer_3w_p`` gives
383        the power entering each three winding transformer winding from its
384        bus, three values per transformer. Values are in the network's units
385        (MW for a parsed network). The result has ``branches`` and
386        ``switches``, one ``{"p_from", "method"}`` per removed element in the
387        order of :attr:`removed_branches` and :attr:`removed_switches`, and
388        ``diagnostics``. ``method`` is ``"tree"`` where Kirchhoff's current
389        law fixes the flow, ``"reactance"`` on a loop split by reactance,
390        ``"minimum_norm"`` on a loop of zero reactance elements, and
391        ``"out_of_service"`` for an element that carries none.
392        """
393        return self._inner.calc_removed_flows(
394            [float(p) for p in branch_p_from],
395            [float(p) for p in branch_p_to],
396            generator_p=None
397            if generator_p is None
398            else [float(p) for p in generator_p],
399            transformer_3w_p=None
400            if transformer_3w_p is None
401            else [tuple(float(p) for p in row) for row in transformer_3w_p],
402        )

The result of BalancedNetwork.merge_buses().

network is the merged network. merged_buses maps every merged bus to the bus that now carries it, and groups lists each joined set as {"survivor", "members"}. removed_branches and removed_switches describe every element the merge removed: its source row, id, from_id and to_id buses, survivor, reason ("zero_impedance", "closed_switch", or "shorted"), status, and ratings. branch_rows and switch_rows map each source row to its merged row, or None when removed, and charging_shunts lists the merged shunt rows that hold removed branches' equivalent admittances. diagnostics holds the merge's findings, which the merged network's module carries as well.

BusMerge(inner: Any)
320    def __init__(self, inner: "_powerio._BusMerge"):
321        self._inner = inner
network: BalancedNetwork
326    @property
327    def network(self) -> "BalancedNetwork":
328        return BalancedNetwork(self._inner.network)
rule: str
330    @property
331    def rule(self) -> str:
332        return self._inner.rule
merged_buses: Dict[int, int]
334    @property
335    def merged_buses(self) -> dict[int, int]:
336        return self._inner.merged_buses
groups: List[powerio.BusGroup]
338    @property
339    def groups(self) -> list[dict[str, Any]]:
340        return self._inner.groups
removed_branches: List[powerio.RemovedBranch]
342    @property
343    def removed_branches(self) -> list[dict[str, Any]]:
344        return self._inner.removed_branches
removed_switches: List[powerio.RemovedSwitch]
346    @property
347    def removed_switches(self) -> list[dict[str, Any]]:
348        return self._inner.removed_switches
branch_rows: List[Optional[int]]
350    @property
351    def branch_rows(self) -> list[Optional[int]]:
352        return self._inner.branch_rows
switch_rows: List[Optional[int]]
354    @property
355    def switch_rows(self) -> list[Optional[int]]:
356        return self._inner.switch_rows
charging_shunts: List[int]
358    @property
359    def charging_shunts(self) -> list[int]:
360        return self._inner.charging_shunts
diagnostics: List[Diagnostic]
362    @property
363    def diagnostics(self) -> list[Diagnostic]:
364        return self._inner.diagnostics
def survivor(self, bus: int) -> int:
366    def survivor(self, bus: int) -> int:
367        """The bus that carries ``bus`` in the merged network."""
368        return self._inner.survivor(bus)

The bus that carries bus in the merged network.

def calc_removed_flows( self, branch_p_from: Any, branch_p_to: Any, *, generator_p: Any = Ellipsis, transformer_3w_p: Any = Ellipsis) -> powerio.RemovedFlows:
370    def calc_removed_flows(
371        self,
372        branch_p_from: Any,
373        branch_p_to: Any,
374        *,
375        generator_p: Any = None,
376        transformer_3w_p: Any = None,
377    ) -> dict[str, Any]:
378        """Recover the active power on every removed element.
379
380        ``branch_p_from`` and ``branch_p_to`` are the power entering each
381        merged network branch at its from and to ends; ``generator_p``
382        replaces the stated generator outputs, and ``transformer_3w_p`` gives
383        the power entering each three winding transformer winding from its
384        bus, three values per transformer. Values are in the network's units
385        (MW for a parsed network). The result has ``branches`` and
386        ``switches``, one ``{"p_from", "method"}`` per removed element in the
387        order of :attr:`removed_branches` and :attr:`removed_switches`, and
388        ``diagnostics``. ``method`` is ``"tree"`` where Kirchhoff's current
389        law fixes the flow, ``"reactance"`` on a loop split by reactance,
390        ``"minimum_norm"`` on a loop of zero reactance elements, and
391        ``"out_of_service"`` for an element that carries none.
392        """
393        return self._inner.calc_removed_flows(
394            [float(p) for p in branch_p_from],
395            [float(p) for p in branch_p_to],
396            generator_p=None
397            if generator_p is None
398            else [float(p) for p in generator_p],
399            transformer_3w_p=None
400            if transformer_3w_p is None
401            else [tuple(float(p) for p in row) for row in transformer_3w_p],
402        )

Recover the active power on every removed element.

branch_p_from and branch_p_to are the power entering each merged network branch at its from and to ends; generator_p replaces the stated generator outputs, and transformer_3w_p gives the power entering each three winding transformer winding from its bus, three values per transformer. Values are in the network's units (MW for a parsed network). The result has branches and switches, one {"p_from", "method"} per removed element in the order of removed_branches and removed_switches, and diagnostics. method is "tree" where Kirchhoff's current law fixes the flow, "reactance" on a loop split by reactance, "minimum_norm" on a loop of zero reactance elements, and "out_of_service" for an element that carries none.

class CalculationUpdate:
data_role
class Collection:
25class Collection:
26    """A shared inventory. Closing it does not invalidate parsed modules.
27
28    Inspect returns metadata and suggested selection dictionaries without
29    electrical parsing. Pass one selection to parse. Candidates are not a
30    completeness or solver-readiness certificate.
31    """
32
33    def __init__(self, native: Any) -> None:
34        self._native = native
35
36    @classmethod
37    @guard
38    def open(cls, path: str | os.PathLike[str], *, max_bytes: int = 64 << 20,
39             max_files: int = 4096) -> Collection:
40        return cls(_powerio._Collection._open(os.fspath(path), max_bytes, max_files))
41
42    @classmethod
43    @guard
44    def from_zip(cls, data: bytes, *, name: str = "collection.zip",
45                 max_bytes: int = 64 << 20, max_files: int = 4096) -> Collection:
46        return cls(_powerio._Collection._from_zip(name, data, max_bytes, max_files))
47
48    @classmethod
49    @guard
50    def from_files(cls, files: Mapping[str, bytes], *, name: str = "collection",
51                   max_bytes: int = 64 << 20, max_files: int = 4096) -> Collection:
52        return cls(_powerio._Collection._from_files(name, dict(files), max_bytes, max_files))
53
54    @guard
55    def inspect(self) -> dict[str, Any]:
56        return self._native._inspect()
57
58    @guard
59    def parse(self, selection: Mapping[str, Any], *,
60              sincal_multiconductor: SincalReadOptions | None = None,
61              sincal_balanced: SincalBalancedReadOptions | None = None) -> CollectionResult:
62        from . import PioModule
63        from ._sincal import _native_selections
64        tx, mc = _native_selections(sincal_balanced, sincal_multiconductor)
65        module, dependencies, incomplete = self._native._parse(json.dumps(dict(selection)), mc, tx)
66        return CollectionResult(PioModule(module), tuple(dependencies), incomplete)
67
68    def close(self) -> None:
69        self._native.close()
70
71    def __enter__(self) -> Collection:
72        return self
73
74    def __exit__(self, *_: Any) -> None:
75        self.close()

A shared inventory. Closing it does not invalidate parsed modules.

Inspect returns metadata and suggested selection dictionaries without electrical parsing. Pass one selection to parse. Candidates are not a completeness or solver-readiness certificate.

Collection(native: Any)
33    def __init__(self, native: Any) -> None:
34        self._native = native
@classmethod
@guard
def open( cls, path: str | os.PathLike[str], *, max_bytes: int = 67108864, max_files: int = 4096) -> Collection:
36    @classmethod
37    @guard
38    def open(cls, path: str | os.PathLike[str], *, max_bytes: int = 64 << 20,
39             max_files: int = 4096) -> Collection:
40        return cls(_powerio._Collection._open(os.fspath(path), max_bytes, max_files))
@classmethod
@guard
def from_zip( cls, data: bytes, *, name: str = 'collection.zip', max_bytes: int = 67108864, max_files: int = 4096) -> Collection:
42    @classmethod
43    @guard
44    def from_zip(cls, data: bytes, *, name: str = "collection.zip",
45                 max_bytes: int = 64 << 20, max_files: int = 4096) -> Collection:
46        return cls(_powerio._Collection._from_zip(name, data, max_bytes, max_files))
@classmethod
@guard
def from_files( cls, files: Mapping[str, bytes], *, name: str = 'collection', max_bytes: int = 67108864, max_files: int = 4096) -> Collection:
48    @classmethod
49    @guard
50    def from_files(cls, files: Mapping[str, bytes], *, name: str = "collection",
51                   max_bytes: int = 64 << 20, max_files: int = 4096) -> Collection:
52        return cls(_powerio._Collection._from_files(name, dict(files), max_bytes, max_files))
@guard
def inspect(self) -> dict[str, typing.Any]:
54    @guard
55    def inspect(self) -> dict[str, Any]:
56        return self._native._inspect()
@guard
def parse( self, selection: Mapping[str, Any], *, sincal_multiconductor: powerio.dist.SincalReadOptions | None = None, sincal_balanced: SincalBalancedReadOptions | None = None) -> CollectionResult:
58    @guard
59    def parse(self, selection: Mapping[str, Any], *,
60              sincal_multiconductor: SincalReadOptions | None = None,
61              sincal_balanced: SincalBalancedReadOptions | None = None) -> CollectionResult:
62        from . import PioModule
63        from ._sincal import _native_selections
64        tx, mc = _native_selections(sincal_balanced, sincal_multiconductor)
65        module, dependencies, incomplete = self._native._parse(json.dumps(dict(selection)), mc, tx)
66        return CollectionResult(PioModule(module), tuple(dependencies), incomplete)
def close(self) -> None:
68    def close(self) -> None:
69        self._native.close()
@dataclass(frozen=True)
class CollectionResult:
18@dataclass(frozen=True)
19class CollectionResult:
20    module: PioModule
21    dependencies: tuple[str, ...]
22    incomplete: bool
CollectionResult( module: PioModule, dependencies: tuple[str, ...], incomplete: bool)
module: PioModule
dependencies: tuple[str, ...]
incomplete: bool
class ComponentId:
local_id
component_type
class ContingencySet(_TypedValue):
1734@_guard_class
1735class ContingencySet(_TypedValue):
1736    """A PSS/E contingency description file: the cases to run, the automatic
1737    specifications that state cases by rule, and the ``SKIP`` rules.
1738
1739    :func:`parse` returns it for a ``.con`` file or for text declared as
1740    ``psse-con``, :func:`powerio.emit` writes it back under that token, and
1741    :func:`serialize` carries it through PowerIO IR. Bind a set to a case with
1742    ``network.resolve_contingencies(cases.text)`` and turn its automatic
1743    specifications into explicit cases with
1744    ``network.expand_contingencies(cases.text, groups.text)``.
1745    """
1746
1747    @property
1748    def text(self) -> str:
1749        """The ``.con`` text for this set."""
1750        return _emitted_text(self.module, "psse-con")

A PSS/E contingency description file: the cases to run, the automatic specifications that state cases by rule, and the SKIP rules.

parse() returns it for a .con file or for text declared as psse-con, powerio.emit() writes it back under that token, and serialize() carries it through PowerIO IR. Bind a set to a case with network.resolve_contingencies(cases.text) and turn its automatic specifications into explicit cases with network.expand_contingencies(cases.text, groups.text).

text: str
1747    @property
1748    def text(self) -> str:
1749        """The ``.con`` text for this set."""
1750        return _emitted_text(self.module, "psse-con")

The .con text for this set.

Inherited Members
_TypedValue
_TypedValue
module
class DcOpfInstance(_BalancedCalculation):
1422class DcOpfInstance(_BalancedCalculation):
1423    """A DC optimal power flow calculation instance."""

A DC optimal power flow calculation instance.

class DcOpfSolution(_BalancedCalculation, _CalculationSolution):
1540class DcOpfSolution(_BalancedCalculation, _CalculationSolution):
1541    """A DC optimal power flow solution."""

A DC optimal power flow solution.

class DcPfInstance(_BalancedCalculation):
1414class DcPfInstance(_BalancedCalculation):
1415    """A DC power flow calculation instance."""

A DC power flow calculation instance.

class DcPfSolution(_BalancedCalculation, _CalculationSolution):
1532class DcPfSolution(_BalancedCalculation, _CalculationSolution):
1533    """A DC power flow solution."""

A DC power flow solution.

class Diagnostic:

One coded, user facing finding from a parse, read, transform, or write pass: the Python mirror of powerio_core::Diagnostic. Every module carries a list of these; PioModule.diagnostics returns them natively instead of the diagnostics_json string form.

target
related
message
code
suggested_action
severity

"error", "warning", "remark", or "note".

id
spans
details

Free form structured detail, or None when the finding carries none.

@dataclass(frozen=True)
class EmitResult:
204@dataclass(frozen=True)
205class EmitResult:
206    """Artifact inventory and diagnostics from an emission or serialization."""
207
208    artifacts: tuple[Artifact, ...]
209    layout: str
210    fidelity: str
211    diagnostics: tuple[Diagnostic, ...]
212
213    @property
214    def text(self) -> Optional[str]:
215        """The sole UTF-8 memory artifact, or ``None`` for other inventories."""
216        if len(self.artifacts) != 1 or self.artifacts[0].data is None:
217            return None
218        return self.artifacts[0].text

Artifact inventory and diagnostics from an emission or serialization.

EmitResult( artifacts: Tuple[Artifact, ...], layout: Literal['file', 'directory'], fidelity: Literal['exact_same_format', 'canonical'], diagnostics: Tuple[Diagnostic, ...])
artifacts: Tuple[Artifact, ...]
layout: Literal['file', 'directory']
fidelity: Literal['exact_same_format', 'canonical']
diagnostics: Tuple[Diagnostic, ...]
text: Optional[str]
213    @property
214    def text(self) -> Optional[str]:
215        """The sole UTF-8 memory artifact, or ``None`` for other inventories."""
216        if len(self.artifacts) != 1 or self.artifacts[0].data is None:
217            return None
218        return self.artifacts[0].text

The sole UTF-8 memory artifact, or None for other inventories.

class FormatInfo(builtins.tuple):

FormatInfo(token, extension, is_directory, can_emit)

FormatInfo( token: str, extension: ForwardRef('Optional[str]'), is_directory: bool, can_emit: bool)

Create new instance of FormatInfo(token, extension, is_directory, can_emit)

token: str

Alias for field number 0

extension: Optional[str]

Alias for field number 1

is_directory: bool

Alias for field number 2

can_emit: bool

Alias for field number 3

class GeoLayer(_TypedValue):
1702@_guard_class
1703class GeoLayer(_TypedValue):
1704    """A standalone geographic document: element points and routes keyed by
1705    element identity, in one coordinate space.
1706
1707    :func:`parse` returns it for the canonical ``.geo.json``, GeoJSON, aliased
1708    CSV or JSON records, headerless buscoords CSV, and a PowerWorld ``.pwd``
1709    display. :func:`powerio.emit` writes the canonical document as
1710    ``geo-json``, and :func:`serialize` carries the layer through PowerIO IR.
1711    Place a layer onto a case with
1712    ``network.apply_geo_layer(layer.geojson)``.
1713    """
1714
1715    @property
1716    def geojson(self) -> str:
1717        """The canonical ``.geo.json`` document for this layer."""
1718        result = emit(self.module, "geo-json")
1719        data = result.artifacts[0].data
1720        if data is None:
1721            raise ValueError("the layer emission returned no artifact bytes")
1722        return data.decode("utf-8")

A standalone geographic document: element points and routes keyed by element identity, in one coordinate space.

parse() returns it for the canonical .geo.json, GeoJSON, aliased CSV or JSON records, headerless buscoords CSV, and a PowerWorld .pwd display. powerio.emit() writes the canonical document as geo-json, and serialize() carries the layer through PowerIO IR. Place a layer onto a case with network.apply_geo_layer(layer.geojson).

geojson: str
1715    @property
1716    def geojson(self) -> str:
1717        """The canonical ``.geo.json`` document for this layer."""
1718        result = emit(self.module, "geo-json")
1719        data = result.artifacts[0].data
1720        if data is None:
1721            raise ValueError("the layer emission returned no artifact bytes")
1722        return data.decode("utf-8")

The canonical .geo.json document for this layer.

Inherited Members
_TypedValue
_TypedValue
module
class LinDist3FlowOpfInstance(_MulticonductorCalculation):
1508@_guard_class
1509class LinDist3FlowOpfInstance(_MulticonductorCalculation):
1510    """A radial fixed-reference multiconductor linear OPF instance."""
1511
1512    @property
1513    def metadata(self) -> dict[str, Any]:
1514        """Node and conductor axes, roots, and reference phasors in volts/radians."""
1515        return self.module._inner._lindist3flow_metadata()

A radial fixed-reference multiconductor linear OPF instance.

metadata: dict[str, typing.Any]
1512    @property
1513    def metadata(self) -> dict[str, Any]:
1514        """Node and conductor axes, roots, and reference phasors in volts/radians."""
1515        return self.module._inner._lindist3flow_metadata()

Node and conductor axes, roots, and reference phasors in volts/radians.

class LinDist3FlowOpfSolution(_MulticonductorCalculation, _CalculationSolution):
1644@_guard_class
1645class LinDist3FlowOpfSolution(_MulticonductorCalculation, _CalculationSolution):
1646    """LinDist3Flow primal values in squared volts, watts, and vars."""
1647
1648    @property
1649    def termination(self) -> str:
1650        """How the calculation ended."""
1651        return self.module._inner._lindist3flow_solution_termination()
1652
1653    @property
1654    def objective(self) -> float:
1655        """The reported objective value."""
1656        return self.module._inner._lindist3flow_solution_objective()
1657
1658    def __getitem__(self, quantity: str) -> list[float]:
1659        """Copy one named primal column in its physical instance order."""
1660        return self.module._inner._lindist3flow_solution_values(quantity)

LinDist3Flow primal values in squared volts, watts, and vars.

termination: str
1648    @property
1649    def termination(self) -> str:
1650        """How the calculation ended."""
1651        return self.module._inner._lindist3flow_solution_termination()

How the calculation ended.

objective: float
1653    @property
1654    def objective(self) -> float:
1655        """The reported objective value."""
1656        return self.module._inner._lindist3flow_solution_objective()

The reported objective value.

class LinDist3FlowPfInstance(_MulticonductorCalculation):
1498@_guard_class
1499class LinDist3FlowPfInstance(_MulticonductorCalculation):
1500    """A fixed-dispatch LinDist3Flow power-flow instance."""
1501
1502    @property
1503    def metadata(self) -> dict[str, Any]:
1504        """Node/conductor axes, preparation actions, and reference phasors."""
1505        return self.module._inner._lindist3flow_metadata()

A fixed-dispatch LinDist3Flow power-flow instance.

metadata: dict[str, typing.Any]
1502    @property
1503    def metadata(self) -> dict[str, Any]:
1504        """Node/conductor axes, preparation actions, and reference phasors."""
1505        return self.module._inner._lindist3flow_metadata()

Node/conductor axes, preparation actions, and reference phasors.

class LinDist3FlowPfSolution(_MulticonductorCalculation, _CalculationSolution):
1625@_guard_class
1626class LinDist3FlowPfSolution(_MulticonductorCalculation, _CalculationSolution):
1627    """Fixed-dispatch LinDist3Flow values and monitored SI line limits."""
1628
1629    @property
1630    def termination(self) -> str:
1631        """How the calculation ended."""
1632        return self.module._inner._lindist3flow_solution_termination()
1633
1634    @property
1635    def limit_checks(self) -> list[dict[str, Any]]:
1636        """Monitored line ratings, values, loading ratios, and overload flags."""
1637        return self.module._inner._lindist3flow_limit_checks()
1638
1639    def __getitem__(self, quantity: str) -> list[float]:
1640        """Copy one named primal column in its physical instance order."""
1641        return self.module._inner._lindist3flow_solution_values(quantity)

Fixed-dispatch LinDist3Flow values and monitored SI line limits.

termination: str
1629    @property
1630    def termination(self) -> str:
1631        """How the calculation ended."""
1632        return self.module._inner._lindist3flow_solution_termination()

How the calculation ended.

limit_checks: list[dict[str, typing.Any]]
1634    @property
1635    def limit_checks(self) -> list[dict[str, Any]]:
1636        """Monitored line ratings, values, loading ratios, and overload flags."""
1637        return self.module._inner._lindist3flow_limit_checks()

Monitored line ratings, values, loading ratios, and overload flags.

class McAcOpfInstance(_MulticonductorCalculation):
1518class McAcOpfInstance(_MulticonductorCalculation):
1519    """A multiconductor AC optimal power flow calculation instance."""

A multiconductor AC optimal power flow calculation instance.

class McAcOpfSolution(_MulticonductorCalculation, _CalculationSolution):
1663class McAcOpfSolution(_MulticonductorCalculation, _CalculationSolution):
1664    """A multiconductor AC optimal power flow solution."""

A multiconductor AC optimal power flow solution.

class McAcPfInstance(_MulticonductorCalculation):
1494class McAcPfInstance(_MulticonductorCalculation):
1495    """A multiconductor AC power flow calculation instance."""

A multiconductor AC power flow calculation instance.

class McAcPfSolution(_MulticonductorCalculation, _CalculationSolution):
1621class McAcPfSolution(_MulticonductorCalculation, _CalculationSolution):
1622    """A multiconductor AC power flow solution."""

A multiconductor AC power flow solution.

class MonitoredSet(_TypedValue):
1769@_guard_class
1770class MonitoredSet(_TypedValue):
1771    """A PSS/E monitored element file: the branches, interfaces, and voltage
1772    scopes a contingency run reports on.
1773
1774    :func:`parse` returns it for a ``.mon`` file or for text declared as
1775    ``psse-mon``.
1776    """
1777
1778    @property
1779    def text(self) -> str:
1780        """The ``.mon`` text for this set."""
1781        return _emitted_text(self.module, "psse-mon")

A PSS/E monitored element file: the branches, interfaces, and voltage scopes a contingency run reports on.

parse() returns it for a .mon file or for text declared as psse-mon.

text: str
1778    @property
1779    def text(self) -> str:
1780        """The ``.mon`` text for this set."""
1781        return _emitted_text(self.module, "psse-mon")

The .mon text for this set.

Inherited Members
_TypedValue
_TypedValue
module
class MulticonductorNetwork:
 57@_guard_class
 58class MulticonductorNetwork:
 59    """A parsed multiconductor distribution network in wire coordinates.
 60
 61    Buses carry named terminals, lines carry conductor impedance matrices, and
 62    transformers carry per winding connections. This type is distinct from the
 63    positive sequence :class:`powerio.BalancedNetwork`; balanced matrix calculations do not
 64    accept it.
 65    """
 66
 67    def __init__(self, inner) -> None:
 68        self._inner = inner
 69
 70    @property
 71    def name(self) -> Optional[str]:
 72        """Distribution network name when the source format carries one."""
 73        return self._inner.name()
 74
 75    @property
 76    def source_format(self) -> Optional[str]:
 77        """Format parsed from: ``dss``, ``pmd-json``, ``pmd-math-json``,
 78        ``bmopf-json``, ``ravens-json``, ``cim-dist``, or ``sincal``; ``None``
 79        for a network built in code."""
 80        return self._inner.source_format()
 81
 82    @property
 83    def base_frequency(self) -> float:
 84        """System base frequency in hertz."""
 85        return self._inner.base_frequency()
 86
 87    @property
 88    def n_buses(self) -> int:
 89        return self._inner.n_buses()
 90
 91    @property
 92    def n_lines(self) -> int:
 93        return self._inner.n_lines()
 94
 95    @property
 96    def n_line_codes(self) -> int:
 97        return self._inner.n_line_codes()
 98
 99    @property
100    def n_switches(self) -> int:
101        return self._inner.n_switches()
102
103    @property
104    def n_transformers(self) -> int:
105        return self._inner.n_transformers()
106
107    @property
108    def n_loads(self) -> int:
109        return self._inner.n_loads()
110
111    @property
112    def n_generators(self) -> int:
113        return self._inner.n_generators()
114
115    @property
116    def n_ibrs(self) -> int:
117        return self._inner.n_ibrs()
118
119    @property
120    def n_control_profiles(self) -> int:
121        return self._inner.n_control_profiles()
122
123    @property
124    def n_shunts(self) -> int:
125        return self._inner.n_shunts()
126
127    @property
128    def n_capacitors(self) -> int:
129        return self._inner.n_capacitors()
130
131    @property
132    def n_voltage_sources(self) -> int:
133        """Number of grid forming voltage sources."""
134        return self._inner.n_voltage_sources()
135
136    @property
137    def n_untyped_objects(self) -> int:
138        return self._inner.n_untyped_objects()
139
140    # These properties are copies of the native model tables. Nested field
141    # names come from the Rust model's serialization, so this wrapper does not
142    # maintain a second distribution schema.
143
144    @property
145    def buses(self) -> "list[dict[str, Any]]":
146        return self._inner.buses()
147
148    @property
149    def line_codes(self) -> "list[dict[str, Any]]":
150        return self._inner.line_codes()
151
152    @property
153    def lines(self) -> "list[dict[str, Any]]":
154        return self._inner.lines()
155
156    @property
157    def switches(self) -> "list[dict[str, Any]]":
158        return self._inner.switches()
159
160    @property
161    def transformers(self) -> "list[dict[str, Any]]":
162        return self._inner.transformers()
163
164    @property
165    def loads(self) -> "list[dict[str, Any]]":
166        return self._inner.loads()
167
168    @property
169    def generators(self) -> "list[dict[str, Any]]":
170        return self._inner.generators()
171
172    @property
173    def ibrs(self) -> "list[dict[str, Any]]":
174        return self._inner.ibrs()
175
176    @property
177    def control_profiles(self) -> "list[dict[str, Any]]":
178        return self._inner.control_profiles()
179
180    @property
181    def shunts(self) -> "list[dict[str, Any]]":
182        return self._inner.shunts()
183
184    @property
185    def capacitors(self) -> "list[dict[str, Any]]":
186        return self._inner.capacitors()
187
188    @property
189    def voltage_sources(self) -> "list[dict[str, Any]]":
190        return self._inner.voltage_sources()
191
192    @property
193    def untyped_objects(self) -> "list[dict[str, Any]]":
194        return self._inner.untyped_objects()
195
196    def to_graph(self) -> Any:
197        """Transform the network to collapsed bus and terminal graph data."""
198        return _json.loads(self._inner.graph_json())
199
200    def to_geo_layer(self) -> Any:
201        """Transform coordinates to a canonical GeoJSON FeatureCollection.
202
203        A network without coordinates produces an empty feature collection.
204        """
205        return _json.loads(self._inner.to_geo_layer_json())
206
207    def apply_geo_layer(
208        self, text: str, name_hint: Optional[str] = None
209    ) -> tuple["MulticonductorNetwork", Any]:
210        """Apply a geographic sidecar and return ``(placed, report)``.
211
212        ``text`` is any form :func:`powerio.parse_geo` accepts. This network
213        is unchanged; the placed copy drops the retained source text, so a
214        same-format emission re-serializes.
215        """
216        inner, report = self._inner.apply_geo_layer(text, name_hint)
217        return MulticonductorNetwork(inner), report
218
219    def __repr__(self) -> str:
220        return self._inner.__repr__()

A parsed multiconductor distribution network in wire coordinates.

Buses carry named terminals, lines carry conductor impedance matrices, and transformers carry per winding connections. This type is distinct from the positive sequence powerio.BalancedNetwork; balanced matrix calculations do not accept it.

MulticonductorNetwork(inner)
67    def __init__(self, inner) -> None:
68        self._inner = inner
name: Optional[str]
70    @property
71    def name(self) -> Optional[str]:
72        """Distribution network name when the source format carries one."""
73        return self._inner.name()

Distribution network name when the source format carries one.

source_format: Optional[str]
75    @property
76    def source_format(self) -> Optional[str]:
77        """Format parsed from: ``dss``, ``pmd-json``, ``pmd-math-json``,
78        ``bmopf-json``, ``ravens-json``, ``cim-dist``, or ``sincal``; ``None``
79        for a network built in code."""
80        return self._inner.source_format()

Format parsed from: dss, pmd-json, pmd-math-json, bmopf-json, ravens-json, cim-dist, or sincal; None for a network built in code.

base_frequency: float
82    @property
83    def base_frequency(self) -> float:
84        """System base frequency in hertz."""
85        return self._inner.base_frequency()

System base frequency in hertz.

n_buses: int
87    @property
88    def n_buses(self) -> int:
89        return self._inner.n_buses()
n_lines: int
91    @property
92    def n_lines(self) -> int:
93        return self._inner.n_lines()
n_line_codes: int
95    @property
96    def n_line_codes(self) -> int:
97        return self._inner.n_line_codes()
n_switches: int
 99    @property
100    def n_switches(self) -> int:
101        return self._inner.n_switches()
n_transformers: int
103    @property
104    def n_transformers(self) -> int:
105        return self._inner.n_transformers()
n_loads: int
107    @property
108    def n_loads(self) -> int:
109        return self._inner.n_loads()
n_generators: int
111    @property
112    def n_generators(self) -> int:
113        return self._inner.n_generators()
n_ibrs: int
115    @property
116    def n_ibrs(self) -> int:
117        return self._inner.n_ibrs()
n_control_profiles: int
119    @property
120    def n_control_profiles(self) -> int:
121        return self._inner.n_control_profiles()
n_shunts: int
123    @property
124    def n_shunts(self) -> int:
125        return self._inner.n_shunts()
n_capacitors: int
127    @property
128    def n_capacitors(self) -> int:
129        return self._inner.n_capacitors()
n_voltage_sources: int
131    @property
132    def n_voltage_sources(self) -> int:
133        """Number of grid forming voltage sources."""
134        return self._inner.n_voltage_sources()

Number of grid forming voltage sources.

n_untyped_objects: int
136    @property
137    def n_untyped_objects(self) -> int:
138        return self._inner.n_untyped_objects()
buses: list[dict[str, typing.Any]]
144    @property
145    def buses(self) -> "list[dict[str, Any]]":
146        return self._inner.buses()
line_codes: list[dict[str, typing.Any]]
148    @property
149    def line_codes(self) -> "list[dict[str, Any]]":
150        return self._inner.line_codes()
lines: list[dict[str, typing.Any]]
152    @property
153    def lines(self) -> "list[dict[str, Any]]":
154        return self._inner.lines()
switches: list[dict[str, typing.Any]]
156    @property
157    def switches(self) -> "list[dict[str, Any]]":
158        return self._inner.switches()
transformers: list[dict[str, typing.Any]]
160    @property
161    def transformers(self) -> "list[dict[str, Any]]":
162        return self._inner.transformers()
loads: list[dict[str, typing.Any]]
164    @property
165    def loads(self) -> "list[dict[str, Any]]":
166        return self._inner.loads()
generators: list[dict[str, typing.Any]]
168    @property
169    def generators(self) -> "list[dict[str, Any]]":
170        return self._inner.generators()
ibrs: list[dict[str, typing.Any]]
172    @property
173    def ibrs(self) -> "list[dict[str, Any]]":
174        return self._inner.ibrs()
control_profiles: list[dict[str, typing.Any]]
176    @property
177    def control_profiles(self) -> "list[dict[str, Any]]":
178        return self._inner.control_profiles()
shunts: list[dict[str, typing.Any]]
180    @property
181    def shunts(self) -> "list[dict[str, Any]]":
182        return self._inner.shunts()
capacitors: list[dict[str, typing.Any]]
184    @property
185    def capacitors(self) -> "list[dict[str, Any]]":
186        return self._inner.capacitors()
voltage_sources: list[dict[str, typing.Any]]
188    @property
189    def voltage_sources(self) -> "list[dict[str, Any]]":
190        return self._inner.voltage_sources()
untyped_objects: list[dict[str, typing.Any]]
192    @property
193    def untyped_objects(self) -> "list[dict[str, Any]]":
194        return self._inner.untyped_objects()
def to_graph(self) -> Any:
196    def to_graph(self) -> Any:
197        """Transform the network to collapsed bus and terminal graph data."""
198        return _json.loads(self._inner.graph_json())

Transform the network to collapsed bus and terminal graph data.

def to_geo_layer(self) -> Any:
200    def to_geo_layer(self) -> Any:
201        """Transform coordinates to a canonical GeoJSON FeatureCollection.
202
203        A network without coordinates produces an empty feature collection.
204        """
205        return _json.loads(self._inner.to_geo_layer_json())

Transform coordinates to a canonical GeoJSON FeatureCollection.

A network without coordinates produces an empty feature collection.

def apply_geo_layer( self, text: str, name_hint: Optional[str] = None) -> tuple[MulticonductorNetwork, typing.Any]:
207    def apply_geo_layer(
208        self, text: str, name_hint: Optional[str] = None
209    ) -> tuple["MulticonductorNetwork", Any]:
210        """Apply a geographic sidecar and return ``(placed, report)``.
211
212        ``text`` is any form :func:`powerio.parse_geo` accepts. This network
213        is unchanged; the placed copy drops the retained source text, so a
214        same-format emission re-serializes.
215        """
216        inner, report = self._inner.apply_geo_layer(text, name_hint)
217        return MulticonductorNetwork(inner), report

Apply a geographic sidecar and return (placed, report).

text is any form powerio.parse_geo() accepts. This network is unchanged; the placed copy drops the retained source text, so a same-format emission re-serializes.

class NetworkUpdate:
def set_branch_thermal_rating(branch, rating, *, terminal=None):
field
class OperatingPoint(_TypedValue):
1361@_guard_class
1362class OperatingPoint(_TypedValue):
1363    """A possibly partial assignment over fixed equipment identities."""
1364
1365    @property
1366    def network(self) -> "BalancedNetwork":
1367        """The balanced network this operating point is stated over.
1368
1369        The point's own values are applied to the returned copy, so it is the
1370        network a solver receives for this entry; the collection's shared
1371        base network is not changed. A multiconductor operating point raises
1372        :class:`PowerIOError`.
1373
1374        Net bus injection quantities have no balanced network field, so they
1375        are dropped here and the property reports nothing. Emit the
1376        collection when you need that omission reported: `emit` warns
1377        `EMIT.OPERATING_POINT.DATA_OMITTED` for the same point.
1378        """
1379        return BalancedNetwork(self.module._inner._operating_point_network())

A possibly partial assignment over fixed equipment identities.

network: BalancedNetwork
1365    @property
1366    def network(self) -> "BalancedNetwork":
1367        """The balanced network this operating point is stated over.
1368
1369        The point's own values are applied to the returned copy, so it is the
1370        network a solver receives for this entry; the collection's shared
1371        base network is not changed. A multiconductor operating point raises
1372        :class:`PowerIOError`.
1373
1374        Net bus injection quantities have no balanced network field, so they
1375        are dropped here and the property reports nothing. Emit the
1376        collection when you need that omission reported: `emit` warns
1377        `EMIT.OPERATING_POINT.DATA_OMITTED` for the same point.
1378        """
1379        return BalancedNetwork(self.module._inner._operating_point_network())

The balanced network this operating point is stated over.

The point's own values are applied to the returned copy, so it is the network a solver receives for this entry; the collection's shared base network is not changed. A multiconductor operating point raises PowerIOError.

Net bus injection quantities have no balanced network field, so they are dropped here and the property reports nothing. Emit the collection when you need that omission reported: emit warns EMIT.OPERATING_POINT.DATA_OMITTED for the same point.

Inherited Members
_TypedValue
_TypedValue
module
class OperatingPointUpdate:
def set_load_active_power(load, p, *, terminal=None):
def set_load_reactive_power(load, q, *, terminal=None):
def set_generator_active_power(generator, p, *, terminal=None):
def set_generator_reactive_power(generator, q, *, terminal=None):
def set_generator_voltage_magnitude(generator, vm_pu):
def set_generator_in_service(generator, in_service):
def set_branch_in_service(branch, in_service):
def set_transformer_tap_ratio(transformer, tap_ratio):
def set_transformer_phase_shift(transformer, shift_degrees):
def set_switch_closed(switch, closed):
field
class PioModule:
1815@_guard_class
1816class PioModule:
1817    """One typed value with diagnostics, producer, sources, source mappings,
1818    history, and extensions.
1819    """
1820
1821    def __init__(self, inner: "_powerio._PioModule"):
1822        self._inner = inner
1823
1824    def sever_source(self) -> "PioModule":
1825        """Copy this module without retained input bytes, forcing fresh emission.
1826
1827        The original module is unchanged. Values, diagnostics, source
1828        descriptors, and history are preserved; preparing the copy has a cost
1829        separate from emission.
1830        """
1831        return PioModule(self._inner.sever_source())
1832
1833    @classmethod
1834    def from_value(cls, value: Any) -> "PioModule":
1835        """Wrap an existing typed value without serializing it."""
1836        if isinstance(value, BalancedNetwork):
1837            return cls(_powerio._PioModule.from_balanced_network(value._inner))
1838        if isinstance(value, dist.MulticonductorNetwork):
1839            return cls(_powerio._PioModule.from_multiconductor_network(value._inner))
1840        if isinstance(value, _TypedValue):
1841            location = value._collection_entry
1842            inner = value.module._inner
1843            if location is not None:
1844                inner = location.root._inner
1845                if location.scenario_id is not None:
1846                    inner = inner._scenario_get(location.scenario_id)
1847                if location.time_index is not None:
1848                    inner = inner._time_series_get(location.time_index)
1849            return cls(inner._copy())
1850        raise TypeError("PioModule.from_value expects a typed PowerIO value")
1851
1852    @property
1853    def value(self) -> Any:
1854        """The contained typed value."""
1855        type_name = self._inner._type_name
1856        if type_name == "powerio.BalancedNetwork":
1857            return BalancedNetwork(self._inner.as_balanced_network())
1858        if type_name == "powerio.MulticonductorNetwork":
1859            return dist.MulticonductorNetwork(self._inner.as_multiconductor_network())
1860        if type_name.startswith("powerio.TimeSeries<"):
1861            return TimeSeries._from_module(self)
1862        if type_name.startswith("powerio.ScenarioSet<"):
1863            return ScenarioSet._from_module(self)
1864        value_class = _VALUE_CLASSES.get(type_name)
1865        if value_class is None:
1866            raise RuntimeError(f"this binding has no Python class for {type_name}")
1867        return value_class(self)
1868
1869    @property
1870    def type_name(self) -> str:
1871        """The canonical structural name of the contained value, such as
1872        ``powerio.OperatingPoint<powerio.BalancedNetwork>``. The C ABI and
1873        PowerIO IR name the same type with the same string.
1874        """
1875        return str(self._inner._type_name)
1876
1877    @property
1878    def diagnostics(self) -> list[Diagnostic]:
1879        """The diagnostics stored on this module, in encounter order."""
1880        return list(self._inner.diagnostics)
1881
1882    @property
1883    def extension_keys(self) -> list[str]:
1884        """The namespaces of the extensions this module carries, sorted."""
1885        return list(self._inner._extension_keys)
1886
1887    def extension(self, namespace: str) -> Any:
1888        """The JSON value stored under ``namespace``, or ``None``.
1889
1890        Only that value is decoded; the module is not serialized.
1891        """
1892        text = self._inner._extension_json(namespace)
1893        return None if text is None else _json.loads(text)
1894
1895    def with_extension(self, namespace: str, value: Any) -> "PioModule":
1896        """A copy of this module carrying ``value`` under ``namespace``.
1897
1898        ``value`` must be JSON serializable. The copy keeps the typed value,
1899        diagnostics, sources, and history without serializing them; an
1900        extension already stored under ``namespace`` is replaced. The original
1901        module is unchanged.
1902        """
1903        return PioModule(self._inner._with_extension_json(namespace, _json.dumps(value)))
1904
1905    def to_balanced_report(self, base_mva: float = 100.0) -> Any:
1906        """Report whether a multiconductor network can become balanced."""
1907        return _json.loads(self._inner.lowering_readiness_json(base_mva))
1908
1909    def to_balanced(self, base_mva: float = 100.0) -> "PioModule":
1910        """Transform a multiconductor network to a balanced module."""
1911        return PioModule(self._inner.lower_to_balanced(base_mva))
1912
1913    def to_dc_pf_instance(self) -> "PioModule":
1914        """Build a DC power flow instance from a balanced network module."""
1915        return PioModule(self._inner._to_dc_pf_instance())
1916
1917    def to_ac_pf_instance(self) -> "PioModule":
1918        """Build an AC power flow instance from a balanced network module."""
1919        return PioModule(self._inner._to_ac_pf_instance())
1920
1921    def to_dc_opf_instance(self) -> "PioModule":
1922        """Build a DC optimal power flow instance from a balanced network module."""
1923        return PioModule(self._inner._to_dc_opf_instance())
1924
1925    def to_ac_opf_instance(self) -> "PioModule":
1926        """Build an AC optimal power flow instance from a balanced network module."""
1927        return PioModule(self._inner._to_ac_opf_instance())
1928
1929    def to_ac_ots_instance(
1930        self,
1931        *,
1932        switchable: Union[str, Sequence[str], None] = None,
1933        switching_costs: Optional[Mapping[str, tuple[float, float]]] = None,
1934        islanding: Optional[str] = None,
1935        max_open: Optional[int] = None,
1936        max_switched: Optional[int] = None,
1937        current_limits: Optional[str] = None,
1938        stated_current_limits: Optional[
1939            Mapping[str, tuple[Optional[float], Optional[float]]]
1940        ] = None,
1941    ) -> "PioModule":
1942        """Build an AC optimal transmission switching instance from a balanced
1943        network, AC optimal power flow, or AC optimal transmission switching
1944        module.
1945
1946        With no option, this gives the default instance: every initially
1947        in-service branch may switch, at zero cost, islanding is forbidden,
1948        there is no budget and no current limit, and the objective gains the
1949        switching cost term. An AC optimal transmission switching module comes
1950        back unchanged.
1951
1952        Any option makes the options explicit, as the C ABI's options struct
1953        and PowerIO.jl's ``AcOtsOptions`` do, and an option not given takes
1954        its explicit default:
1955
1956        - ``switchable``: ``"all"`` (the default, which includes initially
1957          open branches), ``"none"``, or a list of branch identities.
1958        - ``switching_costs``: ``{branch_id: (open_cost, close_cost)}``; a
1959          branch with no entry switches at zero cost.
1960        - ``islanding``: ``"forbidden"`` (the default) or ``"allowed"``.
1961        - ``max_open``: the most branches open in the final topology,
1962          counting fixed open rows; ``None`` is no budget.
1963        - ``max_switched``: the most status changes; ``None`` is no budget.
1964        - ``current_limits``: ``"skip"`` (the default), ``"stated"``, or
1965          ``"derive_from_rate_a"``.
1966        - ``stated_current_limits``: ``{branch_id: (from_pu, to_pu)}``, per
1967          unit; ``None`` on a side is unbounded.
1968
1969        The base problem and objective are kept, and the objective gains the
1970        switching cost term once. Refused options raise
1971        :class:`PowerIOError` with code
1972        ``BUILD.INSTANCE.SWITCHING_OPTIONS_INVALID``; an unknown policy name
1973        raises :class:`ValueError`.
1974        """
1975        if (
1976            switchable is None
1977            and switching_costs is None
1978            and islanding is None
1979            and max_open is None
1980            and max_switched is None
1981            and current_limits is None
1982            and stated_current_limits is None
1983        ):
1984            return PioModule(self._inner._to_ac_ots_instance())
1985        if switchable is None:
1986            selection, identities = "all", []
1987        elif isinstance(switchable, str):
1988            selection, identities = switchable, []
1989        else:
1990            selection, identities = "only", [str(identity) for identity in switchable]
1991        for name, budget in (("max_open", max_open), ("max_switched", max_switched)):
1992            if budget is not None and (
1993                isinstance(budget, bool) or not isinstance(budget, int) or budget < 0
1994            ):
1995                raise ValueError(f"{name} must be a nonnegative integer or None")
1996        costs = [
1997            (str(identity), float(open_cost), float(close_cost))
1998            for identity, (open_cost, close_cost) in (switching_costs or {}).items()
1999        ]
2000        limits = [
2001            (
2002                str(identity),
2003                None if from_pu is None else float(from_pu),
2004                None if to_pu is None else float(to_pu),
2005            )
2006            for identity, (from_pu, to_pu) in (stated_current_limits or {}).items()
2007        ]
2008        return PioModule(
2009            self._inner._to_ac_ots_instance_with_options(
2010                selection,
2011                identities,
2012                costs,
2013                "forbidden" if islanding is None else islanding,
2014                max_open,
2015                max_switched,
2016                "skip" if current_limits is None else current_limits,
2017                limits,
2018            )
2019        )
2020
2021    def to_mc_ac_pf_instance(self) -> "PioModule":
2022        """Build a multiconductor AC power flow instance from a network module."""
2023        return PioModule(self._inner._to_mc_ac_pf_instance())
2024
2025    def to_mc_ac_opf_instance(self) -> "PioModule":
2026        """Build a multiconductor AC optimal power flow instance from a network module."""
2027        return PioModule(self._inner._to_mc_ac_opf_instance())
2028
2029    def to_lindist3flow_opf_instance(self) -> "PioModule":
2030        """Build a LinDist3Flow optimal power flow instance from a network module."""
2031        return PioModule(self._inner._to_lindist3flow_opf_instance())
2032
2033    def to_lindist3flow_pf_instance(self) -> "PioModule":
2034        """Build a fixed-dispatch LinDist3Flow instance from a network module."""
2035        return PioModule(self._inner._to_lindist3flow_pf_instance())
2036
2037    def __repr__(self) -> str:
2038        return repr(self._inner)

Abstract base class for generic types.

On Python 3.12 and newer, generic classes implicitly inherit from Generic when they declare a parameter list after the class's name::

class Mapping[KT, VT]:
    def __getitem__(self, key: KT) -> VT:
        ...
    # Etc.

On older versions of Python, however, generic classes have to explicitly inherit from Generic.

After a class has been declared to be generic, it can then be used as follows::

def lookup_name[KT, VT](mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
    try:
        return mapping[key]
    except KeyError:
        return default
PioModule(inner: Any)
1821    def __init__(self, inner: "_powerio._PioModule"):
1822        self._inner = inner
def sever_source(self) -> PioModule[~_T]:
1824    def sever_source(self) -> "PioModule":
1825        """Copy this module without retained input bytes, forcing fresh emission.
1826
1827        The original module is unchanged. Values, diagnostics, source
1828        descriptors, and history are preserved; preparing the copy has a cost
1829        separate from emission.
1830        """
1831        return PioModule(self._inner.sever_source())

Copy this module without retained input bytes, forcing fresh emission.

The original module is unchanged. Values, diagnostics, source descriptors, and history are preserved; preparing the copy has a cost separate from emission.

@classmethod
def from_value(*args, **kwds):
1833    @classmethod
1834    def from_value(cls, value: Any) -> "PioModule":
1835        """Wrap an existing typed value without serializing it."""
1836        if isinstance(value, BalancedNetwork):
1837            return cls(_powerio._PioModule.from_balanced_network(value._inner))
1838        if isinstance(value, dist.MulticonductorNetwork):
1839            return cls(_powerio._PioModule.from_multiconductor_network(value._inner))
1840        if isinstance(value, _TypedValue):
1841            location = value._collection_entry
1842            inner = value.module._inner
1843            if location is not None:
1844                inner = location.root._inner
1845                if location.scenario_id is not None:
1846                    inner = inner._scenario_get(location.scenario_id)
1847                if location.time_index is not None:
1848                    inner = inner._time_series_get(location.time_index)
1849            return cls(inner._copy())
1850        raise TypeError("PioModule.from_value expects a typed PowerIO value")

Wrap an existing typed value without serializing it.

value: ~_T
1852    @property
1853    def value(self) -> Any:
1854        """The contained typed value."""
1855        type_name = self._inner._type_name
1856        if type_name == "powerio.BalancedNetwork":
1857            return BalancedNetwork(self._inner.as_balanced_network())
1858        if type_name == "powerio.MulticonductorNetwork":
1859            return dist.MulticonductorNetwork(self._inner.as_multiconductor_network())
1860        if type_name.startswith("powerio.TimeSeries<"):
1861            return TimeSeries._from_module(self)
1862        if type_name.startswith("powerio.ScenarioSet<"):
1863            return ScenarioSet._from_module(self)
1864        value_class = _VALUE_CLASSES.get(type_name)
1865        if value_class is None:
1866            raise RuntimeError(f"this binding has no Python class for {type_name}")
1867        return value_class(self)

The contained typed value.

type_name: str
1869    @property
1870    def type_name(self) -> str:
1871        """The canonical structural name of the contained value, such as
1872        ``powerio.OperatingPoint<powerio.BalancedNetwork>``. The C ABI and
1873        PowerIO IR name the same type with the same string.
1874        """
1875        return str(self._inner._type_name)

The canonical structural name of the contained value, such as powerio.OperatingPoint<powerio.BalancedNetwork>. The C ABI and PowerIO IR name the same type with the same string.

diagnostics: List[Diagnostic]
1877    @property
1878    def diagnostics(self) -> list[Diagnostic]:
1879        """The diagnostics stored on this module, in encounter order."""
1880        return list(self._inner.diagnostics)

The diagnostics stored on this module, in encounter order.

extension_keys: List[str]
1882    @property
1883    def extension_keys(self) -> list[str]:
1884        """The namespaces of the extensions this module carries, sorted."""
1885        return list(self._inner._extension_keys)

The namespaces of the extensions this module carries, sorted.

def extension(self, namespace: str) -> Any:
1887    def extension(self, namespace: str) -> Any:
1888        """The JSON value stored under ``namespace``, or ``None``.
1889
1890        Only that value is decoded; the module is not serialized.
1891        """
1892        text = self._inner._extension_json(namespace)
1893        return None if text is None else _json.loads(text)

The JSON value stored under namespace, or None.

Only that value is decoded; the module is not serialized.

def with_extension(self, namespace: str, value: Any) -> PioModule[~_T]:
1895    def with_extension(self, namespace: str, value: Any) -> "PioModule":
1896        """A copy of this module carrying ``value`` under ``namespace``.
1897
1898        ``value`` must be JSON serializable. The copy keeps the typed value,
1899        diagnostics, sources, and history without serializing them; an
1900        extension already stored under ``namespace`` is replaced. The original
1901        module is unchanged.
1902        """
1903        return PioModule(self._inner._with_extension_json(namespace, _json.dumps(value)))

A copy of this module carrying value under namespace.

value must be JSON serializable. The copy keeps the typed value, diagnostics, sources, and history without serializing them; an extension already stored under namespace is replaced. The original module is unchanged.

def to_balanced_report(self, base_mva: float = Ellipsis) -> Any:
1905    def to_balanced_report(self, base_mva: float = 100.0) -> Any:
1906        """Report whether a multiconductor network can become balanced."""
1907        return _json.loads(self._inner.lowering_readiness_json(base_mva))

Report whether a multiconductor network can become balanced.

def to_balanced( self, base_mva: float = Ellipsis) -> PioModule[BalancedNetwork]:
1909    def to_balanced(self, base_mva: float = 100.0) -> "PioModule":
1910        """Transform a multiconductor network to a balanced module."""
1911        return PioModule(self._inner.lower_to_balanced(base_mva))

Transform a multiconductor network to a balanced module.

def to_dc_pf_instance(self) -> PioModule[DcPfInstance]:
1913    def to_dc_pf_instance(self) -> "PioModule":
1914        """Build a DC power flow instance from a balanced network module."""
1915        return PioModule(self._inner._to_dc_pf_instance())

Build a DC power flow instance from a balanced network module.

def to_ac_pf_instance(self) -> PioModule[AcPfInstance]:
1917    def to_ac_pf_instance(self) -> "PioModule":
1918        """Build an AC power flow instance from a balanced network module."""
1919        return PioModule(self._inner._to_ac_pf_instance())

Build an AC power flow instance from a balanced network module.

def to_dc_opf_instance(self) -> PioModule[DcOpfInstance]:
1921    def to_dc_opf_instance(self) -> "PioModule":
1922        """Build a DC optimal power flow instance from a balanced network module."""
1923        return PioModule(self._inner._to_dc_opf_instance())

Build a DC optimal power flow instance from a balanced network module.

def to_ac_opf_instance(self) -> PioModule[AcOpfInstance]:
1925    def to_ac_opf_instance(self) -> "PioModule":
1926        """Build an AC optimal power flow instance from a balanced network module."""
1927        return PioModule(self._inner._to_ac_opf_instance())

Build an AC optimal power flow instance from a balanced network module.

def to_ac_ots_instance( self, *, switchable: Union[Literal['all', 'none'], Sequence[str], NoneType] = Ellipsis, switching_costs: Optional[Mapping[str, Tuple[float, float]]] = Ellipsis, islanding: Optional[Literal['forbidden', 'allowed']] = Ellipsis, max_open: Optional[int] = Ellipsis, max_switched: Optional[int] = Ellipsis, current_limits: Optional[Literal['skip', 'stated', 'derive_from_rate_a']] = Ellipsis, stated_current_limits: Optional[Mapping[str, Tuple[Optional[float], Optional[float]]]] = Ellipsis) -> PioModule[AcOtsInstance]:
1929    def to_ac_ots_instance(
1930        self,
1931        *,
1932        switchable: Union[str, Sequence[str], None] = None,
1933        switching_costs: Optional[Mapping[str, tuple[float, float]]] = None,
1934        islanding: Optional[str] = None,
1935        max_open: Optional[int] = None,
1936        max_switched: Optional[int] = None,
1937        current_limits: Optional[str] = None,
1938        stated_current_limits: Optional[
1939            Mapping[str, tuple[Optional[float], Optional[float]]]
1940        ] = None,
1941    ) -> "PioModule":
1942        """Build an AC optimal transmission switching instance from a balanced
1943        network, AC optimal power flow, or AC optimal transmission switching
1944        module.
1945
1946        With no option, this gives the default instance: every initially
1947        in-service branch may switch, at zero cost, islanding is forbidden,
1948        there is no budget and no current limit, and the objective gains the
1949        switching cost term. An AC optimal transmission switching module comes
1950        back unchanged.
1951
1952        Any option makes the options explicit, as the C ABI's options struct
1953        and PowerIO.jl's ``AcOtsOptions`` do, and an option not given takes
1954        its explicit default:
1955
1956        - ``switchable``: ``"all"`` (the default, which includes initially
1957          open branches), ``"none"``, or a list of branch identities.
1958        - ``switching_costs``: ``{branch_id: (open_cost, close_cost)}``; a
1959          branch with no entry switches at zero cost.
1960        - ``islanding``: ``"forbidden"`` (the default) or ``"allowed"``.
1961        - ``max_open``: the most branches open in the final topology,
1962          counting fixed open rows; ``None`` is no budget.
1963        - ``max_switched``: the most status changes; ``None`` is no budget.
1964        - ``current_limits``: ``"skip"`` (the default), ``"stated"``, or
1965          ``"derive_from_rate_a"``.
1966        - ``stated_current_limits``: ``{branch_id: (from_pu, to_pu)}``, per
1967          unit; ``None`` on a side is unbounded.
1968
1969        The base problem and objective are kept, and the objective gains the
1970        switching cost term once. Refused options raise
1971        :class:`PowerIOError` with code
1972        ``BUILD.INSTANCE.SWITCHING_OPTIONS_INVALID``; an unknown policy name
1973        raises :class:`ValueError`.
1974        """
1975        if (
1976            switchable is None
1977            and switching_costs is None
1978            and islanding is None
1979            and max_open is None
1980            and max_switched is None
1981            and current_limits is None
1982            and stated_current_limits is None
1983        ):
1984            return PioModule(self._inner._to_ac_ots_instance())
1985        if switchable is None:
1986            selection, identities = "all", []
1987        elif isinstance(switchable, str):
1988            selection, identities = switchable, []
1989        else:
1990            selection, identities = "only", [str(identity) for identity in switchable]
1991        for name, budget in (("max_open", max_open), ("max_switched", max_switched)):
1992            if budget is not None and (
1993                isinstance(budget, bool) or not isinstance(budget, int) or budget < 0
1994            ):
1995                raise ValueError(f"{name} must be a nonnegative integer or None")
1996        costs = [
1997            (str(identity), float(open_cost), float(close_cost))
1998            for identity, (open_cost, close_cost) in (switching_costs or {}).items()
1999        ]
2000        limits = [
2001            (
2002                str(identity),
2003                None if from_pu is None else float(from_pu),
2004                None if to_pu is None else float(to_pu),
2005            )
2006            for identity, (from_pu, to_pu) in (stated_current_limits or {}).items()
2007        ]
2008        return PioModule(
2009            self._inner._to_ac_ots_instance_with_options(
2010                selection,
2011                identities,
2012                costs,
2013                "forbidden" if islanding is None else islanding,
2014                max_open,
2015                max_switched,
2016                "skip" if current_limits is None else current_limits,
2017                limits,
2018            )
2019        )

Build an AC optimal transmission switching instance from a balanced network, AC optimal power flow, or AC optimal transmission switching module.

With no option, this gives the default instance: every initially in-service branch may switch, at zero cost, islanding is forbidden, there is no budget and no current limit, and the objective gains the switching cost term. An AC optimal transmission switching module comes back unchanged.

Any option makes the options explicit, as the C ABI's options struct and PowerIO.jl's AcOtsOptions do, and an option not given takes its explicit default:

  • switchable: "all" (the default, which includes initially open branches), "none", or a list of branch identities.
  • switching_costs: {branch_id: (open_cost, close_cost)}; a branch with no entry switches at zero cost.
  • islanding: "forbidden" (the default) or "allowed".
  • max_open: the most branches open in the final topology, counting fixed open rows; None is no budget.
  • max_switched: the most status changes; None is no budget.
  • current_limits: "skip" (the default), "stated", or "derive_from_rate_a".
  • stated_current_limits: {branch_id: (from_pu, to_pu)}, per unit; None on a side is unbounded.

The base problem and objective are kept, and the objective gains the switching cost term once. Refused options raise PowerIOError with code BUILD.INSTANCE.SWITCHING_OPTIONS_INVALID; an unknown policy name raises ValueError.

def to_mc_ac_pf_instance(self) -> PioModule[McAcPfInstance]:
2021    def to_mc_ac_pf_instance(self) -> "PioModule":
2022        """Build a multiconductor AC power flow instance from a network module."""
2023        return PioModule(self._inner._to_mc_ac_pf_instance())

Build a multiconductor AC power flow instance from a network module.

def to_mc_ac_opf_instance(self) -> PioModule[McAcOpfInstance]:
2025    def to_mc_ac_opf_instance(self) -> "PioModule":
2026        """Build a multiconductor AC optimal power flow instance from a network module."""
2027        return PioModule(self._inner._to_mc_ac_opf_instance())

Build a multiconductor AC optimal power flow instance from a network module.

def to_lindist3flow_opf_instance(self) -> PioModule[LinDist3FlowOpfInstance]:
2029    def to_lindist3flow_opf_instance(self) -> "PioModule":
2030        """Build a LinDist3Flow optimal power flow instance from a network module."""
2031        return PioModule(self._inner._to_lindist3flow_opf_instance())

Build a LinDist3Flow optimal power flow instance from a network module.

def to_lindist3flow_pf_instance(self) -> PioModule[LinDist3FlowPfInstance]:
2033    def to_lindist3flow_pf_instance(self) -> "PioModule":
2034        """Build a fixed-dispatch LinDist3Flow instance from a network module."""
2035        return PioModule(self._inner._to_lindist3flow_pf_instance())

Build a fixed-dispatch LinDist3Flow instance from a network module.

class PowerIODataError(PowerIOError):

A well-formed case cannot satisfy a requested operation.

Core errors carry typed Diagnostic records. Refused conversion passes retain dictionary findings with code, severity, message, and target.

class PowerIOError(builtins.ValueError):

Base error from parsing, emission, or matrix calculations.

Rust core failures carry a diagnostic code and typed Diagnostic records. Refused conversion passes retain their existing dictionary findings. These attributes are populated when the exception is raised.

class PowerIOParseError(PowerIOError):

A case file is malformed or unparseable.

class ReactivePower:
def vars(value):
def megavars(value):
value
unit
class Residuals:
max_active_power_mismatch
max_reactive_power_mismatch
@dataclass(frozen=True)
class Scenario:
1210@dataclass(frozen=True)
1211class Scenario:
1212    id: str
1213    probability: Optional[float] = None
Scenario(id: str, probability: Optional[float] = Ellipsis)
id: str
probability: Optional[float] = None
class ScenarioSet(_TypedValue, collections.abc.Mapping):
1298@_guard_class
1299class ScenarioSet(_TypedValue, Mapping):
1300    """Named alternatives of one type, with optional probabilities."""
1301
1302    def __init__(
1303        self,
1304        values: Mapping[str, Any],
1305        *,
1306        probabilities: Optional[Mapping[str, float]] = None,
1307    ) -> None:
1308        if not isinstance(values, Mapping):
1309            raise TypeError("ScenarioSet values must be a mapping from IDs to values")
1310        if probabilities is not None and not isinstance(probabilities, Mapping):
1311            raise TypeError("probabilities must be a mapping from scenario IDs to numbers")
1312        ids = list(values)
1313        modules = [PioModule.from_value(values[id])._inner for id in ids]
1314        inner = _powerio._PioModule._from_scenario_set(
1315            modules,
1316            ids,
1317            None if probabilities is None else dict(probabilities),
1318        )
1319        super().__init__(PioModule(inner))
1320
1321    @classmethod
1322    def _from_module(cls, module: "PioModule") -> "ScenarioSet":
1323        value = object.__new__(cls)
1324        _TypedValue.__init__(value, module)
1325        return value
1326
1327    @property
1328    def scenarios(self) -> tuple[Scenario, ...]:
1329        return tuple(Scenario(*entry) for entry in self.module._inner._scenario_entries())
1330
1331    def __len__(self) -> int:
1332        return len(self.scenarios)
1333
1334    def __iter__(self):
1335        return (scenario.id for scenario in self.scenarios)
1336
1337    def __contains__(self, scenario: object) -> bool:
1338        return isinstance(scenario, str) and any(
1339            entry.id == scenario for entry in self.scenarios
1340        )
1341
1342    def __getitem__(self, scenario: str) -> Any:
1343        if not isinstance(scenario, str):
1344            raise TypeError("scenario keys must be strings")
1345        if scenario not in self:
1346            raise KeyError(scenario)
1347        current = self._collection_entry or _CollectionEntry(self.module)
1348        if current.scenario_id is not None:
1349            raise TypeError("nested ScenarioSet values are not supported")
1350        value = PioModule(self.module._inner._scenario_get(scenario)).value
1351        return _bind_collection_entry(
1352            value,
1353            _CollectionEntry(
1354                root=current.root,
1355                time_index=current.time_index,
1356                scenario_id=scenario,
1357            ),
1358        )

A Mapping is a generic container for associating key/value pairs.

This class provides concrete generic implementations of all methods except for __getitem__, __iter__, and __len__.

ScenarioSet(module: PioModule[typing.Any])
1302    def __init__(
1303        self,
1304        values: Mapping[str, Any],
1305        *,
1306        probabilities: Optional[Mapping[str, float]] = None,
1307    ) -> None:
1308        if not isinstance(values, Mapping):
1309            raise TypeError("ScenarioSet values must be a mapping from IDs to values")
1310        if probabilities is not None and not isinstance(probabilities, Mapping):
1311            raise TypeError("probabilities must be a mapping from scenario IDs to numbers")
1312        ids = list(values)
1313        modules = [PioModule.from_value(values[id])._inner for id in ids]
1314        inner = _powerio._PioModule._from_scenario_set(
1315            modules,
1316            ids,
1317            None if probabilities is None else dict(probabilities),
1318        )
1319        super().__init__(PioModule(inner))
scenarios: Tuple[Scenario, ...]
1327    @property
1328    def scenarios(self) -> tuple[Scenario, ...]:
1329        return tuple(Scenario(*entry) for entry in self.module._inner._scenario_entries())
Inherited Members
_TypedValue
module
class ScucActiveReserveZone:
buses
ramping_up_requirement
ramping_down_requirement
id
regulation_up_violation_cost
regulation_up_requirement_fraction
nonsynchronized_requirement_fraction
synchronized_requirement_fraction
synchronized_violation_cost
ramping_up_violation_cost
ramping_down_violation_cost
regulation_down_violation_cost
nonsynchronized_violation_cost
regulation_down_requirement_fraction
class ScucBranchSwitchingCost:
id
connection_cost
disconnection_cost
class ScucContingency:
components
id
class ScucDevice:
reserve_limits
on_cost
shutdown_cost
ramp_limits
kind
startup_cost
initial_commitment
reactive_capability
startup_cost_adjustments
periods
energy_lower_bounds
energy_upper_bounds
minimum_up_time
minimum_down_time
id
initial_on_status
startup_limits
class ScucDeviceOutputs:
q_res_up
p_on
p_syn_res
p_ramp_res_up_offline
p_ramp_res_down_offline
p_ramp_res_up_online
q_res_down
q
p_ramp_res_down_online
p_reg_res_up
p_reg_res_down
p_nsyn_res
on_status
startup_status
shutdown_status
class ScucDevicePeriod:
on_status_min
energy_cost_blocks
active_power_min
reactive_power_max
reserve_costs
active_power_max
on_status_max
reactive_power_min
class ScucEnergyCostBlock:
marginal_cost
block_size
class ScucEnergyRequirement:
end_time
energy
start_time
class ScucInitialCommitment:
accumulated_down_time
accumulated_up_time
class ScucInputs:
branch_switching_costs
reactive_reserve_zones
shunts
contingencies
violation_costs
interval_durations
devices
transformer_controls
active_reserve_zones
class ScucNetworkOutputs:
bus_va
ac_line_on_status
transformer_on_status
shunt_step
dc_line_pdc_fr
dc_line_qdc_fr
dc_line_qdc_to
transformer_ta
transformer_tm
bus_vm
class ScucRampLimits:
down
shutdown
startup
up
class ScucReactiveCapability:
slope
slope_min
slope_max
reactive_power_at_zero_active_power_max
kind
reactive_power_at_zero_active_power_min
reactive_power_at_zero_active_power
class ScucReactiveReserveZone:
reactive_down_requirement
buses
reactive_up_violation_cost
reactive_down_violation_cost
id
reactive_up_requirement
class ScucReserveCosts:
ramping_down_online
synchronized
ramping_down_offline
reactive_down
reactive_up
nonsynchronized
regulation_up
regulation_down
ramping_up_offline
ramping_up_online
class ScucReserveLimits:
regulation_down
ramping_down_offline
regulation_up
ramping_up_online
ramping_down_online
ramping_up_offline
nonsynchronized
synchronized
class ScucShunt:
id
susceptance_per_step
step_min
conductance_per_step
step_max
initial_step
class ScucStartupCostAdjustment:
maximum_down_time
cost
class ScucStartupLimit:
start_time
maximum_startups
end_time
class ScucTransformerControl:
id
tap_ratio_min
tap_ratio_max
phase_shift_max
phase_shift_min
class ScucViolationCosts:
active_power_balance
energy_requirement
branch_thermal_limit
reactive_power_balance
@dataclass(frozen=True)
class SincalBalancedReadOptions:
16@dataclass(frozen=True)
17class SincalBalancedReadOptions:
18    """Native variant, daily snapshot and optional verified Access companion.
19
20    Use with ``parse(..., format="sincal-balanced", sincal_balanced=...)``.
21    Parsing never invokes an acquisition tool. The primary source remains the MDB.
22    """
23    variant: Optional[int] = None
24    snapshot_hours: Optional[float] = None
25    acquired_tables: Optional[str] = None
26
27    def __post_init__(self):
28        _validate_selection(self)

Native variant, daily snapshot and optional verified Access companion.

Use with parse(..., format="sincal-balanced", sincal_balanced=...). Parsing never invokes an acquisition tool. The primary source remains the MDB.

SincalBalancedReadOptions( variant: Optional[int] = None, snapshot_hours: Optional[float] = None, acquired_tables: Optional[str] = None)
variant: Optional[int] = None
snapshot_hours: Optional[float] = None
acquired_tables: Optional[str] = None
class SocwrOpfSolution(_BalancedCalculation, _CalculationSolution):
1617class SocwrOpfSolution(_BalancedCalculation, _CalculationSolution):
1618    """A PowerModels SOCWR relaxation solution and objective lower bound."""

A PowerModels SOCWR relaxation solution and objective lower bound.

class SourceSpan:

One source byte range a diagnostic points at: the Python mirror of powerio_core::SourceSpan. source is the source ID string, not the bytes themselves; a caller resolves it against the owning module's sources.

source
byte_end
byte_start
class SubsystemSet(_TypedValue):
1753@_guard_class
1754class SubsystemSet(_TypedValue):
1755    """A PSS/E subsystem description file: the named bus groups a contingency
1756    run and a monitored element file draw on.
1757
1758    :func:`parse` returns it for a ``.sub`` file or for text declared as
1759    ``psse-sub``, and ``network.select_subsystem_buses(groups.text, name)``
1760    names the buses one subsystem selects.
1761    """
1762
1763    @property
1764    def text(self) -> str:
1765        """The ``.sub`` text for this set."""
1766        return _emitted_text(self.module, "psse-sub")

A PSS/E subsystem description file: the named bus groups a contingency run and a monitored element file draw on.

parse() returns it for a .sub file or for text declared as psse-sub, and network.select_subsystem_buses(groups.text, name) names the buses one subsystem selects.

text: str
1763    @property
1764    def text(self) -> str:
1765        """The ``.sub`` text for this set."""
1766        return _emitted_text(self.module, "psse-sub")

The .sub text for this set.

Inherited Members
_TypedValue
_TypedValue
module
@dataclass(frozen=True)
class TimePoint:
1204@dataclass(frozen=True)
1205class TimePoint:
1206    label: str
1207    duration_seconds: Optional[float] = None
TimePoint(label: str, duration_seconds: Optional[float] = Ellipsis)
label: str
duration_seconds: Optional[float] = None
class TimeSeries(_TypedValue, collections.abc.Sequence):
1231@_guard_class
1232class TimeSeries(_TypedValue, Sequence):
1233    """Values of one type ordered in time."""
1234
1235    def __init__(
1236        self,
1237        values: Sequence[Any],
1238        *,
1239        time_points: Sequence[TimePoint],
1240    ) -> None:
1241        if isinstance(values, (str, bytes, bytearray)) or not isinstance(
1242            values, Sequence
1243        ):
1244            raise TypeError("TimeSeries values must be a sequence of PowerIO values")
1245        if not isinstance(time_points, Sequence):
1246            raise TypeError("time_points must be a sequence of TimePoint values")
1247        points = tuple(time_points)
1248        if not all(isinstance(point, TimePoint) for point in points):
1249            raise TypeError("time_points must contain only TimePoint values")
1250        modules = [PioModule.from_value(value)._inner for value in values]
1251        inner = _powerio._PioModule._from_time_series(
1252            modules,
1253            [(point.label, point.duration_seconds) for point in points],
1254        )
1255        super().__init__(PioModule(inner))
1256
1257    @classmethod
1258    def _from_module(cls, module: "PioModule") -> "TimeSeries":
1259        value = object.__new__(cls)
1260        _TypedValue.__init__(value, module)
1261        return value
1262
1263    @property
1264    def time_points(self) -> tuple[TimePoint, ...]:
1265        return tuple(TimePoint(*point) for point in self.module._inner._time_series_points())
1266
1267    def __len__(self) -> int:
1268        return self.module._inner._time_series_len()
1269
1270    def __getitem__(self, index):
1271        if isinstance(index, slice):
1272            return [self[position] for position in range(*index.indices(len(self)))]
1273        try:
1274            position = _operator.index(index)
1275        except TypeError:
1276            raise TypeError("time series indices must be integers") from None
1277        if position < 0:
1278            position += len(self)
1279        if position < 0 or position >= len(self):
1280            raise IndexError("time series index out of range")
1281        current = self._collection_entry or _CollectionEntry(self.module)
1282        if current.time_index is not None:
1283            raise TypeError("nested TimeSeries values are not supported")
1284        value = PioModule(self.module._inner._time_series_get(position)).value
1285        return _bind_collection_entry(
1286            value,
1287            _CollectionEntry(
1288                root=current.root,
1289                time_index=position,
1290                scenario_id=current.scenario_id,
1291            ),
1292        )
1293
1294    def __iter__(self):
1295        return (self[position] for position in range(len(self)))

All the operations on a read-only sequence.

Concrete subclasses must override __new__ or __init__, __getitem__, and __len__.

TimeSeries(module: PioModule[typing.Any])
1235    def __init__(
1236        self,
1237        values: Sequence[Any],
1238        *,
1239        time_points: Sequence[TimePoint],
1240    ) -> None:
1241        if isinstance(values, (str, bytes, bytearray)) or not isinstance(
1242            values, Sequence
1243        ):
1244            raise TypeError("TimeSeries values must be a sequence of PowerIO values")
1245        if not isinstance(time_points, Sequence):
1246            raise TypeError("time_points must be a sequence of TimePoint values")
1247        points = tuple(time_points)
1248        if not all(isinstance(point, TimePoint) for point in points):
1249            raise TypeError("time_points must contain only TimePoint values")
1250        modules = [PioModule.from_value(value)._inner for value in values]
1251        inner = _powerio._PioModule._from_time_series(
1252            modules,
1253            [(point.label, point.duration_seconds) for point in points],
1254        )
1255        super().__init__(PioModule(inner))
time_points: Tuple[TimePoint, ...]
1263    @property
1264    def time_points(self) -> tuple[TimePoint, ...]:
1265        return tuple(TimePoint(*point) for point in self.module._inner._time_series_points())
Inherited Members
_TypedValue
module
class UpdateChange:
component_id
field
terminal
class UpdateReport:
connectivity_changed
changes
__version__: str = '0.12.0'
def apply_bus_load_active_power( module: PioModule[typing.Any], bus_id: int, total: ActivePower, *, allocation: Literal['equal', 'proportional_to_current_active_power'] = Ellipsis) -> UpdateReport:
2112@_guard
2113def apply_bus_load_active_power(
2114    module: PioModule,
2115    bus_id: int,
2116    total: ActivePower,
2117    *,
2118    allocation: str = "proportional_to_current_active_power",
2119) -> UpdateReport:
2120    """Replace aggregate bus demand through an explicit PowerIO allocation rule.
2121
2122    ``"proportional_to_current_active_power"`` preserves each participating
2123    load's current share. ``"equal"`` gives every participating load the same
2124    share, including when their current aggregate demand is zero. PowerIO
2125    requires stable load IDs and reports each load changed.
2126    """
2127    if not isinstance(module, PioModule):
2128        raise TypeError("module must be a PioModule")
2129    if not isinstance(total, ActivePower):
2130        raise TypeError("total must be an ActivePower")
2131    return module._inner._apply_bus_load_active_power(
2132        bus_id,
2133        total,
2134        allocation=allocation,
2135    )

Replace aggregate bus demand through an explicit PowerIO allocation rule.

"proportional_to_current_active_power" preserves each participating load's current share. "equal" gives every participating load the same share, including when their current aggregate demand is zero. PowerIO requires stable load IDs and reports each load changed.

def apply_updates( target: Union[PioModule[Any], BalancedNetwork, MulticonductorNetwork, powerio._TypedValue], updates: Union[Iterable[OperatingPointUpdate], Iterable[NetworkUpdate], Iterable[CalculationUpdate]]) -> UpdateReport:
2078@_guard
2079def apply_updates(
2080    target: Any,
2081    updates: Union[
2082        Iterable[OperatingPointUpdate],
2083        Iterable[NetworkUpdate],
2084        Iterable[CalculationUpdate],
2085    ],
2086) -> UpdateReport:
2087    """Validate and apply one batch of typed updates atomically.
2088
2089    ``updates`` contains one update class: :class:`OperatingPointUpdate`,
2090    :class:`NetworkUpdate`, or :class:`CalculationUpdate`. Values are absolute
2091    replacements and power quantities carry their units in the typed value.
2092    ``target`` is a module or a value obtained by indexing a :class:`TimeSeries`
2093    or :class:`ScenarioSet`. If validation fails, the module is unchanged.
2094    """
2095    batch = list(updates)
2096    if isinstance(target, PioModule):
2097        return target._inner._apply_updates(batch)
2098    location = getattr(target, "_collection_entry", None)
2099    if not isinstance(location, _CollectionEntry):
2100        raise TypeError(
2101            "target must be a PioModule or a TimeSeries/ScenarioSet entry"
2102        )
2103    report = location.root._inner._apply_collection_updates(
2104        batch,
2105        time_index=location.time_index,
2106        scenario_id=location.scenario_id,
2107    )
2108    _refresh_collection_entry(target, location)
2109    return report

Validate and apply one batch of typed updates atomically.

updates contains one update class: OperatingPointUpdate, NetworkUpdate, or CalculationUpdate. Values are absolute replacements and power quantities carry their units in the typed value. target is a module or a value obtained by indexing a TimeSeries or ScenarioSet. If validation fails, the module is unchanged.

def deserialize(source: Any) -> PioModule[typing.Any]:
2319@_guard
2320def deserialize(source: Any) -> PioModule:
2321    """Deserialize PowerIO IR from a path, file object, or bytes-like source."""
2322    path = _path_from_source(source)
2323    if path is not None:
2324        return PioModule(_powerio._PioModule._deserialize_path(path))
2325    data, _ = _memory_from_source(source, None)
2326    return PioModule(_powerio._PioModule._deserialize_memory(data))

Deserialize PowerIO IR from a path, file object, or bytes-like source.

def diagnostic_record(diagnostic: Diagnostic) -> Dict[str, Any]:
2346@_guard
2347def diagnostic_record(diagnostic: Diagnostic) -> dict[str, Any]:
2348    """One diagnostic as a JSON-ready dictionary.
2349
2350    ``code``, ``severity``, ``message``, and ``target`` are always present, in
2351    that order. ``id``, ``suggested_action``, and ``related`` follow when the
2352    diagnostic sets them, ``details`` when it is not ``None``, and ``spans``
2353    as ``source``, ``byte_start``, ``byte_end`` dictionaries when the
2354    diagnostic carries at least one span.
2355    """
2356    record: dict[str, Any] = {
2357        "code": diagnostic.code,
2358        "severity": diagnostic.severity,
2359        "message": diagnostic.message,
2360        "target": diagnostic.target,
2361    }
2362    if diagnostic.id:
2363        record["id"] = diagnostic.id
2364    if diagnostic.suggested_action:
2365        record["suggested_action"] = diagnostic.suggested_action
2366    if diagnostic.related:
2367        record["related"] = list(diagnostic.related)
2368    if diagnostic.details is not None:
2369        record["details"] = diagnostic.details
2370    if diagnostic.spans:
2371        record["spans"] = [
2372            {
2373                "source": span.source,
2374                "byte_start": span.byte_start,
2375                "byte_end": span.byte_end,
2376            }
2377            for span in diagnostic.spans
2378        ]
2379    return record

One diagnostic as a JSON-ready dictionary.

code, severity, message, and target are always present, in that order. id, suggested_action, and related follow when the diagnostic sets them, details when it is not None, and spans as source, byte_start, byte_end dictionaries when the diagnostic carries at least one span.

def diagnostic_records( diagnostics: Iterable[Diagnostic]) -> List[Dict[str, Any]]:
2382@_guard
2383def diagnostic_records(diagnostics: Iterable[Diagnostic]) -> list[dict[str, Any]]:
2384    """Every diagnostic as a JSON-ready dictionary, in the order given."""
2385    return [diagnostic_record(item) for item in diagnostics]

Every diagnostic as a JSON-ready dictionary, in the order given.

def emit( module: PioModule[typing.Any], format: str, destination: Optional[Any] = Ellipsis) -> EmitResult:
2289@_guard
2290def emit(module: PioModule, format: str, destination: Optional[Any] = None) -> EmitResult:
2291    """Emit a module as one grid exchange format."""
2292    from . import _sienna_files
2293    if format is not None and format in _sienna_files.FORMATS:
2294        return _sienna_files.emit(module, format, destination)
2295    from . import _pypsa_files
2296    if format in _pypsa_files.FORMATS:
2297        if not isinstance(module, PioModule):
2298            raise TypeError("module must be a PioModule")
2299        return _pypsa_files.emit(module, format, destination)
2300    return _emit_to_destination(
2301        module,
2302        destination,
2303        lambda: module._inner._emit_memory(format),
2304        lambda path: module._inner._emit_path(format, path),
2305    )

Emit a module as one grid exchange format.

def features() -> Dict[str, bool]:
2329@_guard
2330def features() -> dict[str, bool]:
2331    """The build-time features compiled into this powerio installation.
2332
2333    ``matrix``, ``dist``, and ``prob`` are unconditional dependencies of the
2334    extension and are always ``True``. ``gridfm`` reports whether GridFM
2335    Parquet parsing and emission were compiled in; the published wheel
2336    includes them, while a custom source build can omit them.
2337    """
2338    return {
2339        "matrix": True,
2340        "gridfm": bool(getattr(_powerio, "_has_gridfm", False)),
2341        "dist": True,
2342        "prob": True,
2343    }

The build-time features compiled into this powerio installation.

matrix, dist, and prob are unconditional dependencies of the extension and are always True. gridfm reports whether GridFM Parquet parsing and emission were compiled in; the published wheel includes them, while a custom source build can omit them.

def from_ppc(ppc: Dict[str, Any]) -> BalancedNetwork:
1151@_guard
1152def from_ppc(ppc) -> BalancedNetwork:
1153    """Case from a PYPOWER dict (``ppc``); the inverse of :meth:`BalancedNetwork.to_ppc`.
1154
1155    The tables route through the MATPOWER reader, so the semantics match a
1156    ``.m`` case exactly: bus ``PD``/``QD`` become loads, ``GS``/``BS`` become
1157    shunts, and ``gencost`` is read when present. Result columns past the
1158    MATPOWER input widths are dropped. A 10 column ``gen`` table (the layout
1159    without the OPF capability columns) passes through at its own width, so
1160    the generators come back with no capability limits rather than eleven
1161    zero ones. Raises :class:`ValueError` when a required table is absent,
1162    when a ``bus`` or ``branch`` row is below its 13 column width, when a row
1163    is not a sequence of numbers, or when a cell is not numeric; the message
1164    names the table and the row.
1165    """
1166    value = parse(
1167        _io.StringIO(_ppc_to_matpower_text(ppc)),
1168        format="matpower",
1169        name="from_ppc.m",
1170    ).value
1171    assert isinstance(value, BalancedNetwork)
1172    return value

Case from a PYPOWER dict (ppc); the inverse of BalancedNetwork.to_ppc().

The tables route through the MATPOWER reader, so the semantics match a .m case exactly: bus PD/QD become loads, GS/BS become shunts, and gencost is read when present. Result columns past the MATPOWER input widths are dropped. A 10 column gen table (the layout without the OPF capability columns) passes through at its own width, so the generators come back with no capability limits rather than eleven zero ones. Raises ValueError when a required table is absent, when a bus or branch row is below its 13 column width, when a row is not a sequence of numbers, or when a cell is not numeric; the message names the table and the row.

def parse( source: Any, *, format: Optional[str] = Ellipsis, name: Optional[str] = Ellipsis, sincal_multiconductor: Optional[powerio.dist.SincalReadOptions] = Ellipsis, sincal_balanced: Optional[SincalBalancedReadOptions] = Ellipsis, acquisition_root: Optional[Any] = Ellipsis, named_buffers: Optional[Mapping[str, bytes]] = Ellipsis) -> PioModule[typing.Any]:
2180@_guard
2181def parse(
2182    source: Any,
2183    *,
2184    format: Optional[str] = None,
2185    name: Optional[str] = None,
2186    sincal_multiconductor: Optional[dist.SincalReadOptions] = None,
2187    sincal_balanced: Optional[SincalBalancedReadOptions] = None,
2188    acquisition_root: Optional[Any] = None,
2189    named_buffers: Optional[Mapping[str, bytes]] = None,
2190) -> PioModule:
2191    """Parse a path, file object, or bytes-like source.
2192
2193    A string is always a path. Pass raw text through ``io.StringIO`` or
2194    another file object. ``sincal_multiconductor`` requires explicit format
2195    ``sincal-multiconductor``; ``sincal_balanced`` requires ``sincal-balanced``.
2196    File companions stay beneath the file's parent,
2197    or an explicitly selected ``acquisition_root``. Memory sources use only
2198    ``named_buffers`` and never acquire companions from the filesystem.
2199    """
2200    from . import _sienna_files
2201    if format is not None and format in _sienna_files.FORMATS:
2202        if sincal_balanced is not None or sincal_multiconductor is not None:
2203            raise ValueError("SINCAL options do not apply to Sienna bundles")
2204        return _sienna_files.parse(source, format, name=name, acquisition_root=acquisition_root, named_buffers=named_buffers)
2205    from . import _pypsa_files
2206    binary_format = _pypsa_files.detect(source, format)
2207    if binary_format is not None:
2208        if named_buffers is not None or acquisition_root is not None or sincal_balanced is not None or sincal_multiconductor is not None:
2209            raise ValueError("PyPSA binary containers are standalone sources")
2210        if name is not None and _path_from_source(source) is not None:
2211            raise ValueError("name is only valid for memory and file object sources")
2212        return _pypsa_files.parse(source, binary_format, name=name)
2213    balanced_selection, selection = _native_selections(sincal_balanced, sincal_multiconductor)
2214    path = _path_from_source(source)
2215    if path is not None:
2216        if name is not None:
2217            raise ValueError("name is only valid for memory and file object sources")
2218        if named_buffers is not None:
2219            raise ValueError("named_buffers applies only to memory and file object sources")
2220        root = _path_from_source(acquisition_root) if acquisition_root is not None else None
2221        if acquisition_root is not None and root is None:
2222            raise TypeError("acquisition_root must be a path")
2223        return PioModule(_powerio._PioModule._parse_path(path, format, selection, root, balanced_selection))
2224    if acquisition_root is not None:
2225        raise ValueError("acquisition_root applies only to path sources")
2226    buffers = None
2227    if named_buffers is not None:
2228        if not isinstance(named_buffers, Mapping):
2229            raise TypeError("named_buffers must map relative names to bytes-like data")
2230        buffers = []
2231        for buffer_name, buffer_data in named_buffers.items():
2232            if not isinstance(buffer_name, str) or not isinstance(buffer_data, (bytes, bytearray, memoryview)):
2233                raise TypeError("named_buffers must map relative names to bytes-like data")
2234            buffers.append((buffer_name, bytes(buffer_data)))
2235    data, source_name = _memory_from_source(source, name)
2236    return PioModule(_powerio._PioModule._parse_memory(data, source_name, format, selection, buffers, balanced_selection))

Parse a path, file object, or bytes-like source.

A string is always a path. Pass raw text through io.StringIO or another file object. sincal_multiconductor requires explicit format sincal-multiconductor; sincal_balanced requires sincal-balanced. File companions stay beneath the file's parent, or an explicitly selected acquisition_root. Memory sources use only named_buffers and never acquire companions from the filesystem.

def parse_geo(text: str, name_hint: Optional[str] = Ellipsis) -> Dict[str, Any]:
1052@_guard
1053def parse_geo(text: str, name_hint: Optional[str] = None) -> dict[str, Any]:
1054    """Tolerantly read a geographic sidecar and return its canonical form.
1055
1056    Accepts headerless buscoords CSV, aliased CSV/JSON records, and GeoJSON
1057    Point/LineString features. Returns ``{"geojson": <FeatureCollection dict>,
1058    "diagnostics": [...]}``; ``name_hint`` (a file name) picks CSV against JSON
1059    when the content alone is ambiguous. Input with no usable coordinates
1060    raises :class:`PowerIOParseError`.
1061    """
1062    parsed = _powerio.parse_geo(text, name_hint)
1063    parsed["geojson"] = _json.loads(parsed["geojson"])
1064    return parsed

Tolerantly read a geographic sidecar and return its canonical form.

Accepts headerless buscoords CSV, aliased CSV/JSON records, and GeoJSON Point/LineString features. Returns {"geojson": <FeatureCollection dict>, "diagnostics": [...]}; name_hint (a file name) picks CSV against JSON when the content alone is ambiguous. Input with no usable coordinates raises PowerIOParseError.

def resolve_format(name: str) -> Optional[FormatInfo]:
1045@_guard
1046def resolve_format(name: str) -> Optional[FormatInfo]:
1047    """Resolve a format token or common alias to its canonical metadata."""
1048    resolved = _powerio.resolve_format(name)
1049    return None if resolved is None else FormatInfo(*resolved)

Resolve a format token or common alias to its canonical metadata.

def serialize( module: PioModule[typing.Any], destination: Optional[Any] = Ellipsis) -> EmitResult:
2308@_guard
2309def serialize(module: PioModule, destination: Optional[Any] = None) -> EmitResult:
2310    """Serialize a module as PowerIO IR."""
2311    return _emit_to_destination(
2312        module,
2313        destination,
2314        module._inner._serialize_memory,
2315        module._inner._serialize_path,
2316    )

Serialize a module as PowerIO IR.

def versions() -> Any:
1180@_guard
1181def versions() -> Any:
1182    """Return the PowerIO release, the PowerIO IR identity, and BMOPF schema.
1183
1184    ``powerio_ir`` is ``{"schema": "pio-ir", "version": <release>}``: the
1185    release whose schema the documents this build writes follow.
1186    ``bmopf_schema`` is the ``$id`` of the one BMOPF schema PowerIO writes.
1187    """
1188    return _json.loads(_powerio.versions_json())

Return the PowerIO release, the PowerIO IR identity, and BMOPF schema.

powerio_ir is {"schema": "pio-ir", "version": <release>}: the release whose schema the documents this build writes follow. bmopf_schema is the $id of the one BMOPF schema PowerIO writes.