Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

C ABI

powerio-capi exports the C ABI through powerio-capi/include/powerio.h. The header is generated from the Rust declarations and checked in. Regenerate it with:

cbindgen --config powerio-capi/cbindgen.toml --crate powerio-capi \
  --output powerio-capi/include/powerio.h

scripts/capi-header-parity.sh compares the exported symbols with the header in every CI feature job, and scripts/capi-header-regen.sh regenerates the header with cbindgen and diffs it once. Do not edit the header by hand.

The exported symbol set is fixed. The gridfm cargo feature adds GridFM Parquet parsing and emission behind the same entry points, and the matrix, dist, and prob feature names are still accepted by the build but gate nothing. pio_schema_report returns a JSON document with the release (powerio_version), the PowerIO IR schema name and version (powerio_ir with schema and version), the BMOPF schema version, the compiled features, and the diagnostic namespaces and error categories.

The Arrow C export was removed in 0.11.0, and PowerIO 0.12 removed the inert arrow build flag that 0.11 kept for source-build compatibility: a command with --features arrow no longer resolves, so drop the flag (for example cargo build -p powerio-capi --release --features matrix,gridfm,dist,prob). The Arrow record batches and Parquet support behind gridfm are unchanged.

Versions and compatibility

The header states the PowerIO release it was generated from as PIO_VERSION_MAJOR, PIO_VERSION_MINOR, and PIO_VERSION_PATCH, and pio_version_numbers() returns the release of the loaded library as a PioVersionView. pio_version() returns the same release as text. A prerelease such as 1.0.0-rc.1 states its core release, 1.0.0, in the numbers and the whole version in pio_version().

A program compiled against the header of release X.Y.Z works with any library that

  • is in the same release series, as Cargo defines it: the same major and minor numbers before 1.0 (0.12.x), the same major number from 1.0 on (1.x), and
  • is release X.Y.Z or newer.

Within a release series the C ABI only gains symbols: no symbol is removed, and no signature or struct layout changes. A break starts a new release series. Check the library before you use it:

static int library_matches_header(PioVersionView library) {
    if (library.major != PIO_VERSION_MAJOR) {
        return 0;
    }
    if (library.minor != PIO_VERSION_MINOR) {
        return PIO_VERSION_MAJOR > 0 && library.minor > PIO_VERSION_MINOR;
    }
    return library.patch >= PIO_VERSION_PATCH;
}

if (!library_matches_header(pio_version_numbers())) {
    /* the library is from another release series, or older than the header */
}

scripts/check-capi-header.py holds the header to that rule in CI. It compares powerio.h with the header of the newest release tag at or below the workspace version and fails when a function, struct, opaque type, or #define of that header is missing or declared differently; comments and parameter names do not count. A pull request that is meant to break the C ABI before the version moves carries the semver-major label, and once the workspace version starts a new release series the check lists the differences without failing.

Before 0.12 the header carried a separate ABI number; PowerIO 0.12 replaced it with the release. See From 0.11 to 0.12.

Parse and inspect a module

PioError *error = NULL;
PioSource *source = pio_source_open("case9.m", 7, &error);
PioModule *module = pio_parse(source, NULL, 0, &error);
PioValueHandle *value = pio_module_value(module);

if (!pio_value_is_type(value, "powerio.BalancedNetwork", 23)) {
    /* handle an unexpected PowerIO type */
}

PioBalancedNetwork *network = pio_value_balanced_network(value, &error);
size_t buses = pio_balanced_network_bus_count(network);

PioDiagnostics *diagnostics = pio_module_diagnostics(module);
for (size_t i = 0; i < pio_diagnostics_len(diagnostics); i++) {
    PioStringView code = pio_diagnostic_code(diagnostics, i);
    /* code.data has code.len bytes and is not NUL terminated */
}

pio_diagnostics_release(diagnostics);
pio_balanced_network_release(network);
pio_value_release(value);
pio_module_release(module);
pio_source_release(source);

Use pio_source_from_memory for text or binary bytes you already hold in memory; both source constructors feed the same pio_parse. pio_geo_layer_parse reads a geographic layer from a PioSource, opened from a path or built from memory. pio_geo_layer_diagnostics reports what that reader found, and pio_geo_layer_to_geojson writes the layer back as the canonical .geo.json document, the GeoJSON FeatureCollection with the powerio_geo member that pio_geo_layer_parse reads.

PioString *document = pio_geo_layer_to_geojson(layer, &error);
PioStringView geojson = pio_string_view(document); /* release with pio_string_release */

pio_module_value returns an owner rooted value handle, and the exact typed accessors return owner rooted views without serializing or copying the module value. Releasing a module does not invalidate a child you have retained. Every opaque handle has matching retain and release functions, and release(NULL) is a no-op.

Structural type names have replaced ordinal kind integers. Check the type with pio_value_type_name or pio_value_is_type, then call the exact typed accessor for the type you handle.

Diagnostics and errors

Fallible functions take one PioError ** output and signal failure with a null return or a documented failure value. Inspect pio_error_code, pio_error_message, and pio_error_diagnostics, and branch on the stable code rather than the message text. If you pass a null error output the error is discarded.

Every string and buffer comes with an explicit length. PioStringView, PioByteView, PioSizeView, and PioF64View borrow their data from an owning handle and need not end in NUL.

Emit and serialize

pio_emit writes a grid exchange format. With a memory destination the artifact bytes stay in the returned PioEmitResult; with a path destination the artifacts are written to disk and the result holds the same list of artifacts and the same diagnostics.

PioDestination *destination = pio_destination_memory("case", 4, &error);
PioEmitResult *result = pio_emit(module, "matpower", 8, destination, &error);

for (size_t i = 0; i < pio_emit_result_artifact_count(result); i++) {
    PioArtifact *artifact = pio_emit_result_artifact(result, i, &error);
    PioStringView name = pio_artifact_name(artifact);
    PioByteView bytes = pio_artifact_bytes(artifact);
    /* consume name and bytes before releasing artifact */
    pio_artifact_release(artifact);
}

pio_emit_result_release(result);
pio_destination_release(destination);

pio_module_serialize writes PowerIO IR and pio_module_deserialize reads it. The document header names the schema ("schema": "pio-ir") and its version, and pio_schema_report reports both under powerio_ir; the producer record names the program that wrote the document. pio_module_deserialize refuses an unsupported schema name or version, or a structural type the library does not implement, and reports what it found. PowerIO IR states which documents a release reads. The C ABI has no module JSON aliases.

PSS/E contingency analysis files

A contingency set is the content of a PSS/E .con file: named cases, each a list of outage actions. A subsystem is PSS/E’s name for a bus selection stated in a .sub file through bus, area, zone, owner and kV range selectors; a .con automatic specification and a .mon statement refer to a subsystem by name, and selecting a subsystem’s buses evaluates its selectors against a network. A monitored set is the content of a .mon file: the elements whose loading and voltage a study reports.

A .con, .sub, or .mon file parses through pio_parse like any other source; pio_value_contingency_set, pio_value_subsystem_set, and pio_value_monitored_set take the typed handle from the module value, and pio_contingency_set_parse reads a contingency file straight from an acquired source with pio_contingency_set_diagnostics for the reader’s notes. pio_emit writes each one back under psse-con, psse-sub, or psse-mon.

A handle from pio_value_contingency_set, pio_value_subsystem_set, or pio_value_monitored_set borrows the module value rather than copying it, and holds the module owner alive, so it stays readable after the module handle is released. A handle from pio_contingency_set_parse or pio_contingency_set_expand owns its set instead.

pio_contingency_set_resolve binds every case to a balanced network and returns a PioContingencyResolution. It reports rather than refuses: a case naming an element the network does not hold is counted unresolved and keeps its reason. pio_contingency_set_expand turns the automatic specifications into explicit cases against a network and a subsystem set.

PioContingencySet *cases = pio_contingency_set_parse(source, &error);
PioContingencyResolution *resolution =
    pio_contingency_set_resolve(cases, network, &error);

printf("%zu of %zu cases bound\n",
       pio_contingency_resolution_resolved_count(resolution),
       pio_contingency_resolution_case_count(resolution));

for (size_t i = 0; i < pio_contingency_resolution_case_count(resolution); i++) {
    size_t bound =
        pio_contingency_resolution_case_component_count(resolution, i);
    for (size_t j = 0; j < bound; j++) {
        PioContingencyComponentView component;
        if (!pio_contingency_resolution_case_component(resolution, i, j,
                                                       &component, &error)) {
            break;
        }
        /* component.id.component_type names the table component.row
           indexes; component.id.local_id is the element's own identity,
           and its len is 0 when the network states none for that row */
    }

    size_t missing =
        pio_contingency_resolution_case_unresolved_count(resolution, i);
    for (size_t j = 0; j < missing; j++) {
        PioStringView statement =
            pio_contingency_resolution_case_unresolved_action(resolution, i, j,
                                                              &error);
        PioStringView reason =
            pio_contingency_resolution_case_unresolved_reason(resolution, i, j,
                                                             &error);
        /* statement is the `.con` line of the action; reason is a fixed name
           such as "no_such_branch", the same name Python reports */
        printf("%.*s: %.*s\n", (int)statement.len, statement.data,
               (int)reason.len, reason.data);
    }
}

PioDiagnostics *notes = NULL;
PioContingencySet *expanded =
    pio_contingency_set_expand(cases, network, subsystems, &notes, &error);
PioString *text = pio_contingency_set_to_con(expanded, &error);
PioStringView view = pio_string_view(text);
printf("%.*s", (int)view.len, view.data);

pio_string_release(text);
pio_diagnostics_release(notes);
pio_contingency_set_release(expanded);
pio_contingency_resolution_release(resolution);
pio_contingency_set_release(cases);

pio_balanced_network_select_subsystem_buses evaluates one named subsystem’s selectors against a network and returns the buses it selects, in ascending order, as an owned PioVector whose values are bus numbers.

PioVector *buses =
    pio_balanced_network_select_subsystem_buses(network, subsystems, "A1", 2, &error);
PioF64View numbers = pio_vector_values(buses); /* release with pio_vector_release */

The set accessors are pio_contingency_set_case_count, pio_contingency_set_case_name, pio_contingency_set_diagnostics, and pio_contingency_set_to_con; pio_subsystem_set_count, pio_subsystem_set_name, and pio_subsystem_set_to_sub; and pio_monitored_set_statement_count and pio_monitored_set_to_mon. Each of the three writers returns owned text, read with pio_string_view and released with pio_string_release, which is how an expanded set reaches a file. pio_balanced_network_select_subsystem_buses reads a network and a subsystem set together and hands back an owned PioVector, read with pio_vector_values and released with pio_vector_release. The resolution accessors are pio_contingency_resolution_case_count, pio_contingency_resolution_resolved_count, pio_contingency_resolution_unresolved_count, pio_contingency_resolution_unrecognized_statement_count, pio_contingency_resolution_case_name, pio_contingency_resolution_case_is_resolved, pio_contingency_resolution_case_component_count, pio_contingency_resolution_case_component, pio_contingency_resolution_case_unresolved_count, pio_contingency_resolution_case_unresolved_reason, and pio_contingency_resolution_case_unresolved_action. Each handle has its own pio_contingency_set_retain and pio_contingency_set_release, pio_subsystem_set_retain and pio_subsystem_set_release, pio_monitored_set_retain and pio_monitored_set_release, and pio_contingency_resolution_retain and pio_contingency_resolution_release.

Collections, updates, and calculations

Time series and scenario set handles give you the length and owner rooted access to each element. Positions are zero based in C, and scenario sets can also be looked up by scenario ID.

Typed update constructors produce PioOperatingPointUpdate, PioNetworkUpdate, and PioCalculationUpdate. pio_apply_updates validates the whole batch before it applies anything and returns a PioUpdateReport listing the exact component IDs and fields it changed, and whether energized connectivity changed.

AC optimal transmission switching has its own entry points.

  • Build an instance.
    • pio_module_to_ac_ots_instance builds one with the default options from a balanced network or AC OPF module.
    • pio_module_to_ac_ots_instance_with_options takes a PioAcOtsOptions, and also reconfigures an AC OTS module. NULL options are the same as pio_module_to_ac_ots_instance.
    • pio_ac_ots_instance_create combines an AC OPF instance handle with options and keeps its objective exactly.
  • Read an instance. pio_value_ac_ots_instance returns the instance view.
    • pio_ac_ots_instance_options reads its stated options and branch count.
    • pio_ac_ots_instance_branch_at reads one branch’s initial status, whether it may switch, its costs, and its current limits.
  • Check and fix a topology. A final topology is one byte per branch: 0 is open and 1 is closed.
    • pio_ac_ots_instance_validate_topology checks it and writes its switching cost.
    • pio_ac_ots_instance_fix_topology returns the AC OPF module over it.
  • Attach and read a solution.
    • pio_ac_ots_solution_create attaches that AC OPF problem’s solution.
    • pio_value_ac_ots_solution returns the solution view.
    • pio_ac_ots_solution_summary reads the open and switched counts, the switching cost, and the objective.
    • pio_ac_ots_solution_branch_closed_at reads one final status.
    • pio_ac_ots_solution_materialize returns the network with the final statuses and solved values, ready for pio_emit.

Named matrix and vector functions expose the public DC calculations directly:

pio_calc_incidence_matrix
pio_calc_branch_susceptances
pio_calc_bus_susceptance_matrix
pio_calc_branch_flow_matrix
pio_calc_branch_phase_shift_injection
pio_calc_bus_phase_shift_injection
pio_calc_branch_flow_dc
pio_calc_bus_injection_dc

Sparse matrices come back as owned CSR arrays and vectors as owned double arrays. The C API has no public DC data bundle.

pio_calc_dc_operators builds the same operators once and returns a PioDcOperators handle whose axes are named: pio_dc_operators_bus_ids maps each bus row to its source bus id, pio_dc_operators_branch_rows maps each branch row to its position in the branch table (three winding transformer windings follow the branches), and pio_dc_operators_branch_identity states the stable identity of one branch row. Out of service branches and self loops have no row. The skip_zero_impedance argument drops a zero impedance branch and lists it under pio_dc_operators_skipped_branch_rows instead of failing the build with BUILD.OPERATOR.ZERO_IMPEDANCE. The eight calculations run over the handle as pio_dc_operators_incidence_matrix, pio_dc_operators_branch_susceptances, pio_dc_operators_bus_susceptance_matrix, pio_dc_operators_branch_flow_matrix, pio_dc_operators_branch_phase_shift_injection, pio_dc_operators_bus_phase_shift_injection, pio_dc_operators_branch_flow_dc, and pio_dc_operators_bus_injection_dc; release the handle with pio_dc_operators_release.

Distribution loads with voltage bands, dropout or current limits use pio_multiconductor_network_load_details_at. Its borrowed voltage-law view keeps nominal voltages, ZIP fractions or exponents, and every transition bound. Presence flags distinguish absent bounds from zero. The existing load view keeps its original layout and rejects laws it cannot describe.

pio_mc_ac_pf_instance_load_details_at returns prescribed power arrays and the same complete law. pio_mc_ac_pf_instance_load_terminal_name_at reads the full terminal map; power channels can have fewer entries than that map when it includes a reference conductor. Keep the network or instance handle alive while using any borrowed string or numeric array. These accessors do not serialize or clone the network.

pio_balanced_network_islands partitions a balanced network into AC islands with the Rust calc_islands rule and returns a PioIslands handle. pio_islands_count and pio_islands_at read one PioIslandView per island, largest first: its bus positions and ids, its reference buses, its in service generators and HVDC ties, and whether a generator supplies it. pio_islands_isolated_bus_ids and pio_islands_isolated_bus_indices list the buses typed isolated, which belong to no island. Release the handle with pio_islands_release.

pio_calc_sensitivities computes the DC PTDF and LODF through the routine the Python binding calls and returns a PioSensitivities handle. The formula is chosen as for the DC operators, and the solver is auto, dense, or sparse. Every reference bus is grounded, one per island, and its PTDF column is zero. pio_sensitivities_ptdf (branches by buses) and pio_sensitivities_lodf (branches by branches) are dense row major spans borrowed from the handle; pio_sensitivities_bus_ids, pio_sensitivities_branch_rows, pio_sensitivities_branch_identity, and pio_sensitivities_reference_bus_indices name the axes, which are the DC operators’ axes. Release the handle with pio_sensitivities_release.