Contingency Reference

Public API

Sparlectra.ContingencyNames — Type
ContingencyNames

Display names of the outage elements of one network, by internal index. branch_raw, gen_raw and link_raw hold the display name of every branch, prosumer and bus link (the file name of an SCF case where the file names the component, the generated component name otherwise); a prosumer that is no generator carries an empty name. branch, gen and link hold the element strings contingency output uses: the display name where it is unique within its class, "<name>#<index>" where it is not (parallel circuits share a generated name, and file names need not be unique either). The *_by_element dictionaries resolve an element string back to its index. bus is the bus name per bus index.

Build it with contingency_names.

source
Sparlectra.contingency_names — Method
contingency_names(net) -> ContingencyNames
contingency_names(net, index::ScenarioIndex) -> ContingencyNames
contingency_names(net, case::SCFCase) -> ContingencyNames

The display names of the outage elements of net. Without a case the generated component names are used (MATPOWER, CGMES and PowSyBl cases, programmatic nets). With the ScenarioIndex or the SCFCase the net was built from, every component the file names gets its file name (sparlectra.extra[<id>].name); the rest keep the generated name. Element strings that are not unique carry #<index>. Every case generator, both batch entries and the service use this one map.

source
Sparlectra.ContingencyCase — Type
ContingencyCase

One contingency to evaluate: the outage of a single network element or of a group of elements that trip together (a correlated event, an N-2 pair).

Fields

  • name::String: display name of the case (defaults to the element name).
  • kind::Symbol: what the case is (one vocabulary with Scenario and ContingencyResult):
    • single elements: :branch (a line or transformer), :gen (a generator), :transformer3w (a three-winding transformer as a whole: every leg of its star equivalent opens together), :link (a closed bus link, a busbar coupler);
    • correlated events: :double_circuit, :busbar, :substation, :name_group (see generateCorrelatedEvents);
    • :explicit for a hand-written group, :pair for an N-2 pair (generateBranchPairs).
  • elements::Vector{String}: the outaged elements as element strings of contingency_names: a branch, generator or link name, with "#<index>" where the name is not unique. A single-element kind carries exactly one entry; for :transformer3w it is the name of the transformer's star-point bus. The members of a group are resolved against branches, links and generators in that order; a string that names more than one of them is reported as a failed case.
  • weight::Float64: a per-case importance/probability weight (default 1.0), carried through to the ContingencyResult so a weighted ranking can read it. Set it via the constructor, or attach outage rates in bulk with applyContingencyWeights / readContingencyWeightsCSV. A weight of 0 is a pure ranking weight, NOT a skip switch: the case is still solved and reported, and only a weighted ranking neutralizes it. To leave an outage out of the batch entirely, drop it at generation time with the generator filters.

Constructors: ContingencyCase(name, kind, elements::Vector{String}, weight = 1.0), the single-element shorthand ContingencyCase(name, kind, element::String, weight = 1.0), and ContingencyCase(element) for a branch outage named after its element.

source
Sparlectra.ContingencyResult — Type
ContingencyResult

Outcome of one ContingencyCase or Scenario evaluated by runContingencies! or runScenarios!.

Fields

  • name::String: the case name.
  • kind::Symbol: the case kind (see ContingencyCase; :explicit for a user scenario).
  • elements::Vector{String}: the outaged elements as element strings of contingency_names; a three-winding transformer lists its legs, a scenario every component its operations touch.
  • weight::Float64: the originating case's importance/probability weight (default 1.0), carried through unchanged for weighted ranking.
  • converged::Bool: whether the post-outage power flow converged.
  • iterations::Int: Newton iterations of the contingency solve (0 when the solve never ran; the sum across ladder stages that were attempted).
  • start_used::Symbol: the start-value ladder stage that converged (:warm, :apslf, :dc, or :flat), :none for a failed case; with the warm active set :warm_cold (the warm solve failed, the cold one counts) or :warm_cold_check (the cold check found a less favourable result).
  • max_vm_pu::Float64 / min_vm_pu::Float64: voltage envelope over the non-isolated buses of the solved case (NaN when not solved).
  • max_branch_loading_pct::Float64: maximum loading over all rated branches (|S| at either end against sn_MVA); NaN when the case did not solve or no branch carries a finite rating.
  • severity::Float64: a rankable severity, weight · max(0, max loading - 100) for a converged case (0 when nothing is overloaded), and NaN for a failed case so the failures sort to the TOP. This is what printContingencyResults ranks by, giving weight its consumer.
  • overloads::Vector{OverloadRecord}: the branches loaded above 100 percent, each with its loading and the delta to base, worst first.
  • voltage_violations::Vector{String}: bus names outside the [vm_min_pu, vm_max_pu] band.
  • island_count::Int: AC islands of the post-outage topology (0 when the net could not be evaluated).
  • shed_load_mw::Float64: load disconnected by islanding: the total load in reference-less islands of a failed case, the load at the buses the outage cut off in a case whose remaining network solved; 0.0 when the outage disconnects nothing.
  • error::Union{Nothing,String}: nothing on a clean success. A failure is named in one line ("islanded without reference", the solver status, or the exception message). A case that solved but cut off buses (the outage of a radial branch) carries the note "islanded: bus ... cut off, ..." and converged = true. Failures are REPORTED, never thrown.
source
Sparlectra.OverloadRecord — Type
OverloadRecord

One overloaded branch under a contingency, collected per case in ContingencyResult.overloads so a reporting consumer reads the numbers directly instead of parsing a string.

Fields

  • name::String: the branch component name.
  • loading_pct::Float64: post-contingency loading, 100 · s_MVA / sn_MVA.
  • loading_base_pct::Float64: the same branch's loading in the SOLVED base case (before the outage); NaN when the base did not converge or the branch was unrated at base. The reference that makes the post-outage value readable.
  • delta_pct::Float64: loading_pct - loading_base_pct (a jump from 40 % to 105 % is a very different event than 98 % to 105 %); NaN if the base is unknown.
  • s_MVA::Float64: post-contingency apparent power, max(|S_from|, |S_to|).
  • sn_MVA::Float64: the branch rating the loading is measured against.
source
Sparlectra.applyContingencyWeights — Method
applyContingencyWeights(cases, weights; default = 1.0, aliases = Dict()) -> Vector{ContingencyCase}

Return a copy of cases with each case's weight set from weights (an AbstractDict mapping case name to a non-negative number), looked up by case.name. Cases whose name is absent from weights get default. Useful to attach per-branch outage rates read with readContingencyWeightsCSV before calling runContingencies!; ContingencyCase is immutable, so this builds new cases rather than mutating in place.

aliases maps a case name to an older name of the same case (the generated name an SCF case carried before its file names were used, see contingency_names): a weight stored under the old name applies when none is stored under the current one.

source
Sparlectra.buildContingencyReport — Method
buildContingencyReport(results; top = 10) -> ContingencyReport

Summarize a runContingencies! batch: count cases by outcome, the total and worst load shed, the worst single branch loading across all cases, and the top branches overloaded by the most contingencies (ties broken by name).

source
Sparlectra.generateContingenciesFromFOR001 — Method
generateContingenciesFromFOR001(net::Net) -> Vector{ContingencyCase}

Map the FOR001 contingency branch names imported from MATPOWER metadata (mpc.for001_contingencies, stored on net.for001Contingencies) to ContingencyCases. Names that do not resolve to a branch are still listed; runContingencies! reports them as failed cases with an actionable error instead of dropping them silently.

source
Sparlectra.generateN1Branches — Method
generateN1Branches(net::Net; include_transformers = true,
                   min_vn_kV = 0.0, min_sn_MVA = 0.0, name_pattern = nothing,
                   three_winding_legs = false, names = contingency_names(net))
    -> Vector{ContingencyCase}

Generate one branch-outage ContingencyCase per in-service branch of net (aggregate status == 1; partially open branches are skipped, their outage is already half-effective). With include_transformers = false only AC-line branches are listed; a branch counts as a transformer when its component type is Trafo (net-builder path) or its winding ratio is nonzero (the classical MATPOWER indicator: line rows carry ratio = 0).

Optional screening filters keep only the outages worth simulating on a large grid (all default to "no filter"):

  • min_vn_kV: keep a branch only if the HIGHER of its two endpoint voltages is at least this value (so a step-down transformer touching the EHV level is kept). Screens N-1 down to the transmission grid.
  • min_sn_MVA: keep a branch only if it carries a finite sn_MVA rating of at least this value. Unrated branches are dropped when this filter is active.
  • name_pattern: keep a branch only if its display name matches this Regex or contains this substring.

Case names and elements come from names (contingency_names): the generated component names by default, the file names of an SCF case when its map is passed. A name shared by several branches (parallel circuits) carries "#<branch index>".

A three-winding transformer (a star equivalent: three legs meeting in an auxiliary star-point bus) trips as a whole: it gets ONE case of kind :transformer3w, named after the transformer, that opens all of its legs. Its legs are not listed one by one unless three_winding_legs = true. The screening filters apply to the transformer: it is kept when it counts as a transformer under include_transformers, its highest terminal voltage meets min_vn_kV, its largest leg rating meets min_sn_MVA, and its name matches name_pattern; it is listed while at least one leg is in service and closed.

source
Sparlectra.generateN1Generators — Method
generateN1Generators(net::Net; min_pg_MW = 0.0, name_pattern = nothing)
    -> Vector{ContingencyCase}

Generate one generator-outage ContingencyCase (kind = :gen) per in-service generator prosumer of net (isGenerator, i.e. an injection: a generator, external-grid feed-in, or synchronous machine). A generator outage removes ONLY that one unit's injection; the topology is unchanged, so the lost active power must be picked up by the slack (or, with distributed_slack_enabled = true on runContingencies!, shared over the surviving participants). Removing a bus's last voltage-regulating source demotes it to PQ; an island that lost its only reference takes its strongest remaining generating unit as reference (always, independent of auto_slack), and only a load-only island is reported as islanded.

Optional screening filters (default to "no filter"):

  • min_pg_MW: keep a generator only if |Pg| is at least this value (skips tiny or zero-output units).
  • name_pattern: keep names matching a Regex or containing a substring.

Generator names come from names (contingency_names) and are not unique (several units can share one name or bus); duplicates are disambiguated as "<name>#<prosumerIndex>".

source
Sparlectra.printContingencyResults — Method
printContingencyResults([io::IO], results::Vector{ContingencyResult}; max_rows = 50)

Print the contingency results as a fixed-width table (style of printShortCircuitResult): case, convergence, iterations, voltage envelope, worst loading, violation counts, shed load, weight, severity, and the error line for failed cases. Rows beyond max_rows are summarized in one line.

By default (sort_by = :severity) the rows are ranked so the failed cases come first and the converged cases follow by descending severity (weight · max(0, loading - 100)); this keeps the worst contingency on the first page of a long list. Pass sort_by = :none to keep the input order (the order writeContingencyResultsCSV always uses).

source
Sparlectra.readContingencyWeightsCSV — Method
readContingencyWeightsCSV(path) -> Dict{String,Float64}

Read per-case outage weights from a two-column CSV mapping case name to weight. The delimiter is auto-detected as ; or , (semicolon wins when both appear). A header line naming the columns (e.g. name;weight) is recognized and skipped; blank lines and lines beginning with # are ignored. Feed the result to applyContingencyWeights. Throws an ArgumentError on a malformed row or a negative / non-finite weight.

source
Sparlectra.runContingencies! — Method
runContingencies!(net::Net, cases::Vector{ContingencyCase};
                  vm_min_pu = 0.9, vm_max_pu = 1.1,
                  maxIte = 30, base_maxIte = 0, tol = 1e-8,
                  rescue_ladder = [:warm],
                  parallel_enabled = nothing, parallel_max_tasks = nothing,
                  parallel_min_work_items = nothing,
                  executor = nothing, max_processes = nothing,
                  progress = nothing,
                  kwargs...) -> Vector{ContingencyResult}

Evaluate outage contingencies. The base net is NEVER mutated: the batch runs on the scenario engine, which solves a template copy first (the warm start) and evaluates every case on a reusable working copy that is reset to the template afterwards. A case opens its branches (status and both terminals), removes its units, then solves and evaluates the [vm_min_pu, vm_max_pu] band plus branch loadings against sn_MVA ratings. Cases are returned in input order; failures (no convergence, islanding without reference, unknown element) are REPORTED in the result, never thrown.

maxIte is the iteration limit of every outage solve, base_maxIte the limit of the base-case solve (0: the same as maxIte); the service path passes contingency.max_iter and power_flow.max_iter.

rescue_ladder is the per-case start-value ladder (#331): an ordered, duplicate-free subset of (:warm, :apslf, :dc, :flat), default [:warm] (the pre-#331 single warm solve). Each stage is ONE bounded runpf! on the case-local net with a distinct start recipe, tried in order until one converges; the winning stage is reported as start_used:

  • :warm: the template (base-case) voltages;
  • :apslf: APSLF (AnalyticLoadFlow) start values;
  • :dc: flat magnitudes with DC-projected start angles;
  • :flat: flatstart = true.

The full solver rescue ladder (:settled_qlimits, :autodamp) is NOT used per case, only for the base case (below).

When the base case does not converge, it is retried through the solver rescue ladder (the strategies of runpf! with rescue = true, on the same keywords as the base solve) before falling back to a flat template with a warning. auto_slack (default true) hands the reference to the best remaining unit when an outage removes it, for the whole network and for an island that lost it: the stated reference priority first (ProSumer.referencePriority, 1 is the strongest), then reference_candidate_rank; the row then names the bus. With auto_slack = false such a case ends on the missing reference. Remaining kwargs... (distributed slack, Q-limit settings, ...) are forwarded to the base solve, its rescue and every ladder stage.

The batch fans out over Julia threads in runtime.parallel.max_tasks chunks or over the worker processes of start_batch_processes! (gated by runtime.parallel.*; the three parallel_* keywords, executor and max_processes override the active configuration; executor = :auto takes processes from 2000 buses on). Parallel and serial runs produce identical results.

progress (default nothing) is an optional callable invoked as progress(done::Int, total::Int) once after every finished outage, so a caller can show how far the batch is (the Web UI N-1 counter uses it). total is the number of cases; done counts every finished case, solved, screened or failed alike, and the base-case solve is not counted. Over one batch the callback sees each value of 1:total exactly once. On a parallel batch it is called from the worker threads, possibly at the same time and out of order (5 can arrive before 4), so it must be thread safe (take a lock around shared state, keep the maximum of done for a display) and should return quickly. An exception it throws ends the batch.

screening_mode / screening_margin_pct: :off (default, bit-identical to the pre-screening behavior) solves every case fully and returns Vector{ContingencyResult}; :flag estimates every non-islanding outage first on the base Jacobian factorization and fully solves only flagged cases; :only keeps the estimates. With screening active the return type is Vector{ScenarioResult} (screened marks rows whose metric columns carry estimates). The contingency.screening.* configuration (default :off as well) drives the service path.

warm_active_set (default true since 0.30.3) starts every outage from the base case's PV/PQ state. Where the limited solution is not unique this can end on another valid solution than the cold start. With warm_cold_check = true (default false) a converged warm result whose lowest voltage comes within warm_cold_check_margin_pu (default 0.02) of vm_min_pu, or that has an overload or a voltage violation, is solved a second time cold and the less favourable result counts (start_used = :warm_cold_check). See Warm active set.

names (contingency_names) resolves the case elements and names the result rows and overloads: the generated component names by default, the file names of an SCF case when its map is passed (the service does). A case of several elements (a correlated event, an N-2 pair) opens all of them in one solve.

source
Sparlectra.writeContingencyResultsCSV — Method
writeContingencyResultsCSV(path::AbstractString, results::Vector{ContingencyResult}; format = "technical")

Write the contingency results as a CSV (one row per case, always in input order): name, kind, the outaged elements (joined by |), weight, converged, iterations, the start-value ladder stage that converged, voltage envelope, worst loading, severity, the overloaded branches (each name@loading%, the per-branch delta to base lives in the structured overloads field), voltage-violation list, island count, shed load in MW, and the error text. format (technical/excel_de/excel_us, see _resolve_detailed_csv_format) sets the delimiter and number formatting like every other CSV artifact a run writes (issue #376); the previous hardcoded semicolon delimiter is now what excel_de selects, so an existing detailed_result_csv_format = "excel_de" run keeps this file's exact prior shape. Returns path.

source
Sparlectra.generateBranchPairs — Method
generateBranchPairs(net; names = contingency_names(net), rule = :all,
                    include_transformers = true, max_pairs = 50000)
    -> Vector{ContingencyCase}

N-2 pairs of kind :pair: with rule = :all every unordered pair of closed branches (the full enumeration; three-winding legs excluded, the transformer is one case), named P <a> + <b> with the element strings of names. More than max_pairs pairs throw an ArgumentError before any case is built, so a run never truncates silently. The pair count grows with the square of the branch count (217 branches give 23436 pairs).

source
Sparlectra.generateBusbarEvents — Method
generateBusbarEvents(net; names = contingency_names(net), include_transformers = true,
                     min_vn_kV = 0.0, name_pattern = nothing, max_members = 6)
    -> Vector{ContingencyCase}

One event of kind :busbar per bus: a fault on one busbar section opens its closed branches and its closed couplers (links), and the other sections of the station stay in service. Loads, units and shunts at the bus stay in the model; the run reports them as cut off (shed load, stranded units, or an island with its own reference), as for a radial outage. Named BB <bus>. Auxiliary buses (three-winding star points, internal buses of external grids) are no busbars.

Common keyword arguments:

  • names: the display names (contingency_names); events name their members by these element strings and are named after buses.
  • include_transformers (default true): with false, transformer branches are no members of any event.
  • min_vn_kV (default 0.0): keep an event whose highest member voltage meets this value.
  • name_pattern (default nothing): keep an event whose name matches this Regex or contains this substring.
  • max_members (default 6): skip an event with more members.

Only closed branches (in service, both terminals closed) are members; the legs of a three-winding transformer never are (the transformer is one case of its own). An event with a single branch is no event (that is the N-1 case) and is skipped.

source
Sparlectra.generateCorrelatedEvents — Method
generateCorrelatedEvents(net; names = contingency_names(net),
                         double_circuits = true, busbars = false, substations = false,
                         links = false, name_groups = false,
                         name_stem_pattern = DEFAULT_NAME_STEM_PATTERN, max_members = 6,
                         pairs = false, pair_rule = :all, max_pairs = 50000,
                         include_transformers = true, min_vn_kV = 0.0, name_pattern = nothing)
    -> Vector{ContingencyCase}

The union of the selected event classes in the order double circuits (generateDoubleCircuits), name groups (generateNameGroups), busbar sections (generateBusbarEvents), stations (generateSubstationEvents), couplers (generateLinkOutages) and, with pairs, N-2 pairs (generateBranchPairs). Events with the same member set appear once, as the first class that produced them: a double circuit that is also a name group stays :double_circuit, a single-bus station is :busbar when busbars are on and :substation when only stations are, and a pair that equals an event is dropped.

source
Sparlectra.generateDoubleCircuits — Method
generateDoubleCircuits(net; names = contingency_names(net), include_transformers = true,
                       min_vn_kV = 0.0, name_pattern = nothing, max_members = 6)
    -> Vector{ContingencyCase}

One event of kind :double_circuit per pair of buses joined by two or more closed branches: the circuits on the same towers, which a single fault can take out together. Named DC <from bus>-<to bus>.

Common keyword arguments:

  • names: the display names (contingency_names); events name their members by these element strings and are named after buses.
  • include_transformers (default true): with false, transformer branches are no members of any event.
  • min_vn_kV (default 0.0): keep an event whose highest member voltage meets this value.
  • name_pattern (default nothing): keep an event whose name matches this Regex or contains this substring.
  • max_members (default 6): skip an event with more members.

Only closed branches (in service, both terminals closed) are members; the legs of a three-winding transformer never are (the transformer is one case of its own). An event with a single branch is no event (that is the N-1 case) and is skipped.

source
Sparlectra.generateLinkOutages — Method
generateLinkOutages(net; names = contingency_names(net)) -> Vector{ContingencyCase}

One case of kind :link per closed bus link (a busbar coupler): the coupler opens alone, and the two sections it joined run as separate buses. Named after the link.

source
Sparlectra.generateNameGroups — Method
generateNameGroups(net; names = contingency_names(net), stem = Regex(DEFAULT_NAME_STEM_PATTERN),
                   include_transformers = true, min_vn_kV = 0.0, name_pattern = nothing, max_members = 6)
    -> Vector{ContingencyCase}

One event of kind :name_group per set of branches whose display names share a stem: the name with the circuit suffix stem matches removed (Ostheim_Neuwiese_1 and _2, or two legs carrying the same name). Only branches with the same nominal voltage and the same pair of endpoint stations group, so a voltage suffix (Leitung_220, Leitung_380) or a name reused elsewhere never joins unrelated branches. Named NG <stem>. The grouping needs the file names of an SCF case: with the generated names of a plain net (names.generated) the list is empty and one line says so.

Common keyword arguments:

  • names: the display names (contingency_names); events name their members by these element strings and are named after buses.
  • include_transformers (default true): with false, transformer branches are no members of any event.
  • min_vn_kV (default 0.0): keep an event whose highest member voltage meets this value.
  • name_pattern (default nothing): keep an event whose name matches this Regex or contains this substring.
  • max_members (default 6): skip an event with more members.

Only closed branches (in service, both terminals closed) are members; the legs of a three-winding transformer never are (the transformer is one case of its own). An event with a single branch is no event (that is the N-1 case) and is skipped.

source
Sparlectra.generateSubstationEvents — Method
generateSubstationEvents(net; names = contingency_names(net), include_transformers = true,
                         min_vn_kV = 0.0, name_pattern = nothing, max_members = 6)
    -> Vector{ContingencyCase}

One event of kind :substation per station: every closed branch incident to any of its buses opens, so the whole station is out. A station is the set of buses joined by closed links (busbar sections and their couplers); a bus without links is a station of its own. Bus elements stay in the model and are reported as cut off. Named SUB <station bus> after the lowest bus index of the station.

Common keyword arguments:

  • names: the display names (contingency_names); events name their members by these element strings and are named after buses.
  • include_transformers (default true): with false, transformer branches are no members of any event.
  • min_vn_kV (default 0.0): keep an event whose highest member voltage meets this value.
  • name_pattern (default nothing): keep an event whose name matches this Regex or contains this substring.
  • max_members (default 6): skip an event with more members.

Only closed branches (in service, both terminals closed) are members; the legs of a three-winding transformer never are (the transformer is one case of its own). An event with a single branch is no event (that is the N-1 case) and is skipped.

source
Sparlectra.UndoLog — Type
UndoLog

The reversible record of one apply!: the field writes and structural deletions in application order, plus the flag that derived state (bus types, Q-limit tables, node injection sums, isolated-node registry) must be recomputed after the replay.

source
Sparlectra.apply! — Method
apply!(net, ops, index) -> UndoLog

Apply the patch operations to the working copy net, addressing components through the ScenarioIndex, and record every change. Derived state (node injection sums, bus types, Q-limit tables, the isolated-node registry) is refreshed once after the patches, exactly as the importers do after construction. Prosumer outages (status 0 on a generator, load or external grid) are applied after every other operation, highest position first, so the order of the ops does not change the result; a branch outage also removes the bus shunt part a MATPOWER reimport records for the branch.

With a series index (index.origin :cgmes_series or :scf_series) the ops run in three passes: every set in_service (park and unpark; a parked unit keeps its position in prosumpsVec), then every other op, then one refresh. Inside a pass the order is fixed by id and field, bus start values follow the appliance ops and bus isolation comes last, so the order of the ops in a delta does not change the result. Bus isolation ops replace net.isoNodes by a new vector. Every write goes through the undo log, so restore! returns the template bitwise. Before any write, a delta is rejected with an ArgumentError when it leaves r_pu and x_pu of a branch both 0 or writes r_pu/x_pu on a branch whose impedance a typed tap model derives (taps_derived); the net is then unchanged.

source
Sparlectra.restore! — Method
restore!(net, undo) -> Nothing

Replay the undo log in reverse: reinsert every deleted element at its recorded position and write back every recorded field value, then refresh the derived state once. After this the working copy equals the base bitwise on every field a patch can touch (the step-2 acceptance test checks exactly that with the SCF reflection comparison).

source
Sparlectra.validate_scenarios — Method
validate_scenarios(set, index, net) -> ScenarioSet

The net-aware validation of step 2 on top of the structural one: a tap_pos patch is rejected at load time when the transformer carries an ACTIVE tap controller (the message names it), and accepted only where a ratio tap changer exists. Tap-step scenarios on unregulated transformers are a first-class case.

source
Sparlectra.ScenarioResult — Type
ScenarioResult

Outcome of one scenario under an engine with screening: the full ContingencyResult surface (all its fields forward) plus screened (true when the full run was skipped and the metric columns carry the screening estimates) and screening_estimate (the estimate tuple: estimated worst loading, voltage envelope, and the screening-step mismatch before and after; nothing when no estimate was computed).

source
Sparlectra.runScenarios! — Method
runScenarios!(net, set::ScenarioSet; index::ScenarioIndex, kwargs...) -> Vector{ContingencyResult}
runScenarios!(net, scenarios::Vector{Scenario}; index::ScenarioIndex, kwargs...)

Evaluate a scenario set on net: validate against the index and the net (active tap controllers reject a tap_pos patch), expand the N-1 modes through the existing generators, and run every scenario on the engine. A scenario that is a single status-0 outage reproduces runContingencies! exactly; general patch scenarios (setpoint changes, load scalings, multi-op outages) run the same ladder and metrics on the patched working copy. net is never mutated. The keyword surface matches runContingencies! (vm_min_pu, vm_max_pu, maxIte, base_maxIte, tol, rescue_ladder, the parallel_* overrides, executor, max_processes); remaining keywords reach the per-scenario power-flow solves. Results are returned in scenario order; failures are reported in the result, never thrown. progress reports the batch progress exactly as in runContingencies! (one call per finished scenario, thread safe callable required).

Screening: with screening_mode = :flag every non-islanding single outage is estimated first with one Woodbury-corrected Newton step on the base factorization, and only scenarios whose estimate comes within screening_margin_pct of a limit (or whose screening step did not reduce the mismatch) get the full solve; :only reports the estimates without full runs where an estimate exists. The programmatic default is :off (every scenario fully solved, bit-identical to the pre-screening engine); the service path applies the contingency.screening.* configuration, whose default is :off as well (screening is a deliberate opt-in). With screening active the return type is Vector{ScenarioResult} (the ContingencyResult surface plus screened and screening_estimate).

A scenario whose operations are all status-0 outages (of branches, transformers, generators, external grids or links) runs on the exact outage path, a single op as N-1, several as one event. Generator outages leave in descending position order, so the order of the ops does not change the result. events and pairs (a ContingencyEventsConfig and a ContingencyPairsConfig) carry the generator options for the event classes of set.events. Result rows name the components by the file names of the case (contingency_names).

source
Sparlectra.writeContingencyResultsCSV — Method
writeContingencyResultsCSV(path, results::Vector{ScenarioResult}; format = "technical")

The ContingencyResult CSV with the two screening columns appended: screened and the compact estimate max_loading_pct|vmin_pu|vmax_pu (empty when no estimate was computed). With screening :off the engine returns plain ContingencyResult rows and the classic writer runs with the same format, so the two stay in the same shape for one run. format (technical/excel_de/excel_us) sets the delimiter and number formatting like every other CSV artifact a run writes (issue #376); excel_de reproduces the previous hardcoded semicolon delimiter.

source
Sparlectra.InjectionBatchResult — Type
InjectionBatchResult

The result of runInjectionBatch, one column or entry per scenario: vm (pu) and va_deg (n x N, internal bus order), converged, iterations (mismatch evaluations, the start included, as the length of the solver's mismatch history), final_mismatch (pu), and qlimit_violations, the number of PV buses whose reactive output at the solution lies outside its limits by more than qlimit_tol_pu (Q limits are off in batch mode). backend is :cpu or :gpu, strategy the GPU linear-solve strategy (:none on the CPU), note the reason when a GPU request ran on the CPU, stats counts and times of the run (seconds; setup_s and solve_s; on the CPU the executor and its workers, worker_copy_s, the creation of the working copies, and worker_warm_s, the base solve of the workers in power mode, both inside solve_s and summed over the workers (on threads and serially; in worker processes both are part of transfer_s), and per scenario the runpf! time cpu_runpf_s; on the GPU the device phases, the number of cuDSS analyses and refactorizations, the cuDSS library version and reordering algorithm).

source
Sparlectra.InjectionScenarios — Type
InjectionScenarios

N scenarios of one network that differ in the load injections: load_scale[b, s] multiplies P and Q of every load at bus b (internal bus index) in scenario s. Generators keep their setpoints, the slack takes the difference. kind names how the factors were made (:random, :ramp or :custom) and seed the random seed (nothing for a ramp or custom factors), so a study can record it.

See random_load_scenarios, load_ramp_scenarios and runInjectionBatch.

source
Sparlectra.load_ramp_scenarios — Function
load_ramp_scenarios(net, N = 96; low = 0.8, high = 1.2) -> InjectionScenarios

N scenarios with one load factor for all buses, rising in equal steps from low (scenario 1) to high (scenario N): a stand-in for a QSTS day profile with 96 quarter hours.

source
Sparlectra.random_load_scenarios — Method
random_load_scenarios(net, N; band = 0.2, seed = 1) -> InjectionScenarios

N scenarios with an independent load factor per bus and scenario, drawn uniformly from [1 - band, 1 + band] with Random.Xoshiro(seed). The same seed, N and bus count give the same factors.

source
Sparlectra.runInjectionBatch — Method
runInjectionBatch(net, scenarios::InjectionScenarios; config = nothing, backend = :cpu, start = :net, gpu_strategy = :sequential, gpu_uniform_mask = true, gpu_two_phase = :off, gpu_switch_mismatch = 1e-5, qlimit_tol_pu = 1e-4, blas_threads = 1, executor = nothing, max_processes = nothing, parallel_enabled = nothing, parallel_max_tasks = nothing, parallel_min_work_items = nothing) -> InjectionBatchResult

Solve every scenario of scenarios on net and return the states, the convergence flags and the Q-limit report (InjectionBatchResult). net is not changed.

The configuration is the one runpf!(net) would use (config, else the configuration the net was imported with, else the active one), with three changes for the batch: Q limits off (each scenario reports instead how many PV buses would leave their limits by more than qlimit_tol_pu), and the rescue ladder and the DC fallback off (a failed scenario is reported, not retried).

start = :net starts every scenario from the start iterate of net (its imported voltages, or a flat start if the configuration asks for one). start = :base first solves the base case (the loads of net) with the batch configuration on the CPU, for either backend, so the CPU and the GPU batch start from the same bits, and starts every scenario from that solution, with flat start, start projection and the start helpers off, as the QSTS steps after a converged base; the base solve counts into stats[:setup_s].

backend = :cpu runs each scenario through runpf! on reused working copies of net (reset after every scenario), in worker processes, on Julia threads or serially: executor (:auto, :threads, :processes, else runtime.parallel.executor) picks, :auto takes processes from 2000 buses on and threads below (Parallel Execution). The process batch uses the worker pool of start_batch_processes! (started on first use, at most max_processes or runtime.parallel.max_processes workers) and sends the net once per worker; the thread batch makes one working copy per chunk inside its task. parallel_enabled = false or fewer scenarios than min_work_items run serially. The results are the same bit for bit on every executor. With power_flow.power_mode on, every worker solves the base case once before its first scenario (stats[:worker_warm_s] sums these solves on threads), so its power-mode caches (Ybus, LU analysis) are warm from its first scenario on and kept across its scenarios; the copies start without the cache and the solver status of net. blas_threads sets the BLAS thread count of the batch (in the workers, or restored afterwards; nothing leaves it). The GC is paused while a scenario solves (runtime.gc_pause).

backend = :gpu needs the CUDA extension (using CUDA, CUDSS): the Ybus, the Jacobian pattern and one cuDSS analysis are built once, and all scenarios run their Newton iterations on the device, the Jacobian of all active scenarios in one kernel launch. gpu_strategy picks the linear solve: :sequential (default; one cuDSS solver, refactorization and solve per scenario, deterministic mode), :nonuniform (cuDSS non-uniform batch on column-permuted Jacobians, deterministic mode) or :uniform (cuDSS uniform batch on column-permuted Jacobians, fast mode only, since cuDSS 1.0.0 refuses the deterministic mode there; gpu_uniform_mask = false refactorizes and solves the retired scenarios as well). The precision follows power_flow.compute_backend.gpu_precision. If the GPU cannot take the batch (no extension or device, more than one island, links, Q(U) or P(U) controllers with a voltage-dependent characteristic, distributed slack, damping or start helpers) or fails on the device (out of device memory, a cuDSS error), the batch runs on the CPU and note says why, as long as power_flow.compute_backend.gpu_fallback_to_cpu is true (the default); with it false a refusal throws an ArgumentError and a device error is rethrown.

gpu_two_phase (GPU and :sequential only, study variants) replaces the precision setting by two phases. Phase 1 runs V, mismatch, Jacobian and LU in Float32 on the device until the Float32 mismatch norm is at most gpu_switch_mismatch, or until two steps in a row reduce it by less than half. Phase 2: :g5 keeps V and mismatch in Float64 on the device and steps with the last Float32 LU of phase 1, with one Float32 refactorization after 5 steps without convergence; :g5r refactorizes in Float32 at the first step that reduces the mismatch by less than half and goes over to a Float64 Newton on the device at the next such step; :g6 finishes with a Float64 Newton on the CPU (runpf! from the phase-1 iterate, flat start and start helpers off, on the CPU workers as with backend = :cpu). stats holds per scenario the steps of both phases, the reason of the switch, the refactorizations of phase 2 and the reduction rate per step (:tp_* keys). iterations counts the mismatch evaluations of both phases (for :g6 the CPU history, its start included).

Throws an ArgumentError for an unknown backend, start, strategy or two-phase variant, for gpu_two_phase with the CPU backend or another strategy than :sequential, or for a scenario matrix that does not match the bus count, and an error when start = :base and the base case does not converge.

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

The process ids of the running workers of the process batch (empty when the pool is not started). A worker that has exited is not listed (and leaves the pool).

source
Sparlectra.start_batch_processes! — Method
start_batch_processes!(n::Integer) -> Vector{Int}

Start worker processes for the process batch until the pool has at least n (one Julia thread each, the project, load path and system image of this process), load Sparlectra on them and return the process ids of the pool. The pool lives until stop_batch_processes! or the end of the process. A batch that runs in processes starts the pool by itself; calling this first keeps the start (a few seconds) out of the first batch. When this process has the KLU extension loaded, every worker of the pool loads KLU as well (power mode then factorizes with KLU on both sides). Throws an ErrorException when a worker loads another Sparlectra than this process; the workers started by a call that throws are stopped again.

source
Sparlectra.PatchOp — Type
PatchOp

One patch operation of a scenario: op is :status, :set or :scale, target names the component class, id the SCF component id. :status carries value (0 or 1); :set carries field (one of p, q, vm_pu, tap_pos, b_pu, angle_deg) and value; :scale carries factor and applies it to p and q together unless field names one of them. angle_deg is in degrees: the phase shift of a transformer, or the voltage angle of an external grid (the SCF u_ref_angle, which the file stores in radians); on the reference unit it sets the angle reference of its island. No structural operations exist by design.

A ScenarioIndex with origin :cgmes_series or :scf_series also accepts the QSTS :set fields: isolated, vm_start, va_start on a bus; status, from_status, to_status, r_pu, x_pu, g_from_pu, b_from_pu, g_to_pu, b_to_pu on a branch or transformer and ratio, shift_deg, tap_data on a transformer; g_pu on a shunt; in_service on a generator, load or external grid; qmin, qmax, regulated, reference, reference_priority, participation on a generator or external grid; enabled, target_vm_pu, deadband_vm_pu, p_target_mw, deadband_p_mw on a tap controller. qmin, qmax, participation, target_vm_pu and p_target_mw take value = nothing for "no value".

The branch parameters are per unit on the branch base, as the branch stores them. r_pu and x_pu write the live and the equipment value together, the four terminal values keep g_pu and b_pu their sums, ratio writes ratio and tap_ratio, shift_deg writes angle and phase_shift_deg (the SCF angle_deg writes phase_shift_deg only). tap_data with value k writes record k of that transformer in index.tap_data (a BranchTapData: tap range, step, table ratios, impedance per step) onto the branch.

source
Sparlectra.Scenario — Type
Scenario

A named, weighted, ordered list of patch operations with a kind from the vocabulary of ContingencyCase: :explicit for a user scenario (the default), a single-element kind for an expanded N-1 outage, an event class for a generated correlated event, :pair for an N-2 pair. The positional constructor Scenario(name, weight, ops) sets :explicit.

source
Sparlectra.ScenarioIndex — Type
ScenarioIndex

The id map of one network: component id to component class (kind_by_id) and the INTERNAL index the built network uses (internal_by_id: branch vector position for branches and transformers, prosumer position for appliances, shunt position for shunts, link position for links, bus number for :bus, position in _tap_controllers(net) for :tap_controller), so a patch resolves without name lookups, plus the display name of every component (name_by_id, the SCF extra[<id>].name), the source of the display names of contingency output (contingency_names).

Four fields serve the series (QSTS):

  • id_by_mrid: mRID to component id (CGMES series union);
  • parked_values: per component id, the values of a unit that is parked in the template, copied back by :set :in_service 1;
  • tap_data: per transformer id, the tap changer data records (BranchTapData) that :set :tap_data writes, numbered from 1;
  • origin: :scf for an index of a typed case, :cgmes_series for the CGMES series union, :scf_series for an SCF time series (SCFSeries). Only a series index accepts the QSTS vocabulary (validate_scenarios) and switches apply! to its three passes.

ScenarioIndex(kind_by_id, internal_by_id, name_by_id) builds an :scf index with empty mRID, parked-value and tap data maps. The full constructor takes tap_data as a keyword (default empty). Throws ArgumentError for another origin.

source
Sparlectra.ScenarioIndex — Method
ScenarioIndex(case::SCFCase; origin = :scf) -> ScenarioIndex

Build the id map of case: lines and links map to :branch and :link, generic branches to :transformer, sources to :external_grid, symgen to :generator, symload to :load, shunts to :shunt. Internal indices come from the recorded build-order fields of the extra block.

origin = :scf_series builds the index of an SCF time series: the node ids map to :bus as well (internal index from extra.bus_index), so the QSTS bus fields can address them. The parked values stay empty; the series fills them (read_scf_series).

source
Sparlectra.ScenarioSet — Type
ScenarioSet

An ordered vector of scenarios plus the selection mode (:explicit, :n1_branches, :n1_generators, :n1_all), the exclusions the N-1 expansion honors, and the correlated event classes events (any of :double_circuits, :busbars, :substations, :links, :name_groups, :pairs) generated next to the listed scenarios. The N-1 modes and the event classes expand to explicit scenarios at load time (expand_scenarios), so the engine sees one kind of input.

source
Sparlectra.expand_scenarios — Method
expand_scenarios(set, net, index; events = ContingencyEventsConfig(), pairs = ContingencyPairsConfig()) -> Vector{Scenario}

Expand a scenario set to the scenarios the engine runs. The N-1 modes expand through the EXISTING generators (generateN1Branches, generateN1Generators), honoring exclusions by element string or case name; every expanded scenario carries one status patch (a three-winding transformer one per leg) and the kind of its case. The event classes of set.events add the generated correlated events and N-2 pairs (generateCorrelatedEvents, generateBranchPairs); the generator options (max_members, name_stem_pattern, the pair rule and cap) come from events and pairs. Explicit scenarios come first, then the N-1 list, then the events. Case names and elements use the file names of the case (contingency_names).

source
Sparlectra.scenario_from_case — Method
scenario_from_case(case, net, index; names = contingency_names(net, index)) -> Union{Nothing,Scenario}

The scenario form of a ContingencyCase: one status-0 operation per outaged element (every leg of a three-winding transformer), with the case's name, weight and kind. Returns nothing when an element does not resolve to a component of the case (a case list built for another network).

source
Sparlectra.scf_case_scenarios — Method
scf_case_scenarios(case) -> Union{Nothing,ScenarioSet}

The scenario set a typed case carries: the scenarios block when present, otherwise nothing. Scenarios are a Sparlectra Case Format feature; converting a case to another format does not carry them.

source
Sparlectra.validate_scenarios — Method
validate_scenarios(set, index) -> ScenarioSet

Load-time validation of the patch model: every operation must name a known id whose class admits the operation and field; a scenario needs a non-empty op list and a unique name. Errors carry the scenario name and the op index. Returns set unchanged on success.

The QSTS :set fields (see PatchOp) are accepted only by a series index (index.origin :cgmes_series or :scf_series); an :scf index rejects them with the op named. With a series index a scenario may write each (id, op, field) once, in_service 1 needs the parked values of its id in index.parked_values, and tap_data k record k of its id in index.tap_data. The branch parameters need a finite value, ratio a nonzero one. Whether r_pu and x_pu of a branch are both 0 after the delta depends on the net, so apply! checks that.

source

Internals

Sparlectra._validate_contingency_ladder — Method
_validate_contingency_ladder(ladder; context) -> Vector{Symbol}

Validate a contingency start-value ladder: a non-empty, duplicate-free ordered subset of (:warm, :apslf, :dc, :flat). Throws an ArgumentError naming context otherwise. Shared by the contingency.rescue_ladder config section and the runContingencies! keyword so both reject the same inputs.

source
Sparlectra.ScenarioEngine — Type
ScenarioEngine

The scenario batch engine: the solved base template (never mutated after construction), the base branch loadings every result reports its deltas against, the resolved solve parameters, the optional ScenarioIndex that patch scenarios address components through, and, with screening_mode other than :off, the screening state: the base Jacobian factorization plus everything one Woodbury-corrected Newton step needs. A distributed-slack batch screens on the AUGMENTED system: lambda as the extra state, a generator outage zeroes the lost unit's participation factor and renormalizes the rest (a rank-1 column update the generic correction covers), and a participating unit whose estimated output leaves its P band flags the scenario. screen === nothing with screening requested means the state could not be built (base not converged, residual inconsistent, voltage-dependent injections, no surviving participant); every scenario then gets the full run.

source
Sparlectra.ScenarioEngine — Method
ScenarioEngine(net; vm_min_pu, vm_max_pu, maxIte, tol, ladder, index, pf_kwargs)

Build the engine template from net: solve the base case (with the full solver rescue ladder as fallback, then a flat template with a warning, exactly the old runContingencies! preamble), clear the solver status and Q-limit logs the workers must not inherit, and record the base branch loadings. net itself is never mutated.

source
Sparlectra.ScenarioWorker — Type
ScenarioWorker

One reusable working copy of the engine template. After every evaluation the worker is reset to the template state (patch undo plus solver-state reset), so the next scenario starts from exactly the state a fresh deepcopy would have provided.

source
Sparlectra._reset_scenario_worker! — Method
_reset_scenario_worker!(work, template) -> Nothing

Reset a working copy to the template state after an evaluation. The patch itself is already undone (undo log replay, prosumer reinsertion); what remains is everything a SOLVE mutates: node voltages and types, branch status/flow/loss fields, prosumer write-backs, the isolated-node registry (with the list of buses the marking isolated itself), slack rows, Q-limit tables and logs, loss accumulators, and the solver status. The step-3 acceptance test proves the reset with the SCF reflection comparison: after evaluations with solves, the worker equals the template bitwise on every compared field. Transformer tap CONTROLLER state is not reset here: scenario nets with active tap controllers are rejected at validation time (step 2), so no engine path moves a tap.

source
Sparlectra.evaluate! — Method
evaluate!(engine, worker, item) -> ContingencyResult

Evaluate one work item on the worker's net and reset the worker afterwards. An outage item reproduces the pre-engine contingency semantics exactly: a branch outage opens both terminals (equivalent to the old structural removal for the Y-bus, isolation marking, and metrics, all of which treat a fully open branch as absent), and a generator outage runs _remove_contingency_generator! with the deleted prosumer reinserted afterwards. A patch item applies its operations through apply! with the documented scenario semantics.

source
Sparlectra.InjectionBatchGpuInput — Type
InjectionBatchGpuInput

What the GPU batch of the CUDA extension needs, built once per batch on the CPU: the Ybus, the start iterate V0 shared by all scenarios, the specified injections S (n x N), the bus types (no switching, Q limits off), the voltage setpoints, the slack, the Newton settings and the linear-solve strategy (:sequential, :nonuniform, :uniform), the precision (:float64, :float32_mixed), fast_mode (cuDSS deterministic mode off), uniform_mask (the uniform batch skips the retired scenarios through ubatch_mask; off, it refactorizes and solves all N every iteration), fallback_to_cpu (a GPU error returns its message instead of throwing, so the batch can run on the CPU), and two_phase (:off, :g5, :g5r, :g6) with switch_tol, the Float32 mismatch norm at which the two-phase variants leave phase 1 (see runInjectionBatch). ysh is the conjugate admittance of the voltage-dependent bus shunts per bus (zero without one): with such shunts S holds the prosumer part only, and the device rebuilds S - abs(V)^2 * ysh and the chain terms in every iteration, as buildControlledSVec does on the CPU.

source
Sparlectra._process_parallel_map — Method
_process_parallel_map(setup, payload, eval_one, item_arg, n, pids; blas_threads, progress) -> (results, stats)

The process counterpart of _engine_parallel_map: item k of 1:n is eval_one(state, k, item_arg(k)) on a worker process, where state = setup(deserialize(payload)) was built once per worker; a worker keeps the state of its last batch, and a later batch with the same payload (same SHA-256) and setup reuses it without sending the payload. setup and eval_one must be functions defined at the top level of Sparlectra (they are sent by name). Items go to the next free worker (results do not depend on the worker: every item starts from the same state). The abort token is checked here before every item and watched while the items run: when it is set, the workers stop their running items within one Newton iteration (_FileAbortFlag) and the call throws PowerFlowAborted. progress is counted here in the main process. The workers drop the batch state in a finally. stats holds transfer_s (sending and loading the payload on all workers, wall time), setup_max_s (the slowest worker's load) and workers_reused (workers that kept the state).

source
Sparlectra.BranchTapData — Type
BranchTapData

The tap changer data of one transformer branch as the importer sets it: the ratio tap (has_ratio_tap, tap_min, tap_max, tap_step, the table ratios tap_ratio_points), the phase tap (has_phase_tap, phase_min_deg, phase_max_deg, phase_step_deg) and the impedance per tap step (tap_step_impedance). The field names are those of Branch. BranchTapData(br) takes the data of a branch. A series index keeps these records per transformer id (ScenarioIndex.tap_data); the QSTS op :set :tap_data with value k writes record k onto the branch.

source
Sparlectra._sv_align_angles — Method
_sv_align_angles(dva, island_of) -> (aligned = Vector{Float64}, offset_deg = Float64, offsets = Dict{Int,Float64})

Remove one angle offset per island from the angle differences dva (degrees, model minus SV, one entry per compared bus). island_of[i] is the island of entry i (0 for none); the caller builds it from the islands the power flow solves (_power_flow_island_of_bus: closed links connect, also through a bus the branch-only marking isolates), never from the branch-only view, where a part that hangs on the rest through a closed switch alone becomes an island of its own and its median hides its own deviation.

The offset of an island is the median of its finite differences, and aligned[i] is dva[i] minus the offset of its island. offset_deg is the offset of the island with the most finite differences, the reference offset of the delivery as a whole; an entry whose island has no finite difference is aligned with it. offsets maps every island with a finite difference to its offset, so a caller can align further values of the same islands (get(offsets, island, offset_deg)) with exactly the offsets the entries got.

source
Sparlectra._sv_branch_terminal_flow — Method
_sv_branch_terminal_flow(br, V, side, baseMVA) -> ComplexF64

Complex power in MW/MVAr flowing from the bus into branch br at its terminal side (:from, anything else is the to side), from the complex bus voltages V in pu indexed by bus number. The model is the solver's: series admittance, the shunt arm of each terminal (the from arm behind the tap), and the off-nominal ratio tap_ratio with phase_shift_deg on the from side; a branch with ratio == 0 has no tap. calcNetLosses! uses the same ratio and shift.

source