Skip to content

mambo_power.io.matpower

MATPOWER .m case-file importer. See File formats for the column map, derived ids, warnings and limitations.

mambo_power.io.matpower

MATPOWER case-file (.m) importer.

A parser, not a MATLAB interpreter: it recognises mpc.<name> = <scalar>;, mpc.<name> = [ rows ]; and mpc.<name> = { ... }; statements, tolerates % comments, tabs, blank lines, CRLF, scientific notation, rows split by ; or newlines, and ignores every field it does not know (mpc.version is not checked; the caseformat v2 column layout is assumed). Read: baseMVA, bus, gen, branch and the optional gencost. bus_name is skipped because Bus carries no name field.

Column mapping follows the MATPOWER manual (wave M1 design items 3, 4 and 6; W1 extract §2). Units stay physical — MW, MVAr, kV, degrees, branch impedances in pu on baseMVA — exactly as the file stores them. Derived ids: bus-<BUS_I>, gen-<row>, branch-<row>, load-<BUS_I>, shunt-<BUS_I>; loads and shunts are emitted only for non-zero rows.

Three conditions are repaired rather than rejected, and each repair is reported as an ImportIssue — typed, in the ImportReport returned by load_with_report / loads_with_report, and as the CODE: message string in the legacy list returned by load_with_warnings / loads_with_warnings:

  • BASE_KV_REPLACEDBASE_KV <= 0 becomes 1.0 (CDF-derived cases carry 0 for "unknown");
  • GENCOST_REACTIVE_IGNORED — a gencost with 2 * ngen rows (reactive costs appended) keeps the first ngen rows;
  • ISLAND_DEACTIVATED — buses the slack cannot reach over in-service branches are switched off with their elements by mambo_power.model.repair_islands_entities before the network is validated (W4, design item 4: the importer repairs, the model stays strict).

Everything else that is wrong with the file raises MatpowerImportError; everything that is wrong with the network (no slack, dangling bus, ...) is left to Network validation, which raises NetworkValidationError. load / loads discard the warnings.

MatpowerImportCode module-attribute

MatpowerImportCode = Literal[
    "MISSING_BASE_MVA",
    "MISSING_SECTION",
    "UNTERMINATED_MATRIX",
    "BAD_NUMBER",
    "BAD_ROW",
]

The closed set of importer error codes (wave M1 design item 5, ported from W1).

DEFAULT_BASE_KV module-attribute

DEFAULT_BASE_KV = 1.0

Substituted for BASE_KV <= 0 (W1 convention); each substitution is warned.

ImportReport dataclass

ImportReport(
    warnings: list[ConversionIssue] = list(),
    errors: list[ConversionIssue] = list(),
)

Bases: _Report

Every repair an importer performed, in the order it happened (empty = lossless).

MatpowerImportError

MatpowerImportError(
    code: MatpowerImportCode,
    message: str,
    line: int | None = None,
)

Bases: Exception

A defect in the case file; code is stable, line is 1-based when known.

Source code in src/mambo_power/io/matpower.py
def __init__(self, code: MatpowerImportCode, message: str, line: int | None = None) -> None:
    self.code = code
    self.line = line
    super().__init__(message)

load

load(source: str | PathLike[str]) -> Network

Parse the MATPOWER case file at source; repair warnings are discarded.

Source code in src/mambo_power/io/matpower.py
def load(source: str | PathLike[str]) -> Network:
    """Parse the MATPOWER case file at ``source``; repair warnings are discarded."""
    return load_with_warnings(source)[0]

loads

loads(text: str) -> Network

Parse MATPOWER case text; repair warnings are discarded.

Source code in src/mambo_power/io/matpower.py
def loads(text: str) -> Network:
    """Parse MATPOWER case text; repair warnings are discarded."""
    return loads_with_warnings(text)[0]

load_with_warnings

load_with_warnings(
    source: str | PathLike[str],
) -> tuple[Network, list[str]]

Parse the file at source and return (network, warnings) with string warnings.

Each string is str(warning) of the typed warning load_with_report returns — CODE: message — kept as list[str] for M1 callers.

Source code in src/mambo_power/io/matpower.py
def load_with_warnings(source: str | PathLike[str]) -> tuple[Network, list[str]]:
    """Parse the file at ``source`` and return ``(network, warnings)`` with string warnings.

    Each string is ``str(warning)`` of the typed warning :func:`load_with_report` returns \u2014
    ``CODE: message`` \u2014 kept as ``list[str]`` for M1 callers.
    """
    net, report = load_with_report(source)
    return net, report.as_strings()

loads_with_warnings

loads_with_warnings(text: str) -> tuple[Network, list[str]]

Parse case text and return (network, warnings) with string warnings.

Source code in src/mambo_power/io/matpower.py
def loads_with_warnings(text: str) -> tuple[Network, list[str]]:
    """Parse case text and return ``(network, warnings)`` with string warnings."""
    net, report = loads_with_report(text)
    return net, report.as_strings()

load_with_report

load_with_report(
    source: str | PathLike[str],
) -> tuple[Network, ImportReport]

Parse the file at source and return (network, report) with typed warnings.

Source code in src/mambo_power/io/matpower.py
def load_with_report(source: str | PathLike[str]) -> tuple[Network, ImportReport]:
    """Parse the file at ``source`` and return ``(network, report)`` with typed warnings."""
    text = Path(source).read_text(encoding="utf-8-sig", errors="replace")
    return loads_with_report(text)

loads_with_report

loads_with_report(
    text: str,
) -> tuple[Network, ImportReport]

Parse case text and return (network, report); see the module docstring.

Source code in src/mambo_power/io/matpower.py
def loads_with_report(text: str) -> tuple[Network, ImportReport]:
    """Parse case text and return ``(network, report)``; see the module docstring."""
    # A leading BOM is not whitespace and would hide an ``mpc.`` assignment on the first line.
    case = _scan(text.lstrip("\ufeff"))
    net, warnings = _build(case)
    return net, ImportReport(warnings=warnings)