Skip to main content

Crate powerio_capi

Crate powerio_capi 

Source
Expand description

C ABI for powerio: ABI v5.

Functions parse, query, and convert networks through opaque handles. Feature gates add Arrow tables, directory datasets, distribution networks, .pio.json packages, and SCOPF problem instances. Each entry point is extern "C" and writes errors to a caller provided buffer.

The C API follows a fixed grammar, written out in the header preamble (include/powerio.h, generated by cbindgen, never hand-edit):

  • Verb-led names are operations and the verb fixes the return family: parse/read/normalize return a new handle, write has a filesystem effect, convert transcodes without keeping a handle, free destroys.
  • to_ marks a representation change of the same network; the target is a format string (pio_to_format) unless the output type differs (pio_to_arrow fills Arrow C Data Interface structs).
  • Format names never appear in symbols: formats are strings, so a new format never changes this ABI. Model JSON uses pio_to_json and pio_from_json.
  • Array extractors share the cap/count convention: write up to cap values, return the total available, NULL out is a pure count query.
  • Vocabulary: a bus is a named connection point (this API is bus granular); a node is one conductor’s point at a bus, reserved for the multiconductor API; a branch is any two-terminal series element, lines and transformers alike.

Structs§

PioDistNetwork
Opaque parsed distribution network handle (the multiconductor wire coordinate model). Distinct from PioNetwork (the positive sequence transmission model); none of the pio_n_*/extractor functions accept it. Only built with the dist cargo feature.
PioNetwork
Opaque parsed network handle. Carries the parsed BalancedNetwork, the IndexCore derived from it once at parse time (so every indexed query reuses the same bus-id map and per-bus aggregates instead of rebuilding them), and the reader’s fidelity warnings (pio_warnings).
PioPackage
Opaque .pio.json compiler package handle. A package owns one powerio_pkg::NetworkPackage, which wraps either a balanced PioNetwork payload or a multiconductor PioDistNetwork payload.
PioScopfInstance
Opaque matrix free SCOPF instance.

Constants§

PIO_ABI_VERSION
ABI version of this C interface. Bump on any breaking change to an existing pio_* signature or documented behavior, including removing a supported format token from the C API. New additive symbols do not require a bump. A consumer compares pio_abi_version against the value it was built against (the PIO_ABI_VERSION macro in powerio.h) and refuses a mismatched library before calling another function.
PIO_ARROW_TABLE_BDOUBLEPRIME
PIO_ARROW_TABLE_BPRIME
PIO_ARROW_TABLE_BRANCH
PIO_ARROW_TABLE_BUS
Table selectors for pio_to_arrow; the C header mirrors these as PIO_ARROW_TABLE_*.
PIO_ARROW_TABLE_GEN
PIO_ARROW_TABLE_INCIDENCE
PIO_ARROW_TABLE_LOAD
PIO_ARROW_TABLE_MATRIX_BRANCH
PIO_ARROW_TABLE_MATRIX_BUS
PIO_ARROW_TABLE_SHUNT
PIO_ARROW_TABLE_SOLVER_ARC
PIO_ARROW_TABLE_SOLVER_BRANCH
PIO_ARROW_TABLE_SOLVER_BUS
PIO_ARROW_TABLE_SOLVER_GEN
PIO_ARROW_TABLE_SOLVER_HVDC
PIO_ARROW_TABLE_SOLVER_LOAD
PIO_ARROW_TABLE_SOLVER_SHUNT
PIO_ARROW_TABLE_SOLVER_STORAGE
PIO_ARROW_TABLE_SOLVER_SWITCH
PIO_ARROW_TABLE_SWITCH
PIO_ARROW_TABLE_YBUS
PIO_DIST_ABI_VERSION
Frozen at 1 and no longer meaningful. It existed to absorb distribution volatility, but that volatility lives in the BMOPF schema, which changes a reader, a writer and an emitted token, and no C signature. One shared object carrying two compatibility promises is a thing no mature C library does.
PIO_ERRBUF_MIN
Recommended error buffer size: pass a char[PIO_ERRBUF_MIN] to any errbuf/warnbuf parameter and a message always fits without truncation.

Functions§

pio_abi_version
The ABI version the library was built with (see PIO_ABI_VERSION). Lets a consumer detect a stale or incompatible library at load time. Infallible.
pio_arrow_catalog_json
Return the Arrow table catalog as owned compact JSON.
pio_base_mva
pio_branch_charging
Write the branch terminal charging table as parallel arrays, each up to cap entries, and return the total branch count. Columns are p.u.
pio_branches
Write the branch table as parallel arrays, each up to cap entries, and return the total branch count. A branch is any two-terminal series element lines and transformers alike (a transformer has tap != 0). from/to are 1-based bus IDS (the pio_bus_ids id space, not dense indices); map them to dense matrix rows with the pio_bus_ids ordering. Any output pointer may be NULL to skip that column; all NULL is the count query.
pio_build_info
Everything a loader needs to decide what this library can do, as one owned JSON document. Free the returned string with pio_string_free. Infallible.
pio_bus_demand
Write the per-bus demand aggregates (active pd, reactive qd, summed over each bus’s loads, dense pio_bus_ids order), each up to cap entries, and return the total bus count. Either pointer may be NULL.
pio_bus_ids
Write the 1-based external bus ids, in dense order, into out, up to cap entries, and return the total bus count. This ordering DEFINES the dense index space every other per-bus array shares. Call once with (NULL, 0) to size, allocate, then call again to fill. Ids are int64 in 1..2^63-1 (a v4 invariant); a source id that is a string or exceeds that range is mapped to dense int64 at read, never passed through raw.
pio_bus_shunt
Write the per-bus shunt aggregates (conductance gs, susceptance bs, dense pio_bus_ids order), each up to cap entries, and return the total bus count. Either pointer may be NULL.
pio_classify_str
Classify in-memory JSON case text by its top level markers, without parsing the case. Writes one of
pio_convert_file
Convert the case file at path from format from (NULL to infer from the path, as pio_parse_file) to format to, without keeping a handle. Returns the converted text as an owned C string (free with pio_string_free), NULL on error. Fidelity warnings, read side first, are published through out_warnings as one owned C string (free it with pio_string_free), NULL when there are none. Pass NULL to discard them.
pio_convert_str
Convert in-memory case text from format from (required; there is no path to infer from) to format to without keeping a handle. Returns the converted text as an owned C string (free with pio_string_free), NULL on error. Fidelity warnings, read side first, are written \n-joined into warnbuf.
pio_dist_abi_version
The ABI version of the optional pio_dist_* C API. Only linked when the dist feature is compiled in; probe that first with pio_has_feature("dist") if loading dynamically.
pio_dist_capabilities_json
Return distribution capability flags as owned JSON. Free the returned string with pio_string_free. Only linked when the dist feature is compiled in; runtime loaders can either check pio_has_feature("dist") or probe for this symbol directly. The JSON schema is versioned separately from PIO_DIST_ABI_VERSION so new additive flags do not force a C signature change.
pio_dist_convert_file
Convert distribution case path from optional source format from to format to; see pio_dist_parse_file for the inference rules. Returns the converted text as an owned C string (free with pio_string_free), NULL on error. The warnings written \n-joined into warnbuf carry both the parse warnings and the writer’s fidelity losses (there is no handle to query them).
pio_dist_convert_str
Convert in-memory distribution case text of format from to format to (both required; dss, pmd, or bmopf). The parameter order is input, source, target, matching pio_dist_convert_file. Returns the converted text as an owned C string (free with pio_string_free), NULL on error. The warnings written \n-joined into warnbuf carry both the parse warnings and the writer’s fidelity losses (there is no handle to query them).
pio_dist_from_json
Parse model JSON produced by pio_dist_to_json (or lifted from a .pio.json document’s model.multiconductor_network) back into an owned handle: the inverse of pio_dist_to_json. The rebuilt handle retains no source text, so a same format write is a fresh serialization. The handle retains the model JSON warnings. Returns NULL on error. Free with pio_dist_network_free.
pio_dist_geo_apply
Apply a geographic sidecar (any form pio_geo_parse accepts) onto a NEW distribution network handle; the input handle is unchanged and both are freed with pio_dist_network_free. name_hint (a file name, nullable) picks CSV against JSON as in pio_geo_parse. The returned handle drops the retained source text, so a same-format write re-serializes the placed case. The reader’s notes and an apply summary are appended to the handle’s warnings (pio_dist_warnings). Returns NULL on error.
pio_dist_geo_extract
Extract a multiconductor network’s coordinates as the canonical GeoJSON layer, keyed by the string bus and line names. Free the returned string with pio_string_free. Returns NULL (with a message) when the network carries no coordinates.
pio_dist_graph_json
Serialize the collapsed bus and terminal graph projection for net as JSON. The returned string is owned by the library; free it with pio_string_free.
pio_dist_network_free
Free a distribution network handle from pio_dist_parse_file or pio_dist_parse_str. NULL is a no-op; free exactly once.
pio_dist_parse_file
Parse a distribution case file into a PioDistNetwork handle. The format comes from from if non-NULL (dss, pmd, or bmopf), else from the file itself: .dss is OpenDSS, and .json holding the ENGINEERING data_model key is PMD JSON, otherwise BMOPF JSON. Returns NULL on error and writes the message into errbuf. Free the handle with pio_dist_network_free.
pio_dist_parse_str
Parse in-memory distribution case text of the named format (dss, pmd, or bmopf; required, since there is no path to infer from). An OpenDSS Redirect/Compile in text resolves against the current working directory. Returns NULL on error and writes the message into errbuf. Free the handle with pio_dist_network_free.
pio_dist_summary_json
Serialize a compact summary of a distribution handle as JSON. This lets bindings answer display and scalar queries without forcing pio_dist_to_json’s full model payload.
pio_dist_to_format
Serialize net to distribution format to (dss, pmd, or bmopf). Writing back to the format the handle was parsed from echoes the source text byte for byte; a cross format write reports every fidelity loss in warnbuf (\n-joined). Returns the text as an owned C string (free with pio_string_free), NULL on error.
pio_dist_to_json
Serialize net to its model JSON: the same object a .pio.json package carries under model.multiconductor_network, without the surrounding document. This is the bindings’ data transport, not a case format: the converter, CLI, and format inference do not know it; distribution cases exchanged with other tools are BMOPF JSON (pio_dist_to_format). Returns an owned C string (free with pio_string_free), NULL on error.
pio_dist_warnings
Parse warnings retained on the handle (everything the reader could not represent or had to assume), \n-joined and written into the caller warnbuf (truncated to fit, always NUL-terminated). Returns the total byte length of the joined message; call with NULL/0 to size first, then fill — the same idiom as pio_warnings. Returns 0 for a NULL handle.
pio_from_json
Parse model JSON produced by pio_to_json (or lifted from a .pio.json document’s model.balanced_network) back into an owned handle, the inverse of pio_to_json and the function form of parsing under the powerio-json token. Returns NULL on error. Free with pio_network_free.
pio_gens
Write the generator table as parallel arrays, each up to cap entries, and return the total generator count. bus is the 1-based bus id (the pio_bus_ids id space). Any output pointer may be NULL to skip.
pio_geo_apply
Apply a geographic sidecar (any form pio_geo_parse accepts) onto a NEW network handle; the input handle is unchanged and both are freed with pio_network_free. name_hint (a file name, nullable) picks CSV against JSON as in pio_geo_parse. Matched bus points land in Bus.location, matched branch routes in Branch.route. The returned handle drops the retained source text, so a same-format write re-serializes the placed case instead of echoing the original. The reader’s notes and an apply summary (geo apply: N bus point(s), ...) are appended to the handle’s warnings (pio_warnings). Returns NULL on error.
pio_geo_extract
Extract a network’s coordinates as the canonical GeoJSON layer: one point per located bus, one route per routed branch. Free the returned string with pio_string_free. Returns NULL (with a message) when the network carries no coordinates.
pio_geo_parse
Normalize a tolerant geographic sidecar (headerless buscoords CSV, aliased CSV/JSON records, GeoJSON Point/LineString) to the canonical GeoJSON form. name_hint (a file name, nullable) picks CSV against JSON when given; otherwise the content is sniffed. The tolerant reader’s notes are not returned here; parse through the Rust or Python surface to see them. Free the returned string with pio_string_free. Returns NULL on input that carries no usable coordinates and writes the message into errbuf.
pio_has_feature
Whether an optional build feature is compiled in: pass "arrow", "matrix", "gridfm", "dist", "pkg", or "prob". Returns 1 if present, 0 otherwise (and 0 for a NULL or unknown name). The optional entry points (pio_to_arrow, the matrix Arrow tables, the pio_read_dir/gridfm path, the pio_dist_* block, and the pio_package_* block) are only linked when their feature is built, so a consumer that loaded the library at runtime probes for them here instead of resolving symbols blind. Feature names are strings like format names, so a new feature never changes this signature. Infallible.
pio_is_radial
1 if the in-service topology is radial (every island a tree), else 0.
pio_matrix_available
Whether the matrix Arrow table API is usable in this build. Returns 1 only when both arrow and matrix are compiled in. Matrix tables use pio_to_arrow. Infallible.
pio_n_branches
pio_n_buses
pio_n_gens
pio_n_islands
Number of islands: connected components of the in-service topology.
pio_n_switches
pio_network_free
Free a network handle from pio_parse_file, pio_parse_str, pio_read_dir, pio_normalize, or pio_normalize_with_options.
pio_network_name
Case name. Writes UTF-8 bytes into out, up to cap, NUL-terminates when possible, and returns the byte length needed excluding the NUL. NULL or cap == 0 is a size query.
pio_normalize
Normalize net into a NEW network handle: per unit, radians, out of service filtered, source bus ids preserved, bus types canonicalized (see BalancedNetwork::to_normalized). A value transform, not a serialization, hence the verb, while the to_* family re-encodes unchanged data. The result is independent of net; free both with pio_network_free. Every extractor and serializer works on it unchanged (the handle is per unit, not MW). Returns NULL on error (no reference bus can be chosen, or a non-positive base MVA) and writes the message into errbuf.
pio_normalize_with_options
Normalize net into a NEW network handle, with opt in solver preparation repairs. clamp_angle_bounds != 0 applies the same branch angle difference bound repair as PowerModels (angmin <= -pi/2, angmax >= pi/2, and zero/zero bounds replaced by [-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. Existing read warnings and repair warnings are attached to the returned handle and can be read with pio_warnings.
pio_package_diagnostics_json
Return the package structured diagnostics array as JSON. The returned string is owned by the library; free it with pio_string_free.
pio_package_free
Free a package handle returned by pio_package_*. NULL is a no-op; free exactly once.
pio_package_from_balanced_network
Wrap a balanced PioNetwork handle in a .pio.json package. The C handle name is historical; the payload is powerio::BalancedNetwork. include_solver_metadata != 0 attaches compact normalized solver table metadata.
pio_package_from_multiconductor_network
Wrap a multiconductor PioDistNetwork handle in a .pio.json package. The C handle name is historical; the payload is powerio_dist::MulticonductorNetwork.
pio_package_lower_multiconductor_to_balanced
Lower a multiconductor package to a new balanced package. Call pio_package_multiconductor_to_balanced_preflight_json first when the caller needs structured blockers for unsupported inputs. base_mva is the three phase system power base used for the balanced per-unit projection.
pio_package_materialize_operating_point
Materialize one operating point into a new static package.
pio_package_materialize_study_commit
Materialize one study commit into a new static package.
pio_package_multiconductor_to_balanced_preflight_json
Return the multiconductor-to-balanced lowering preflight report as JSON. base_mva is the three phase system power base used for the balanced per-unit projection. Returns NULL if the package is not multiconductor.
pio_package_operating_points_json
Return the package operating point series as JSON, or null when absent. The returned string is owned by the library; free it with pio_string_free.
pio_package_parse_file
Parse a .pio.json package file into an opaque package handle. This reads only the package; case format names still enter through pio_parse_file / pio_dist_parse_file and package constructors. Returns NULL on error and writes the message into errbuf. Free the handle with pio_package_free.
pio_package_parse_str
Parse in-memory .pio.json text into an opaque package handle. Returns NULL on error and writes the message into errbuf. Free the handle with pio_package_free.
pio_package_set_operating_points
Replace the package’s operating point series from json. null or an empty series clears it. Validation is recomputed before this function returns. Returns 0 on success and -1 on error.
pio_package_study_json
Return the package study block as JSON, or null when absent. The returned string is owned by the library; free it with pio_string_free.
pio_package_to_balanced_network
Materialize the balanced payload of a package handle as an owned network handle: the inverse of pio_package_from_balanced_network. Errors when the package holds a different model kind. The handle is built from the payload alone: it retains no source text, so a same format write is a fresh serialization rather than a byte-exact echo, and it carries no parse warnings. Free with pio_network_free.
pio_package_to_json
Serialize a package handle to compact .pio.json. Returns an owned C string (free with pio_string_free) or NULL on error.
pio_package_to_multiconductor_network
Materialize the multiconductor payload of a package handle as an owned distribution network handle: the inverse of pio_package_from_multiconductor_network. Errors when the package holds a different model kind. The handle retains no source text, so a same format write is a fresh serialization. The handle retains the payload’s parse warnings, readable through pio_dist_warnings. Free with pio_dist_network_free.
pio_package_validate
Run the package semantic validation profile in place. Returns 0 on success, -1 on error.
pio_package_validation_json
Return the package validation summary as JSON. The returned string is owned by the library; free it with pio_string_free.
pio_parse_bytes
Parse len bytes of in-memory case data of the named format into a network handle. Accepts every pio_parse_str format name plus pwb: PowerWorld binary has no text form, so before this call the only way to reach that reader was pio_parse_file, which means staging a temporary file. bytes need not be NUL-terminated and may contain interior NULs; text formats are decoded as UTF-8 and fail with a message if they are not.
pio_parse_file
Parse path (format from extension, or from if non-NULL) into a network handle. from accepts the pio_parse_str format names plus pypsa-csv/pypsa, goc3-json/goc3, surge-json/surge, and pwb; that includes pslf/epc, and .epc is inferred by extension. A PyPSA CSV folder is a directory, so it can only enter through this function, with from = "pypsa-csv" (or NULL when the directory holds a network.csv). Read fidelity warnings attach to the handle (pio_warnings). Returns NULL on error and writes the message into errbuf. Free the handle with pio_network_free.
pio_parse_str
Parse in-memory case text of the named format into a network handle. Unlike pio_parse_file there is no path to infer from, so format is required: one of matpower/m, powermodels/pm, egret, pandapower-json/pandapower/pp, psse/raw, powerworld/aux, pslf/epc, goc3-json/goc3, or surge-json/surge. PyPSA CSV folders are directories, not text; parse them with pio_parse_file and from = "pypsa-csv". Read fidelity warnings attach to the handle (pio_warnings). Returns NULL on error and writes the message into errbuf. Free the handle with pio_network_free. Also accepts powerio-json/json as aliases for pio_from_json.
pio_read_dir
Read one scenario of a dataset directory in the named from format into a network handle. gridfm (the gridfm-datakit Parquet layout; dir resolves leniently: the raw/ leaf, a <case>/ directory with a raw/ child, or a parent holding exactly one such case) is the currently supported dataset format. scenario selects within a multi-scenario dataset (pio_scenario_ids enumerates them); formats without scenarios take 0. Read fidelity warnings attach to the handle (pio_warnings). Returns NULL on error and writes the message into errbuf. Free the handle with pio_network_free. Built --features gridfm.
pio_ref_bus_index
Dense [0, n) index of the single reference (slack) bus, or -1 if not exactly one. An INDEX into the pio_bus_ids ordering, not a bus id; pio_branches from/to carry ids, so the unit is in the name. A network may carry several references (one per island, or a normalized case that kept the file’s multiple REF buses); pio_ref_bus_indices reads them all, and its count (NULL out) tells zero from many.
pio_ref_bus_indices
Write the dense [0, n) indices of the reference (slack) buses, ascending, into out, up to cap entries, and return the total count: the cap/count convention of pio_bus_ids. 0 means none; > 1 means one reference per island or several fixed references in one island (a normalized case always reports >= 1).
pio_scenario_ids
Write the distinct scenario ids (ascending) of the dataset directory dir in the named from format into out, up to cap entries, and return the total count: the cap/count convention of pio_bus_ids. gridfm is the currently supported dataset format. Returns -1 on error and writes the message into errbuf (unlike the handle extractors, this reads the filesystem and can fail). Built --features gridfm.
pio_schema_versions_json
Report the schema version of each document format in this library, as owned JSON. Free the returned string with pio_string_free. Infallible.
pio_scopf_instance_free
Free a SCOPF instance handle. NULL is a no-op; free each handle once.
pio_scopf_parse_str
Parse SCOPF source text into an owned problem instance. from currently accepts "goc3-json". Returns NULL on error and writes the message into errbuf. Free the handle with pio_scopf_instance_free.
pio_scopf_to_json
Serialize a SCOPF instance as its Julia compatibility document. The JSON records its schema version and index base. Free the returned string with pio_string_free. Returns NULL for a null handle or serialization error.
pio_source_format
Source format enum spelling used by the JSON snapshot, for example Matpower, PowerModelsJson, or Normalized. Uses the same cap/count string convention as pio_network_name.
pio_string_free
Free any owned C string returned by this API.
pio_summary_json
Serialize a compact balanced network summary as JSON for display and scalar queries without serializing pio_to_json’s full payload.
pio_switches
Write the switch table as parallel arrays, each up to cap entries, and return the total switch count. from/to are external bus ids.
pio_to_arrow
Export one network table over the Arrow C Data Interface: the to_ conversion whose output type is Arrow structs rather than a string, and the bulk table surface of this ABI. Tables 0..5 are raw network tables; tables 6..14 are normalized solver tables with per unit/radian values and dense zero based row ids; the matrix tables carry COO triplets in that dense index space with dimensions in schema metadata. New columns extend the Arrow schema without changing an existing C signature.
pio_to_format
Serialize net to the named format to: the one text serializer; every format is named by a string. Accepts the pio_parse_str names: matpower is a byte-exact echo when the handle was parsed from MATPOWER. Also accepts powerio-json as an alias for pio_to_json. Model JSON cannot represent a non-finite f64 (Inf/NaN): it writes null, records the field in out_warnings, and fails validation when read back.
pio_to_json
Serialize net to its model JSON: the same object a .pio.json package carries under model.balanced_network, without the surrounding document, and the same text the powerio-json format token writes. This is the bindings’ data transport; the token remains as a compatibility alias for file based workflows. Returns an owned C string (free with pio_string_free), NULL on error.
pio_version
The crate version string (a semver string), 'static and NUL-terminated. Do NOT free it. Informational; pair it with pio_abi_version for the actual compatibility check.
pio_warnings
The fidelity warnings attached to the handle at construction (by whichever of pio_parse_file, pio_parse_str, pio_read_dir, or pio_normalize built it), \n-joined into warnbuf (truncated to fit on a UTF-8 boundary; NULL/0 to skip). Returns the byte length of the full joined text, excluding the NUL; call once with (NULL, 0) to size, then pass a char[len + 1]. 0 means no warnings (or a NULL handle); readers that are total attach none.
pio_write_dir
Write net into out_dir as the named directory format to. PyPSA CSV (pypsa-csv/pypsa) is the currently supported directory format; a text format name is an error pointing back at pio_to_format. Returns 0 on success and -1 on error (message into errbuf). Fidelity warnings, if any, are published through out_warnings as one owned C string (free it with pio_string_free), NULL when there are none. Pass NULL to discard them.