Format Adapters Reference

Public API

Sparlectra.FormatAdapter — Type
FormatAdapter

Abstract supertype of the format adapters. The model: an adapter owns BOTH output forms of its format. Its IMPORTER builds the network directly and hands it to the solver, with no intermediate format, no conversion, no loss; its CONVERTER turns the format into the typed SCFCase and runs ONLY when someone asks for that file (export to SCF, the Case page export action, the shipped-case builders, or the scenario engine's id index). SCF is the preferred working format but never a mandatory way station: no import path converts.

The contract per concrete adapter:

  • detect(::Type{A}, path)::Bool: content-based detection reading at most the first 4 KiB of the file.
  • options_type(::A)::Type: the adapter's option struct.
  • import_net(::A, source, opts)::Net: the importer, used by import_case.
  • convert_case(::A, source, opts)::SCFCase: the converter, explicit requests only.
  • export_case(::A, net, path; opts): optional, the reverse direction.
source
Sparlectra.DTFAdapterOptions — Type
DTFAdapterOptions

The adapter-scope options of the DTF conversion: parser strictness and base power, the transformer ratio convention, the legacy voltage-level collapse, the model settings consumed while the case is interpreted, the outage selection (a DTF adapter option), and the system frequency f_nom in Hz the conversion writes into the case (model.nominal_frequency_hz; DTF states none).

source
Sparlectra.dtf_adapter_options — Method
dtf_adapter_options(cfg::SparlectraConfig) -> DTFAdapterOptions

The adapter options an effective run configuration implies. The DTF conventions themselves (transformer_ratio_mode, the legacy collapse) have no configuration keys yet, so they stay at the importer defaults here.

source
Sparlectra.MatpowerAdapterOptions — Type
MatpowerAdapterOptions

The adapter-scope options of the MATPOWER conversion: the import conventions plus the model settings that are consumed WHILE the case is interpreted (the tap-changer impedance correction rewrites R/X at conversion time). Field names follow the configuration keys.

source
Sparlectra.matpower_adapter_options — Method
matpower_adapter_options(cfg::SparlectraConfig) -> MatpowerAdapterOptions

The adapter options an effective run configuration implies; the run path builds them here so the conversion and the historical direct import read the same keys.

source
Sparlectra.PGMAdapterOptions — Type
PGMAdapterOptions

The power-grid-model conversion takes no options: the dataset is already in the case format's own vocabulary. The struct exists for the adapter contract.

source
Sparlectra.PowsyblAdapterOptions — Type
PowsyblAdapterOptions

The adapter-scope options of the PowSyBl import, mirroring the powsybl_import configuration scope: the system base, the HVDC model (:fixed_injection or :paired_control), generator ids that override the slack choice, whether every synchronous component gets its own slack, how a remote voltage regulation is mapped (:remote, the default, attaches an outer-loop machine voltage control on the regulated bus as OpenLoadFlow regulates it; :hold_local keeps the unit PV at its own bus with the target in pu of the regulated bus, :pq makes it PQ with target_q). remote_deadband_vm_pu is the deadband of those controls, ten times the power-flow tolerance (power_flow.tol, or tol_MW over the base), at most 1e-3 pu; the default follows the default tolerance. f_nom is the system frequency in Hz the conversion writes into the case (model.nominal_frequency_hz; IIDM states none).

source
Sparlectra.convert_case — Method
convert_case(::PowsyblAdapter, source, opts) -> SCFCase

Build the network and capture it as a typed case (source_format = "powsybl"); the import report goes into the namespaced meta as powsybl_import.

source
Sparlectra.powsybl_adapter_options — Method
powsybl_adapter_options(cfg::SparlectraConfig) -> PowsyblAdapterOptions

The adapter options an effective run configuration implies (the powsybl_import scope, and the remote-control deadband from the power-flow tolerance).

source
Sparlectra.PowsyblTables — Type
PowsyblTables

A PowSyBl table bundle in memory: the manifest as a Dict and one NamedTuple of column vectors per pypowsybl table (field names as in POWSYBL_TABLE_FIELDS). The keyword constructor defaults every table to its empty schema form, so a table that a source does not carry is present with zero rows, never absent.

source
Sparlectra.read_powsybl_bundle — Method
read_powsybl_bundle(dir) -> PowsyblTables

Read a PowSyBl table bundle: manifest.json (format powsybl_tables, version 1) and every table of POWSYBL_TABLE_NAMES from the file the manifest names. Column types follow POWSYBL_SCHEMA, never the data; a required column that is missing, a table that the manifest does not list or whose file is absent, and a row count that disagrees with the manifest each fail with an ArgumentError naming the bundle, the table and the column. Columns the schema does not know are kept as strings. A tap changer row with an empty tap cell carries no step: the changer sits at the middle of low_tap..high_tap, the transformer columns at the current tap are recomputed from the step rows, and the manifest key tap_position_assumed lists the changer for the import notice and the tap estimation.

source
Sparlectra.write_powsybl_bundle — Method
write_powsybl_bundle(tables::PowsyblTables, dir; manifest_extra = Dict()) -> String

Write a bundle directory: one CSV per table of POWSYBL_TABLE_NAMES (<table>.csv, index columns first as the NamedTuple carries them) and manifest.json. The manifest starts from tables.manifest, so a read bundle round-trips with its case, source and reference fields, then sets format, format_version, written (UTC now) and the tables entries (file, rows, index), and finally takes every key of manifest_extra. Returns the manifest path.

source
Sparlectra.build_net_from_powsybl — Method
build_net_from_powsybl(tables::PowsyblTables, opts::PowsyblAdapterOptions; name = "") -> (Net, PowsyblImportReport)

Build a Sparlectra network from PowSyBl tables: buses and links, lines, two- and three-winding transformers, generators (with the slack per synchronous component), loads, shunts, static var compensators, dangling and tie lines, HVDC links. The report says what was built, what was skipped and why, and which generator carries the reference of each component. name defaults to the manifest's case name.

With remote_regulation = :remote a remote voltage control the control framework refuses is mapped as with :hold_local: the net is built again with that unit held at its own bus, so it is the net the :hold_local import builds for that unit.

source
Sparlectra.PowsyblImportReport — Type
PowsyblImportReport

What the builder did with a bundle. counts maps an element kind ("bus", "line", "generator", ...) to (read, built, skipped); skipped lists every element that was not built with its id, kind and reason; slack records the slack decision per synchronous component; messages holds the notices. bus_substation and bus_view keep the bus metadata the Net has no field for (substation id and bus-view id per bus-breaker bus), temporary_limits the temporary current limits per branch element id as (duration_s, value_A) pairs.

source
Sparlectra.format_powsybl_report — Method
format_powsybl_report(report::PowsyblImportReport) -> String

The console block of an import: one count line per element kind (read, built, skipped), the slack decision per synchronous component, the notices, then one line per skipped element with id, kind and reason.

source
Sparlectra.createNetFromDTFFile — Method
createNetFromDTFFile(path; baseMVA = 100.0, strict = true, bus_shunt_model = :admittance, transformer_ratio_mode = :neutral_one) -> Net

Read a legacy DTF file and build a Sparlectra Net without routing through MATPOWER. Outage cards are parsed and preserved in DTFCase by DTFImporter.read_dtf, but are not executed by this Task-1 importer MVP.

source
Sparlectra.CGMESImporter.importCGMES — Method
importCGMES(config; path, name, hvdc_mode, ignore_connected) -> CGMESImportResult

Import a CGMES delivery with everything the configuration says about it, in one place: the seventeen cgmes_import values and the bus shunt model (the net-parameter stamping lives with the import dispatch: once per importer). The four service call sites used to unpack the same values by hand, and a new option had to be added in four places or it silently kept its default at three of them (the accompanying stamp was found in the wrong function once already). The keyword form of importCGMES stays for programmatic use.

path takes everything the keyword form takes, including a CGMESStore from loadCGMES, which is not modified. hvdc_mode and ignore_connected default to cgmes_import.hvdc_mode and cgmes_import.ignore_connected; a caller that needs every element built whatever its SSH state passes ignore_connected = true.

source
Sparlectra.writeMatpowerCasefile — Method
writeMatpowerCasefile(net::Net, pathfilename::String; write_solution::Union{Nothing,Bool} = nothing, source_case = nothing)

Write Matpower case files.

A transformer row carries the ratio and shift in effect in TAP/SHIFT, so every MATPOWER reader solves the same network. Tap-changer nameplates and the neutral position go to mpc.sparlectra.tap_changers (14 columns), which Sparlectra reads back; see the MATPOWER page of the documentation.

Arguments

  • net::Net: Network object.
  • pathfilename::String: Path and filename to write the Matpower case file.
  • asymmetric_shunts::Symbol: the rule for a branch whose two terminal shunt arms differ; :bus_shunt (the only value) writes the symmetric part on the branch row and the terminal excess as a bus shunt, named in a comment line and in mpc.sparlectra.branch_shunts.
  • source_case::Union{Nothing,AbstractString}: the case file the network came from; when given, its file name is written into the header as % Source case: so that an exported calculated state stays linked to its input. The input file itself is never written by this function.
  • write_solution::Union{Nothing,Bool}: Whether to write the solved AC power-flow state back into the export: mpc.bus VM/VA reflect the solved node state, and mpc.branch gains the MATPOWER result columns 14-17 (PF, QF, PT, QT) sourced from the existing branch-flow report path (no flow recomputation in the exporter). nothing (default) reads matpower_export.write_solution from the active configuration (default true, see MatpowerExportConfig). When true but the network has no solved branch flows, the exporter warns and falls back to the historical 13-column model-only mpc.branch export instead of writing empty result columns. When false, the export is a pure model file: mpc.branch keeps 13 columns and VM = 1.0/VA = 0.0 for all non-slack/non-PV buses (slack and PV setpoints are preserved), except an auxiliary bus (three-winding star point), which gets the start the solver's flat start gives it: the voltage at which its stiffest winding carries no current. With a slack angle other than 0 every bus is written at the slack angle, the angle of the flat start. The auxiliary buses are listed in mpc.sparlectra.aux_buses, so the reader keeps them auxiliary. A network without solved branch flows writes the generator voltage setpoint as Vg and as VM of its PV and slack bus, and the flat-start angle at a PV bus.

Example

net = Net(...)
writeMatpowerCasefile(net, "casefile.m")
source
Sparlectra.run_matpower_case — Method
run_matpower_case(; casefile::AbstractString = "", config_file::AbstractString = "")

Run MATPOWER import and power-flow with central typed configuration plus runner-level operational output and logging.

source
Sparlectra.SCFCase — Type
SCFCase

One SCF document in memory: the PGM root scalars, the typed data section, and the namespaced sparlectra block (nothing for a strict-PGM file, which carries none). File reading (read_scf_json) and writing (write_scf_json) are serialization of this struct; build_net is the one network constructor over it.

source
Sparlectra.read_scf_json — Method
read_scf_json(path) -> SCFCase

Read one SCF case file into its typed in-memory form. Validation is the reader's staged file-level check (schema, study definitions, reference integrity) on the parsed document, so a broken file fails here with the same line of reasoning the upload path shows; the model plausibility stage runs when the network is built (build_net).

source
Sparlectra.exportSCF — Method
exportSCF(net; file, kwargs...) -> String

Write net as a Sparlectra Case Format file (.scf.json, issue #342) and return the path. The data section is a valid power-grid-model input dataset in SI units; everything Sparlectra adds (slack roles, tap changers and their sets, names and source ids, measurement detail) lives under the namespaced sparlectra key. Case-scope configuration travels in the case configuration file next to the case (write_case_config), not inside it.

Ids are deterministic (component type, then name), so exporting the same network twice produces byte-identical files and Git diffs stay readable.

Keyword arguments:

  • case_name, source_format, source_reference, notes: meta fields; case_name defaults to the network name.
  • f_nom: system frequency in Hz, written as meta.f_nom and used to turn the line susceptance into the capacitance c1; default net.nominal_frequency_hz.
  • intended_calculations: the contract of the file (default ["power_flow"]).
  • measurement_provenance: what is known about the measurement set (noise, generator, seed); it lands in sparlectra.measurements.provenance and is what tells a reader that a set is ideal rather than measured.
  • scenarios, short_circuit: study definitions written as the sparlectra.scenarios and sparlectra.short_circuit blocks (the document form of scenario_set_dict for scenarios).
  • include_start_state: write the current bus voltages as START values (never as results). Off by default, because a stale start state on an edited net is worse than none.
  • strict_pgm: write ONLY the power-grid-model input dataset, without the namespaced sparlectra block, for a consumer that reads PGM and nothing else. Everything that block carries is then absent from the file, meta.f_nom included; the export names what it dropped in a warning. Off by default.
  • units: :si (default) or :pu. With :pu the file declares meta.units = "pu" and carries the branch and shunt parameters per unit in the pu block of their sparlectra.extra entry, so a network that was built from per-unit data (MATPOWER) reads back bit for bit. The data section stays the SI view. Not combinable with strict_pgm.

Throws an ArgumentError when the network carries FACTS-compensated impedances (call restoreBaseImpedances! first).

source
Sparlectra.net_to_scf — Method
net_to_scf(net; kwargs...) -> Dict{String,Any}

Build the SCF root object of net (see exportSCF for the keyword arguments). Pure: the network is not modified.

source
Sparlectra.net_to_scfcase — Method
net_to_scfcase(net; kwargs...) -> SCFCase

The typed case of net: what exportSCF writes, as the in-memory SCFCase. Takes the same keyword arguments as exportSCF; pure, the network is not modified. The document assembly stays the deterministic dict builder (net_to_scf), converted once at the end, so the typed form and the file bytes cannot diverge.

source
Sparlectra.scf_is_case_config_key — Method
scf_is_case_config_key(key) -> Bool

Whether a dotted configuration key describes the CASE (its model, import conventions, solver, estimation, and short-circuit math) rather than the installation. Only case-scope keys travel inside a case file; everything else stays in the configuration file. The key must also be GUI-editable, which is the same allowlist every other configuration surface uses.

source
Sparlectra.build_net — Method
build_net(case::SCFCase; config = active_sparlectra_config()) -> Net

The one network constructor of the run path over the typed case: construct through the existing public constructors, then apply the run configuration's net parameters exactly once, here. config is the EFFECTIVE run configuration (the run path passes its resolved ImportedCase configuration; interactive use takes the active one).

System frequency: meta.f_nom of the file sets net.nominal_frequency_hz; a file without it takes model.nominal_frequency_hz of config. When the user set that key explicitly and it differs from the file, the file wins with one warning that names both values.

source
Sparlectra.importSCF — Method
importSCF(file) -> Net

Read a Sparlectra Case Format file (.scf.json, issue #342) and build the network through the existing constructors. Validation is staged: schema (unknown keys and unsupported components are hard errors), reference integrity (every id resolves, ids are unique), then the model checks validate! already performs. Wrapper over read_scf_json and build_net with the active configuration.

source
Sparlectra.scf_case_config — Method
scf_case_config(file) -> Dict{String,Any}

The dotted configuration keys a case file carries in sparlectra.config, ready to be merged as config_overrides (the case file sits below API/CLI overrides and above the YAML file in precedence). Empty when the file carries no configuration.

source
Sparlectra.scf_case_studies — Method
scf_case_studies(file) -> NamedTuple

The study definitions a case file carries: (short_circuit,), an empty dictionary when the file does not define that study. The block states WHAT to compute; the result contract of the run itself is unchanged. Contingency studies live in the scenarios block (scf_case_scenarios); a file that still carries the contingencies block removed in 0.40.0 fails here with a message naming the replacement.

source
Sparlectra.scf_extra_names — Method
scf_extra_names(file) -> Dict{Int,String}

The reference name of every component id in a case file, taken from sparlectra.extra. Study blocks address components by id, so a runner that executes a study from the file resolves the ids through this map: the names are exactly the ones the network object uses, which is what makes a case list from the file addressable in the runner.

source
Sparlectra.scf_fault_nodes — Method
scf_fault_nodes(file) -> Vector{Int}

The node ids a case file's data.fault rows point at, in file order. PGM expresses "evaluate the fault here" with a fault component; a short-circuit run uses these buses when the study block does not name its own selection, so a case written in PGM vocabulary is runnable as it stands.

source
Sparlectra.scf_to_net — Method
scf_to_net(root::AbstractDict) -> Net

Build a Net from a parsed SCF root object. Every element is created through the existing public constructors and the network is validated with validate! at the end, so an SCF case behaves exactly like a case from any other importer. The document is converted to its typed form (SCFCase) first; this wrapper keeps the historical dict entry point and applies NO configuration (callers that want the run-path behavior use build_net); only a file without meta.f_nom takes the active model.nominal_frequency_hz as its system frequency.

source
Sparlectra.scf_validate_dataset — Method
scf_validate_dataset(root) -> Nothing

Run the file-level validation of a parsed case file: schema, study definitions, reference integrity. Throws ArgumentError with the offending key or id, and returns nothing when the document is a usable case file.

This is the check without building a network, which is what an upload path needs: an arbitrary JSON must be rejected BEFORE it is stored, and the user should see the reader's own message rather than a generic refusal.

source
Sparlectra.DTFImporter — Module

Importer for the native DTF (FOR001) format: parser, network construction and the outage bookkeeping of that format.

source
Sparlectra.DTFImporter.build_net — Method
build_net(case; bus_shunt_model = :admittance) -> Net

Build a Sparlectra Net from a parsed native DTF case. Branch R/X/G/B are converted with the branch voltage-level index as reference voltage, not with the from-side bus voltage. Outages remain parsed metadata and are not executed by this Task-1 MVP.

tap_changer_model selects the tap-changer model applied to all transformers (model.tap_changer_model in the central configuration; nothing reads the active configuration). :ideal keeps the neutral-position series impedance; :impedance_correction re-refers R/X through the tapped winding via the central calcTapCorrectedRX using the parsed regulating vector 1 + f·e^(jφ).

source
Sparlectra.DTFImporter.is_dtf_deck — Method
is_dtf_deck(path) -> Bool

Whether the file is a DTF network deck, judged by the reader itself: true when read_dtf takes the file and what it read is a network (the size card counts at least one bus and one branch, every counted card was there, and one of the bus cards is the slack bus). There is no second description of the format: a file the importer reads is a deck, and a file it does not read is none. A result report (FOR002), an outage list without a network and any other text fail in the reader.

source
Sparlectra.DTFImporter.read_dtf — Method
read_dtf(path; baseMVA = 100.0, strict = true) -> DTFCase

Read a legacy DTF fixed-column input file into a typed DTFCase. This MVP parses outage cards into DTFOutage records but intentionally does not execute outage simulations.

source
Sparlectra.MatpowerIO.build_ybus_matpower — Method
build_ybus_matpower(bus, branch, baseMVA) -> SparseMatrixCSC{ComplexF64,Int}

MATPOWER-style Ybus stamping (π-model + tap/shift + bus shunts):

  • series r/x
  • line charging b split as b/2 on each end
  • off-nominal tap ratio and phase shift on from-side
  • bus shunts GS/BS added on diagonal: (GS + j*BS)/baseMVA

Optional matpower_shift_sign and matpower_shift_unit convert branch SHIFT before stamping. matpower_ratio controls whether branch TAP is used as stored ("normal", default) or inverted first ("reciprocal"). Defaults preserve MATPOWER degrees/from-side semantics.

source
Sparlectra.MatpowerIO.read_case — Method
read_case(path::AbstractString; legacy_compat::Bool=true) -> MatpowerCase

Dispatches based on file extension:

  • .m => read_case_m
  • .jl => read_case_julia (expects file returns MatpowerCase or NamedTuple)
source
Sparlectra.MatpowerIO.read_case_julia — Method
read_case_julia(path::AbstractString; legacy_compat::Bool=true) -> MatpowerCase

The .jl file should either: (A) return a MatpowerCase, OR (B) return a NamedTuple with fields: baseMVA, bus, gen, branch and optional gencost, bus_name, name.

source
Sparlectra.MatpowerIO.read_case_m — Method
read_case_m(path::AbstractString; legacy_compat::Bool=true) -> MatpowerCase

Best-effort parser for typical MATPOWER case files (*.m). Parses:

  • mpc.baseMVA
  • mpc.bus
  • mpc.gen
  • mpc.branch
  • optional: mpc.gencost
  • optional: mpc.bus_name
source
Sparlectra.MatpowerIO.vmva_power_mismatch_stats — Method
vmva_power_mismatch_stats(mpc::MatpowerCase) -> NamedTuple

Checks whether mpc.bus[:, 8:9] (VM/VA) are internally consistent with MATPOWER power balance equations for this case data.

Important PF semantics:

  • Active-power equation is enforced for PQ/PV buses (not slack).
  • Reactive-power equation is enforced for PQ buses only.

Returns maxima of residuals in p.u. and MW/MVar for those enforced equation sets, plus equation counts.

source
Sparlectra.FetchMatpowerCase — Module

Utilities for downloading MATPOWER-compatible case files on demand.

Note:

  • Downloaded files are stored locally and are not part of the Sparlectra source distribution.
  • Users are responsible for complying with the license terms of the respective upstream sources.
source
Sparlectra.FetchMatpowerCase.emit_julia_case — Method
emit_julia_case(mfile, outdir; legacy_compat=true, overwrite=false) -> jlfile::String

Parses a MATPOWER .m case and writes a Julia NamedTuple (.jl) compatible with MatpowerIO.readcasejulia().

source
Sparlectra.FetchMatpowerCase.ensure_casefile — Method
ensure_casefile(casefile; outdir=nothing, overwrite=false, to_jl=true) -> String

Ensure a MATPOWER-compatible case file exists locally.

  • If casefile is an existing path, it is returned unchanged.
  • If casefile is a bare filename (e.g. case14.m), it is downloaded into outdir.
  • If casefile ends with .jl and is missing, the corresponding .m is downloaded and .jl is generated.

Returns the local path to the requested case file.

source
Sparlectra.FetchMatpowerCase.ensure_matpower_case — Method
ensure_matpower_case(; url, outdir, to_jl=true, overwrite=false, legacy_compat=true, verbose=true)
    -> (mfile::String, jlfile::Union{Nothing,String})

Ensures the MATPOWER .m file exists in outdir by downloading it if missing. Optionally emits a Julia NamedTuple case (.jl).

This is intended to be called from examples and other code.

source
Sparlectra.FetchMatpowerCase.fetch_matpower_case — Method
fetch_matpower_case(url, outdir; overwrite=false) -> mfile::String

Downloads a MATPOWER *.m file from url into outdir (unless already present). Returns the local path to the downloaded file.

Transient failures (raw.githubusercontent.com rate limits hit CI runners regularly) are retried three times with a short backoff before giving up.

source
Sparlectra.FetchMatpowerCase.large_cases_dir — Method
large_cases_dir() -> String

The shared directory for large MATPOWER and DTF cases, resolved in two steps:

  1. SPARLECTRA_LARGE_CASES_DIR, if set (override for CI and special setups)
  2. otherwise the Web UI user case directory (~/.local/state/sparlectra/webui/data/mpower on Linux, %LOCALAPPDATA%\Sparlectra\WebUI\data\mpower on Windows)

ensure_casefile downloads here, the Web UI keeps its imported cases here, and the test suite reads large cases from here, so a case fetched once is available to all three and one variable moves the location for all of them.

This function only resolves a path. It does not write, and it does not create the directory; callers that need it to exist say so themselves.

It is deliberately not the checkout. Downloading used to write into <repo>/data/mpower, where the test suite gates several legs on files being present: having used the package decided how many assertions the suite ran, 7180 against 7121 on a fresh tree, and nothing said so.

source

Internals

Sparlectra.import_net — Method
import_net(::DTFAdapter, case, opts::DTFAdapterOptions) -> Net

The DTF importer of the adapter contract: builds the network DIRECTLY through DTFImporter.build_net; the adapter options carry every model knob the build takes.

source
Sparlectra.import_net — Method
import_net(::MatpowerAdapter, mpc, opts::MatpowerAdapterOptions; kwargs...) -> Net

The MATPOWER importer of the adapter contract: builds the network DIRECTLY from the parsed case; createNetFromMatPowerCase is its implementation and keeps its exported name and signature. The opts cover the adapter scope; run-scope knobs (bus shunt model, flatstart, cooldown, preallocation) ride through as keywords exactly as the import dispatch passes them.

source
Sparlectra.detect — Method
detect(::Type{PGMAdapter}, path) -> Bool

A .json file with the PGM dataset markers in its first 4 KiB. An SCF case matches too, because the canonical writer sorts the namespaced block to the end of the file, beyond any bounded probe: the registry resolves that tie by probing SCF FIRST (SCF detection keeps precedence), and both formats run the same parse and build pipeline, so the tie costs correctness nothing; the format label is refined at parse time by the presence of the sparlectra key.

source
Sparlectra.import_net — Method
import_net(::PGMAdapter, path::AbstractString, opts::PGMAdapterOptions; config = active_sparlectra_config()) -> Net

The PGM importer of the adapter contract: a plain power-grid-model dataset reads through the shared SCF reader (the SCF data section IS a PGM dataset) and builds directly through build_net.

source
Sparlectra._import_powsybl — Method
_import_powsybl(path, opts; name) -> (net, report, tables)

The one import path behind import_net and import_case: read the tables of the source, build the network.

source
Sparlectra._powsybl_tables_of — Method
_powsybl_tables_of(path) -> PowsyblTables

The tables of a PowSyBl source: a .powsybl bundle directory reads through read_powsybl_bundle, an IIDM file (.xiidm, .xml) through the native reader read_iidm_tables, in Julia without Python.

source
Sparlectra.detect — Method
detect(::Type{PowsyblAdapter}, path) -> Bool

A bundle directory whose name ends in .powsybl and whose manifest.json carries "format": "powsybl_tables" in its first 4 KiB, or a regular .xiidm, .xiidm.bz2 or .xml file whose first 4 KiB carry the IIDM namespace. Content based; the extension is a hint. Probed before the CGMES detection, which claims every directory and every .xml.

source
Sparlectra.import_net — Method
import_net(::PowsyblAdapter, path, opts; config = active_sparlectra_config()) -> Net

The PowSyBl importer of the adapter contract: a .powsybl bundle directory reads through read_powsybl_bundle, an IIDM file through the native read_iidm_tables; both build through build_net_from_powsybl. No Python is involved.

source
Sparlectra.POWSYBL_COLUMN_ALIASES — Constant
POWSYBL_COLUMN_ALIASES

Column renames between pypowsybl versions, per table: canonical name to the names older or newer releases used. Empty: pypowsybl 1.16.1 (the version the schema was verified on) renamed nothing. The reader maps an alias to its canonical name before the schema check.

source
Sparlectra.POWSYBL_SCHEMA — Constant
POWSYBL_SCHEMA

The bundle schema, keyed by the manifest table name (the pypowsybl getter name without get_): the columns the reader knows, in pypowsybl order, with type, index flag and required flag. Every table listed here must be present in a bundle, with at least its header line. Columns of a bundle that the schema does not list are read as String and carried along unchanged, so a newer pypowsybl adds nothing that breaks a read.

source
Sparlectra.POWSYBL_TABLE_NAMES — Constant
POWSYBL_TABLE_NAMES

The manifest table names in the order of the pypowsybl getters (and of the bundle files). tie_lines closes the list: the getter exists in pypowsybl 1.16.1 and pairs the dangling lines of a tie line.

source
Sparlectra.PowsyblColumn — Type
PowsyblColumn

One column of the bundle schema: its name, its element type (String, Float64, Int or Bool), whether it is an index column of the pypowsybl table, and whether the network builder reads it (required). A column the builder never reads is read when present and ignored when absent; a required column that is missing fails the bundle read.

source
Sparlectra.powsybl_empty_table — Method
powsybl_empty_table(name) -> NamedTuple

An empty table with every schema column of name (required and optional), in schema order, with typed empty vectors.

source
Sparlectra.powsybl_table_rows — Method
powsybl_table_rows(table::NamedTuple) -> Int

The row count of a table: the length of its first column, 0 for a table without columns.

source
Sparlectra.read_iidm_tables — Method
read_iidm_tables(path; case = "") -> PowsyblTables

Read an IIDM XML file into PowSyBl tables without Python. case names the network in the manifest (default: the file name without extension). Fails with an ArgumentError naming the construct on a compressed file (.bz2, .gz; unpack it first), on an XML file that is not an IIDM network, and on the tie-line form of IIDM versions before 1.10 (the two half lines inline); every other IIDM 1.x construct the builder reads is mapped, unknown elements are ignored, and of the extensions the generator short-circuit data (generatorShortCircuit) is read.

source
Sparlectra.ImportedCase — Type
ImportedCase

What one case import hands to a service run:

  • net: the constructed network, configuration parameters stamped.
  • config: the effective run configuration AFTER the import. It can differ from the general configuration that went in: the MATPOWER path may apply an auto profile and a projected start, the CGMES path resolves cgmes_import.start_values against the delivery it actually read.
  • format: the detected (or requested) case format.
  • provenance: source path, per-format import records (the CGMES import result with its short-circuit data and SV bookkeeping, the parsed DTF case, the auto-profile decision), for the artifacts a service writes.
  • studies: the study definitions a case file carries (short_circuit); empty for every foreign format. Scenarios and contingency studies are read from the typed case (scf_case_scenarios), not from here.
  • overrides: reserved for auto-profile recommendations as override level; empty while the MATPOWER context still rewrites the run configuration itself.
source
Sparlectra._case_file_lead — Method
_case_file_lead(case_path; nbytes = 4096) -> String

The first non-blank bytes of a case file, at most nbytes, with a UTF-8 byte order mark removed. Empty for a directory, a missing file or an empty file. This is what format decisions look at: the extension is only a hint, the content is the evidence. The bytes are not required to be valid UTF-8 (a MATPOWER comment in a Windows code page must not break detection).

source
Sparlectra._case_format_conflict — Method
_case_format_conflict(case_path, requested) -> Union{Nothing,String}

The reason an explicitly requested case format cannot apply to case_path, or nothing when file and format agree. The verdict comes from the CONTENT, not from the extension: a requested :scf needs a file that opens with a JSON object, a requested :matpower one that does not (no MATPOWER reader takes JSON). :cgmes and :dtf_for001 are left alone on purpose, they cover directories, ZIPs and the ambiguous .DAT files whose whole point is the explicit choice. A missing file gets no verdict here; the reader names it.

Found in practice: a per-case setting case_format = scf saved for sp_case118.m sent the MATPOWER file into the SCF reader, which reported SCF JSON parse error at byte 1: invalid integer "" (byte 1 is the f of function mpc), a message that blames a JSON file nobody was reading. The message here names the file, what it actually starts with, and the way out.

source
Sparlectra._import_cgmes — Method
_import_cgmes(path, cfg; name, phase_callback) -> NamedTuple

The one CGMES import of the run path: delivery-path resolution, the configured import, and the cgmes_import.start_values decision, which belongs to the import because auto can only resolve against the delivery that was actually read (does it carry a usable SvVoltage state or not). Returns the import result, the run configuration with the start decision applied, and the records the service artifacts need. Import errors propagate; the caller owns the failure reporting (the power-flow service writes a diagnostic cgmesimportreport.md from what can still be read).

source
Sparlectra.import_case — Method
import_case(path, general_config; requested_format, name, performance_profile, phase_callback) -> ImportedCase

Import a case of any format for a service run. Detection follows _detect_case_format unless requested_format names the format explicitly. Construction goes through the same per-format paths the power-flow service used, so every service gets the identical network for the identical file: the shared context for MATPOWER and the case format (auto profile, projected start, configuration stamping), the configured CGMES import with the start-values decision, and the DTF build with its DC-line rejection.

An SCF time series (:scf_series) imports as its base case, with the units the base case parks parked (build_net(series)); the steps are not applied.

Format policy stays with the caller: a service that does not accept a format checks ImportedCase.format and words its own refusal, because the wording of those refusals is part of each service's contract.

source
Sparlectra._matpower_sparlectra_tap_changer_model_marker — Method
_matpower_sparlectra_tap_changer_model_marker(mpc) -> Union{Nothing,String}

Read the optional mpc.sparlectra.tap_changer_model roundtrip marker written by writeMatpowerCasefile. When it is "impedance_correction", the exported BR_R/BR_X values already carry the tap-impedance correction, so createNetFromMatPowerCase must not reapply calcTapCorrectedRX on reimport (that would stack a second, differently-derived correction factor on top of the already-corrected values). Absent the marker, import behavior is unchanged so standard third-party MATPOWER cases are unaffected.

source
Sparlectra.createNetFromMatPowerCase — Method
createNetFromMatPowerCase(; mpc, log=false, flatstart=false, kwargs...) -> Net

Builds a Sparlectra Net from an already parsed MATPOWER case object mpc. This is the construction core behind createNetFromMatPowerFile: bus, branch, generator and shunt import, PQ generator controllers, and the MATPOWER convention switches below. flatstart is stored as the start mode of the net: the solver then starts from 1 pu and the slack angle (see initialVrect) instead of the case VM/VA, keeping the reference bus voltage and the PV voltage magnitudes. profile collects per-stage import timings when given. Throws on inconsistent case data.

mpc can be either:

  • a MatpowerIO.MatpowerCase as MatpowerIO.read_case returns
  • or a NamedTuple (or any struct) with the fields baseMVA, bus, gen, branch; name is optional (default "mpc"), and an optional bus_name vector names the buses when apply_bus_names = true

All matrices are expected in MATPOWER v2 column conventions.

bus_shunt_model controls how MATPOWER bus Gs/Bs values are represented: "admittance" stamps them into Ybus (default), while "voltage_dependent_injection" keeps them out of Ybus and evaluates their |V|²-dependent contribution in the rectangular mismatch path.

matpower_shift_sign and matpower_shift_unit control how MATPOWER branch SHIFT values are converted before they are stored as Sparlectra transformer phase shifts. Defaults preserve MATPOWER convention: SHIFT is in degrees, positive on the branch from side. PEGASE-style data sets may require matpower_shift_unit = "rad" and/or matpower_shift_sign = -1.

matpower_ratio controls MATPOWER branch TAP import. The default "normal" uses the TAP value directly (with MATPOWER 0 treated as 1). Set matpower_ratio = "reciprocal" when an input data set stores the inverse tap ratio expected by Sparlectra.

tap_changer_model selects the tap-changer model applied to all transformers (model.tap_changer_model in the central configuration). :ideal (default) keeps the imported series impedance unchanged; :impedance_correction re-refers R/X through the tapped winding via calcTapCorrectedRX, interpreting the effective off-nominal tap ratio as the tap deviation of the tapped winding.

source
Sparlectra.writeCostData — Method
writeCostData(file, gens)

Write mpc.gencost for the generator rows just written (gens, one entry per mpc.gen row in its order, nothing for a row the exporter added itself, such as the synthetic slack generator). The P rows come first, the Q rows of the same units after them (MATPOWER layout), each row as imported and padded with zeros to the widest row.

No block is written when no generator carries cost data. When only some do (a generator added in Sparlectra, a synthetic row), a warning names the units without a row and no block is written: a partial matrix would assign the rows to the wrong generators. Q rows are written only when every unit has one; otherwise a warning says the Q costs are left out.

source
Sparlectra._print_timing_coverage — Method
_print_timing_coverage(io, profile; level=:compact)

Print coverage diagnostics that compare representative wall time against recorded phase timings and benchmark-event totals.

source
Sparlectra._record_perf! — Method
_record_perf!(profile, label, seconds)

Append a benchmark/performance event to profile[:events] when a mutable profile dictionary is available.

source
Sparlectra._run_matpower_single — Method
_run_matpower_single(local_case, cfg, profile, status_ref)

Run one MATPOWER power-flow solve and update status_ref with elapsed-time and result-output timing metadata.

source
Sparlectra._sum_perf_timings — Method
_sum_perf_timings(profile; top_level_only=false)

Return accumulated timing seconds from profile[:timings].

When top_level_only=true, only major runner phases are included so coverage can be compared against representative wall time.

source
Sparlectra.benchmark_trial_seconds — Function
benchmark_trial_seconds(f; samples, seconds) -> (median_s, min_s)

Repeated timing of f() with BenchmarkTools: median and minimum of the trial in seconds. The method comes with the package extension SparlectraBenchmarkToolsExt, which Julia loads once BenchmarkTools is loaded next to Sparlectra (using BenchmarkTools). Sparlectra does not depend on BenchmarkTools, so an installation does not compile it and the packages it brings.

source
Sparlectra.print_performance_profile — Method
print_performance_profile(io, profile; ...)

Render a human-readable performance report from the MATPOWER runner profile.

Supports compact and full output levels, optional allocation columns, and optional iteration diagnostics.

source
Sparlectra.print_runtime_thread_config — Method
print_runtime_thread_config(io, status)

Print runtime thread request/active/apply status, including startup guidance when Julia thread requests cannot be applied in-process.

source
Sparlectra.run_with_output_capture — Method
run_with_output_capture(f; capture_stdout=true, capture_stderr=true)

Run f() with redirected stdio and return (result, stdout, stderr).

Used by the runner to isolate diagnostic output for logfile routing.

source
Sparlectra.write_matpower_import_auto_profile — Method
write_matpower_import_auto_profile(io, auto_profile_result, cfg; casefile)

Report the import-convention analysis, at the verbosity output.console_auto_profile asks for. That setting existed with values :off, :compact (the default) and :full but was read by nobody, so every run printed the full block: about seventy console lines for a case where every single check said "keep". A study tool should not narrate its importer that loudly, least of all in another product's vocabulary.

  • :off prints nothing.
  • :compact prints only the rows that actually RECOMMEND a change, plus one line saying how many checks were made and kept.
  • :full prints the original block: option list before, recommendation table, and effective options after.
source
Sparlectra.SCFData — Type
SCFData

The PGM-compatible data section of one SCF document as typed component vectors (no stringly-typed row access on the build path). A component key is written to the file exactly when its vector is non-empty, which is the writer's behavior for every revision so far.

source
Sparlectra.SCFSparlectra — Type
SCFSparlectra

The namespaced sparlectra block of one SCF document. roles, components and start_state are typed (the adapters construct them); the genuinely free-form sub-objects (per-id extra records, controller declarations, study definitions, measurement rows) stay dictionaries and every consumer addresses them by key. meta, roles and extra are always written; every other block only when non-empty, exactly like the writer.

source
Sparlectra.scf_root_dict — Method
scf_root_dict(case::SCFCase) -> Dict{String,Any}

The document form of a typed case, ready for scf_json_string. Component keys appear exactly when their vector is non-empty; the namespaced block writes meta, roles and extra always and every other sub-block only when non-empty, matching the writer's shape.

source
Sparlectra.scfcase_from_root — Method
scfcase_from_root(root::AbstractDict) -> SCFCase

Convert a parsed (and validated) SCF root object into its typed form. The converter mirrors the reader's field vocabulary exactly; unknown row fields of a foreign PGM file are dropped here, which is the documented scope of the round-trip contract (it covers files Sparlectra wrote).

source
Sparlectra._scf_apply_controllers! — Method
_scf_apply_controllers!(net, entries; branch_by_name)

Instantiate the case file's controllers on net. The entries are the declarative control.controllers schema, so they go through applyConfiguredControllers! unchanged: one construction path, one validation, one vocabulary. branch_by_name maps the file's branch names (extra block) to built branch indices, so a trafo/followers reference resolves to the branch of that id even where several branches share the name. Other references (index strings, component ids) are passed through untouched.

source
Sparlectra._scf_branch_vn — Method
_scf_branch_vn(net, branch) -> Float64

Voltage base of a branch's impedance in kV. Sparlectra stamps the tap on the FROM side (ui /= tap in the Y-bus), so r_pu/x_pu are referenced to the TO side, which is exactly PGM's generic_branch convention.

source
Sparlectra._scf_bus_name — Method
_scf_bus_name(net, i) -> String

The REFERENCE name of a bus: the busDict key. That is the name measurements, controllers, scenarios, and reports resolve against, and the name the reader has to restore. Since 0.50.0 addBus! gives the node that name as its component name; a component name that differs (the schematic "Bus1110" read from an older file) is kept separately in extra.component_name.

source
Sparlectra._scf_cgmes_mrids — Method
_scf_cgmes_mrids(net) -> (buses, branches, links)

Resolve the CGMES mRIDs of a delivery-sourced net by their structural keys (TN|<bus>, ACL|<a>|<b>|<k>, PT|<a>|<b>|<k>, EQB|<a>|<b>|<k>, EQBT|<a>|<b>|<k>, SW|...), so external_id carries the source-system identity instead of the internal component id. Empty dictionaries on nets from other formats.

source
Sparlectra._scf_faults — Method
_scf_faults(net, ids, buses) -> Vector

The buses a short-circuit study evaluates, in PGM's own fault vocabulary (fault_object, fault_type, r_f/x_f). Sparlectra computes the balanced three-phase bolted fault, so the rows state exactly that; the block is only written when a study names buses, and it is the PGM-readable twin of short_circuit.buses.

source
Sparlectra._scf_sc_sources — Method
_scf_sc_sources(net, ids) -> Vector

Short-circuit source data (IEC 60909 feeders and machines) as a sparlectra.components.sc_source list. The data is stored on the net by the CGMES importer and by addExternalGrid!; PGM's source component carries only sk/rx_ratio, so the full set travels here and stays lossless.

source
Sparlectra._scf_shunt_state — Method
_scf_shunt_state(net, ids) -> Vector

Per-shunt state that PGM's shunt (g1/b1 only) has no slot for: whether the shunt is in service, which model it uses (a voltage-dependent injection is NOT an admittance), and whether its susceptance is released as a state-estimation state. Only shunts that deviate from the defaults produce a row, so an ordinary case file stays free of noise.

source
Sparlectra._scf_stable — Method
_scf_stable(pu, to_si, to_pu) -> Float64

Return the SI number to WRITE for the per-unit value pu: the one that the reader turns back into exactly pu. to_si is this writer's conversion, to_pu the reader's.

Unit conversion is not exactly invertible in floating point, and the naive value cost both guarantees at once: the re-read network differed in the last bit (so the Y-bus was not bit-identical), and the next export wrote that neighbour, so a file could drift on EVERY cycle instead of being a fixed point (seen on case14/case118/case300). Checking the two neighbouring floats finds an exact preimage in practice; if none exists, the value that maps to itself keeps at least the byte-identical round trip. The correction is at most one ulp.

source
Sparlectra._scf_stable_step — Method
_scf_stable_step(pos, base, step) -> Int

The band position to WRITE. The reader rebuilds the ratio edge as base / (1 + pos * step), and a second export derives the position from that edge again. Rounding can land on the other side of a tie there, so the file would not be a fixed point (measured on case13659pegase: 6674 branches moved their band edge by one step on re-export). Pick the neighbour that reproduces itself; the ratio edge stays within the documented one-step snap either way.

source
Sparlectra._scf_transformer3w — Method
_scf_transformer3w(net, ids) -> Vector

Group the three star legs of a three-winding transformer. Sparlectra builds the same star equivalent PGM documents for generic_branch: three legs and one auxiliary star node. The electrical parameters therefore live exactly once, in data.generic_branch; this block only says which three branches belong together, which node is their star point, and which end is which.

Leg direction is Sparlectra's own: from_node is usually the star node and to_node the terminal, a leg with its tap at the terminal runs the other way (leg_direction says which), and each end names both explicitly, so no reader has to guess an orientation.

source
Sparlectra.scf_id_map — Method
scf_id_map(net; controller_shunts = false) -> ScfIdMap

Assign SCF ids deterministically: components are walked in a fixed type order and, inside a type, in lexicographic name order (ties broken by the internal index). Rebuilding the same net therefore produces the same ids and the same file bytes.

A shunt owned by a shunt voltage controller gets no id and is not written: the controller entry recreates it. controller_shunts = true (the strict PGM writer, which drops the controllers) writes it as a plain shunt with its present susceptance.

source
Sparlectra._scf_measurement_provenance — Method
_scf_measurement_provenance(file) -> Dict{String,Any}

What a case file records about its own measurement set (sparlectra. measurements.provenance): whether the values carry noise, which generator and seed produced them, the per-row truth values, and the tap deviations the generator applied. Empty for a case without measurements, without a provenance block, or for anything that is not an SCF file, so callers can ask unconditionally.

source
Sparlectra._scf_require_current_revision — Method
_scf_require_current_revision(spar)

The revision decides whether this reader understands the file at all. Backward compatibility across revisions is not promised while the format is young, so a file from another revision is refused BY NAME instead of being read with today's meaning. Every reader that feeds a RUN goes through this: the full import, and the config/studies accessors that are consulted before the import. A file written by power-grid-model has no namespaced block and never reaches the check; the display-only readers (measurement provenance, source reference) stay lenient on purpose, so a stale file still renders enough for the user to select it and be told to re-export.

source
Sparlectra._scf_source_reference — Method
_scf_source_reference(file) -> String

The case file the SCF case was exported from (sparlectra.meta. source_reference), empty when unknown. It is what lets a run tell a set generated for the SOURCE case apart from a genuinely foreign one.

source
Sparlectra.nominal_frequency_line — Method
nominal_frequency_line(case::SCFCase, config::SparlectraConfig) -> String

The run header line of nominal_frequency_line(net) for a case before it is built (the base case of a QSTS series).

source
Sparlectra.nominal_frequency_source — Method
nominal_frequency_source(case::SCFCase, config::SparlectraConfig) -> String

nominal_frequency_source(net) for a case before it is built, for example the base case of a QSTS series: the same answer the network build_net(case; config) returns would give.

source
Sparlectra.scf_case_units — Method
scf_case_units(case::SCFCase) -> Symbol

The declared unit system of the electrical parameters: :pu or :si. An ABSENT declaration means :si, which is what every file before the declaration meant, so existing files read unchanged. Unknown values are a hard error. For :pu the conversion base must be complete: meta.s_base (VA, positive and finite) and a positive finite u_rated on every node; per-unit numbers without their base are not interpretable, so a missing piece is a hard error naming the field. build_net reads the branch and shunt parameters of a :pu file from the pu block of their sparlectra.extra entry.

source
Sparlectra.scf_node_ids_in_build_order — Method
scf_node_ids_in_build_order(case) -> Vector{Int}

The file node ids in the order build_net creates the buses (recorded extra.bus_index, id as the tie break), so a consumer can map net node index k to its file id, for example to look up the raw start values of start_state.

source
Sparlectra._scf_json_write — Method
_scf_json_write(io, value; indent = 0, key_order = nothing)

Write value as pretty JSON: objects and the objects inside a list break one key per line. Only a vector of plain scalars stays inline ([1, 2, 3]), because breaking a list of node ids over twenty lines helps nobody.

Component rows used to be written as ONE compact line each, which kept diffs narrow but read like a stream of data rather than a document. The expanded form is what JSON tooling produces and what a reader expects; a diff now points at the changed FIELD instead of the changed component.

source
Sparlectra.scf_infinity_sentinel — Method
scf_infinity_sentinel(value) -> value

Encode a possibly non-finite nameplate number for the namespaced sparlectra block. JSON cannot carry Inf, and an unlimited rating is real data (MATPOWER writes rateA = 0 for "no limit", which arrives as Inf), so it travels as the string "inf" / "-inf" and comes back as a number on read. Finite values pass through unchanged. The PGM data section never uses this: a value it cannot express is omitted there.

source
Sparlectra.scf_json_parse — Method
scf_json_parse(text) -> Dict{String,Any}

Parse an SCF case file. Object keys become String, integers stay Int (component ids), numbers with a fraction or exponent become Float64. The one exception is value and sigma of sparlectra.measurements.rows: a literal with more than 17 significant digits there stays a ScfDecimalText (its text and its Float64), so the row reader can divide a U value in kV at 256 bits and the writer prints it back unchanged. A leading UTF-8 byte order mark is skipped (Windows editors write one; the export never does), everything else outside the JSON grammar is an error.

source
Sparlectra.scf_json_string — Method
scf_json_string(root::AbstractDict) -> String

Serialize an SCF root object to its canonical text form (trailing newline included). Deterministic: the same object always produces the same bytes.

source
Sparlectra.MatpowerIO._normalize_pv_voltage_source — Method
compare_vm_va(net, mpc; show_diff=false, tol_vm=1e-6, tol_va=1e-4, maxlines=20)

Compare net results (node.vmpu/vadeg) against MATPOWER reference (mpc.bus VM/VA). Skips isolated buses (BUS_TYPE==4) by default. Returns (ok::Bool, stats::NamedTuple).

source
Sparlectra.MatpowerIO.apply_matpower_bus_voltage! — Method
apply_matpower_bus_voltage!(net, mpc; flatstart, verbose=0)

Policy:

  • flatstart=true -> do NOT write bus VM/VA into net (true flat start)
  • flatstart=false -> write bus VM/VA as initial guess (only if node has no meaningful voltage yet)

Never warn; debug-only on conflicts.

source
Sparlectra.MatpowerIO.legacy_sort_bus — Method
legacy_sort_bus(mpc::MatpowerCase) -> MatpowerCase

Mimics the legacy casefileparser behavior:

  • Sorts bus rows by BUS_I (column 1) ascending.
  • Does NOT reorder gen or branch.

This keeps results compatible with the old importer.

source
Sparlectra.MatpowerIO.normalize_branch_tap! — Method
normalize_branch_tap!(branch)

MATPOWER semantics:

  • column 9 (TAP) == 0 means "no transformer tap specified" and is treated electrically as 1.0 by Y-bus stamping and import code.

This helper is kept for callers that explicitly want normalized data, but read_case preserves raw TAP values so import code can tell TAP == 1 between two voltage levels (a transformer with ratio 1) from TAP == 0.

source