pub struct BalancedNetwork { /* private fields */ }Expand description
A balanced network with stable source bus IDs and separate element tables: an immutable cheap to clone owning handle over private shared tables.
Cloning the handle bumps one reference count and clones no table
allocation. Reads go through the per field accessors; the *_mut
accessors copy the shared tables once on first write to a shared handle
(copy on write), so no other handle ever observes a mutation. The choice
of whole value sharing is private: clone stays zero allocation because
the handle wraps its tables in one Arc.
Implementations§
Source§impl BalancedNetwork
impl BalancedNetwork
Sourcepub fn apply_gen_cost_policy(
&mut self,
patches: &[GenCostPatch],
policy: MissingGenCostPolicy,
) -> Result<GenCostPolicyReport>
pub fn apply_gen_cost_policy( &mut self, patches: &[GenCostPatch], policy: MissingGenCostPolicy, ) -> Result<GenCostPolicyReport>
Apply explicit cost patches, then a missing-cost policy.
Patches replace the existing cost for the named generator. The missing-cost fill policy only touches generators still missing a cost after patching.
Source§impl BalancedNetwork
impl BalancedNetwork
Sourcepub fn geo_layer(&self) -> GeoLayer
pub fn geo_layer(&self) -> GeoLayer
Extract this network’s coordinates as a standalone GeoLayer:
one point per located bus, one route per routed branch. The layer
carries the network’s coordinate space and default origin.
Sourcepub fn apply_geo_layer(&mut self, layer: &GeoLayer) -> GeoApplyReport
pub fn apply_geo_layer(&mut self, layer: &GeoLayer) -> GeoApplyReport
Apply a GeoLayer onto this network: matched bus points land in
Bus.location, matched branch routes in Branch.route, and the
layer’s space becomes the network’s GeoMeta when anything matched.
Matching follows ElementKey. Substation features are not applied
here; join them through super::apply_substation_points.
Source§impl BalancedNetwork
impl BalancedNetwork
Sourcepub fn name_mut(&mut self) -> &mut String
pub fn name_mut(&mut self) -> &mut String
Mutable access to the same table; a shared handle copies its tables once here, so no other handle observes the change.
Sourcepub fn geo_mut(&mut self) -> &mut Option<GeoMeta>
pub fn geo_mut(&mut self) -> &mut Option<GeoMeta>
Mutable access to the same table; a shared handle copies its tables once here, so no other handle observes the change.
Sourcepub fn solver(&self) -> &Option<SolverParams>
pub fn solver(&self) -> &Option<SolverParams>
Solver / solution-control metadata when the source carries it.
Sourcepub fn solver_mut(&mut self) -> &mut Option<SolverParams>
pub fn solver_mut(&mut self) -> &mut Option<SolverParams>
Mutable access to the same table; a shared handle copies its tables once here, so no other handle observes the change.
Source§impl BalancedNetwork
impl BalancedNetwork
Replace each element table’s allocation with donor’s wherever the
contents are equal, so equal tables across derived networks (the
scenarios of one dataset, the points of one series) are stored once.
No value changes; a table that differs anywhere keeps its own
allocation.
Source§impl BalancedNetwork
impl BalancedNetwork
pub fn buses(&self) -> &Vec<Bus>
Sourcepub fn buses_mut(&mut self) -> &mut Vec<Bus>
pub fn buses_mut(&mut self) -> &mut Vec<Bus>
Mutable access to the same table. A shared handle copies the table set spine and this one table here, so no other handle observes the change and untouched tables stay shared.
pub fn loads(&self) -> &Vec<Load>
Sourcepub fn loads_mut(&mut self) -> &mut Vec<Load>
pub fn loads_mut(&mut self) -> &mut Vec<Load>
Mutable access to the same table. A shared handle copies the table set spine and this one table here, so no other handle observes the change and untouched tables stay shared.
pub fn shunts(&self) -> &Vec<Shunt>
Sourcepub fn shunts_mut(&mut self) -> &mut Vec<Shunt>
pub fn shunts_mut(&mut self) -> &mut Vec<Shunt>
Mutable access to the same table. A shared handle copies the table set spine and this one table here, so no other handle observes the change and untouched tables stay shared.
pub fn branches(&self) -> &Vec<Branch>
Sourcepub fn branches_mut(&mut self) -> &mut Vec<Branch>
pub fn branches_mut(&mut self) -> &mut Vec<Branch>
Mutable access to the same table. A shared handle copies the table set spine and this one table here, so no other handle observes the change and untouched tables stay shared.
pub fn switches(&self) -> &Vec<Switch>
Sourcepub fn switches_mut(&mut self) -> &mut Vec<Switch>
pub fn switches_mut(&mut self) -> &mut Vec<Switch>
Mutable access to the same table. A shared handle copies the table set spine and this one table here, so no other handle observes the change and untouched tables stay shared.
pub fn generators(&self) -> &Vec<Generator>
Sourcepub fn generators_mut(&mut self) -> &mut Vec<Generator>
pub fn generators_mut(&mut self) -> &mut Vec<Generator>
Mutable access to the same table. A shared handle copies the table set spine and this one table here, so no other handle observes the change and untouched tables stay shared.
pub fn storage(&self) -> &Vec<Storage>
Sourcepub fn storage_mut(&mut self) -> &mut Vec<Storage>
pub fn storage_mut(&mut self) -> &mut Vec<Storage>
Mutable access to the same table. A shared handle copies the table set spine and this one table here, so no other handle observes the change and untouched tables stay shared.
pub fn hvdc(&self) -> &Vec<Hvdc>
Sourcepub fn hvdc_mut(&mut self) -> &mut Vec<Hvdc>
pub fn hvdc_mut(&mut self) -> &mut Vec<Hvdc>
Mutable access to the same table. A shared handle copies the table set spine and this one table here, so no other handle observes the change and untouched tables stay shared.
Sourcepub fn transformers_3w(&self) -> &Vec<Transformer3W>
pub fn transformers_3w(&self) -> &Vec<Transformer3W>
Three-winding transformers, kept as typed records.
Sourcepub fn transformers_3w_mut(&mut self) -> &mut Vec<Transformer3W>
pub fn transformers_3w_mut(&mut self) -> &mut Vec<Transformer3W>
Mutable access to the same table. A shared handle copies the table set spine and this one table here, so no other handle observes the change and untouched tables stay shared.
Source§impl BalancedNetwork
impl BalancedNetwork
pub fn base_mva_mut(&mut self) -> &mut f64
Sourcepub fn base_frequency(&self) -> f64
pub fn base_frequency(&self) -> f64
System base frequency in hertz (50 or 60).
pub fn base_frequency_mut(&mut self) -> &mut f64
Sourcepub fn source_format(&self) -> SourceFormat
pub fn source_format(&self) -> SourceFormat
The format the case was parsed from.
pub fn source_format_mut(&mut self) -> &mut SourceFormat
Source§impl BalancedNetwork
impl BalancedNetwork
pub fn new(name: impl Into<String>, base_mva: f64) -> BalancedNetwork
Sourcepub fn in_memory(
name: impl Into<String>,
base_mva: f64,
buses: Vec<Bus>,
branches: Vec<Branch>,
) -> BalancedNetwork
pub fn in_memory( name: impl Into<String>, base_mva: f64, buses: Vec<Bus>, branches: Vec<Branch>, ) -> BalancedNetwork
A network assembled in memory from buses and branches, with no loads,
shunts, generators, storage, HVDC, or retained source document. Synthetic
topology generators and tests use it instead of repeating the struct
literal. The caller owns reference integrity (run check_references if
the ids might be inconsistent).
Sourcepub fn to_json(&self) -> Result<String>
pub fn to_json(&self) -> Result<String>
Serialize the structured tables to model JSON. The C ABI and language
bindings use this representation. The retained source text is
excluded (see the field’s #[serde(skip)]), so the byte-exact echo
stays on the same-format write path; a from_json
round-trip reproduces every field except source, which returns None.
JSON has no Inf/NaN literal: a nonfinite field is written as
"Infinity", "-Infinity", or "NaN" (see [crate::nonfinite]) and
from_json reads either a number or one
of those spellings back, so every network round trips — readers
legitimately produce Inf limits, and a document written before
0.9.0 spelled them null, which still refuses with a message naming
the change.
§Errors
A serde_json serialization failure (none arise from this model today).
Sourcepub fn to_json_with_diagnostics(&self) -> Result<(String, Vec<Diagnostic>)>
pub fn to_json_with_diagnostics(&self) -> Result<(String, Vec<Diagnostic>)>
to_json plus the fidelity records the
write produced. The write is faithful today — a nonfinite value spells
itself as a string and reads back — so the record list is empty; the
channel stays because it is the shape a write-side finding arrives
through, and a caller wired to it needs no change when one appears.
§Errors
A serde_json serialization failure (none arise from this model today).
Sourcepub fn to_format(&self, format: TargetFormat) -> Result<Conversion>
pub fn to_format(&self, format: TargetFormat) -> Result<Conversion>
Serialize this typed network to format, the semantic write. The byte
exact echo of an unchanged parsed module lives on the module write
path, write_as.
§Errors
Error::WriteUnsupported for a read
only target, and the writer’s own error on a case it cannot state.
Sourcepub fn to_canonical_format(&self, format: TargetFormat) -> Result<Conversion>
pub fn to_canonical_format(&self, format: TargetFormat) -> Result<Conversion>
Sourcepub fn to_format_with_options(
&self,
format: TargetFormat,
options: &WriteOptions,
) -> Result<Conversion>
pub fn to_format_with_options( &self, format: TargetFormat, options: &WriteOptions, ) -> Result<Conversion>
Serialize this network with write-time cost policies.
The network itself is not mutated.
Sourcepub fn to_matpower(&self) -> String
pub fn to_matpower(&self) -> String
Serialize this network to MATPOWER .m text.
This is byte-exact when the network was parsed from MATPOWER and still carries its retained source text.
Sourcepub fn from_json(text: &str) -> Result<BalancedNetwork>
pub fn from_json(text: &str) -> Result<BalancedNetwork>
Rebuild a BalancedNetwork from JSON produced by to_json.
A float position accepts a number or the nonfinite spellings
"Infinity", "-Infinity", "NaN" (see [crate::nonfinite]).
Validates the result (no buses, unique bus ids, no dangling references)
before returning, so the JSON transport (the C ABI and Julia bridge ride
on it) can’t hand back a network the file readers would have rejected
(the same no-buses guard read_source applies to every parse path).
Sourcepub fn from_json_bytes(bytes: &[u8]) -> Result<BalancedNetwork>
pub fn from_json_bytes(bytes: &[u8]) -> Result<BalancedNetwork>
Rebuild a BalancedNetwork from UTF-8 JSON bytes produced by
to_json.
Decoding is strict: invalid UTF-8 returns a coded JSON read error and
is never replaced with Unicode replacement characters. A leading UTF-8
byte order mark is accepted. The decoded document goes through
from_json, including its reference and
nonempty-network validation.
Sourcepub fn is_normalized(&self) -> bool
pub fn is_normalized(&self) -> bool
Whether this is a normalized (per-unit, radian, filtered)
derived product from to_normalized, rather
than a raw network at the file’s unit basis. Unit-sensitive code that
takes a &BalancedNetwork can check this instead of silently assuming MW.
Sourcepub fn check_base_mva(&self) -> Result<()>
pub fn check_base_mva(&self) -> Result<()>
Error unless base_mva is a positive, finite number. It is every
per-unit divisor, so a malformed base would otherwise silently poison
downstream values with NaN/Inf or flipped signs. The per-unit
consumers (to_normalized, the gridfm
export) call this; any other unit-sensitive consumer should too.
Sourcepub fn validate_values(&self) -> Vec<Diagnostic>
pub fn validate_values(&self) -> Vec<Diagnostic>
Report element fields whose values fall outside their physical domain,
without changing anything, as coded VALIDATE.BALANCED.VALUE_DOMAIN
findings. Each record targets the element and carries the field, the
current value, the value a repair would set, and why in details.
This generalizes the per-reader value clamps (a bus voltage magnitude
outside [0, 2], an angle past ±2000°, a zero generator MVA base or
voltage setpoint) into one pass any consumer can run, separate from the
structural validate (which only checks
ids and references). It is non-mutating; repair_values applies the
fixes to a parsed module and records them.
Sourcepub fn validate(&self) -> Result<()>
pub fn validate(&self) -> Result<()>
Check structural integrity: bus ids are unique and every element
references an existing bus. The file readers and from_json
run this; a BalancedNetwork built by hand (or mutated, e.g. by a scenario
generator) should call it before handing the network to
IndexedNetwork, whose dense indexing assumes it.
Source§impl BalancedNetwork
impl BalancedNetwork
Sourcepub fn to_normalized(&self) -> Result<BalancedNetwork>
pub fn to_normalized(&self) -> Result<BalancedNetwork>
A normalized, computation-ready copy of this network. The raw BalancedNetwork is
kept lossless (MATPOWER units, 1-based sparse ids, out-of-service elements
retained); to_normalized derives the form a solver or ML pipeline wants:
- Per unit (÷
base_mva): genpg/qg/pmax/pmin/qmax/qminand the ramp caps (GEN_PU_KEYS); loadp/q; shuntg/b; branchrate_a/b/c; storage energy/ratings/limits/losses; HVDCpf/pt/qf/qt, reactive limits,loss0; gen-cost coefficients (cost_to_pu). Storageps/qsand HVDC aggregatepmin/pmaxstay raw, matching the PowerModels per-unit convention. Voltages, impedances, tap, andloss1are already dimensionless. - Radians: bus
va; branchshift/angmin/angmax. - Tap:
0 → 1.0(an explicit1is kept). - Filtered: drop buses typed isolated (
BusType::Isolated) and every out-of-service element, then drop any element left referencing a dropped bus. A bus orphaned by the out-of-service filter (no in-service branch, but not typed isolated) is kept — its load is real — and surfaces as its own island, which the grounding check reports if it has no reference. - IDs: kept buses retain their source bus ids, and every surviving
endpoint stays in the same id space. Consumers that need dense rows should
use
IndexedNetwork, which derives[0, n)indices without destroying source ids. - Bus types: a bus hosting a surviving generator keeps
REFif the file marked itREF, otherwise becomesPV; a generator-less bus isPQ(so a generator-lessREFis demoted). The file’sREFbuses are kept, several included, and the consumer picks the slack. Only when no reference bus survives is the largest-pmaxin-service generator’s bus promoted toREF.
This is a derived product, not a source for write-back: source is dropped
and source_format is SourceFormat::Normalized, so writing it serializes
the per-unit/radian model instead of echoing the raw bytes, and a consumer
can tell it apart from a raw in-memory network.
Scope is the universal canonicalization only. It does not synthesize a
missing rate_a or restrict the gen-cost model — those are solver
preparation choices a consumer applies on top. Use
BalancedNetwork::to_normalized_with_options for the opt in PowerModels angle
bound repair. The cost rescale is
universal and lives here; the model restriction does not.
§Errors
Error::InvalidBaseMva if base_mva is not a positive, finite number
(every per-unit divisor), so a malformed base can’t silently poison the
whole network with NaN/Inf or sign-flipped values.
Error::NoReferenceBus if no reference bus can be established — no REF
survives and there is no in-service generator to anchor one.
Sourcepub fn to_normalized_with_options(
&self,
options: &NormalizeOptions,
) -> Result<NormalizedNetwork>
pub fn to_normalized_with_options( &self, options: &NormalizeOptions, ) -> Result<NormalizedNetwork>
Like BalancedNetwork::to_normalized, with opt in solver preparation repairs
that report fidelity warnings.
Source§impl BalancedNetwork
impl BalancedNetwork
Sourcepub fn subset(&self, sel: &Selector, keep_boundary: bool) -> BalancedNetwork
pub fn subset(&self, sel: &Selector, keep_boundary: bool) -> BalancedNetwork
Carve out the sub-network whose buses match sel.
In-scope buses keep their loads, shunts, generators, and storage; a branch,
HVDC line, or 3-winding transformer is kept when every bus it touches is
kept. With keep_boundary, a branch or HVDC line straddling the selection
edge pulls its out-of-scope endpoint in as a tie bus (tagged
extras["tie_bus"] = true) so the carved island has no dangling branch
ends; without it, a straddling branch is dropped. A tie bus is a stub: its
own loads/generators are not pulled in. A control reference (regulated bus)
that falls outside the kept set is cleared so the result is
reference-consistent.
The result is a fresh SourceFormat::InMemory network (no retained
source); an empty Selector returns a clone-equivalent of the whole case,
and a selector matching no bus returns an empty network.
Sourcepub fn merge_bus(&mut self, into: BusId, from: BusId)
pub fn merge_bus(&mut self, into: BusId, from: BusId)
Merge bus from into bus into: re-home every element on from (loads,
shunts, generators, storage, branch/HVDC/transformer endpoints, and control
references) onto into, drop the branches and HVDC lines that ran directly
between the two (now self-loops), and remove the from bus. The surviving
bus keeps the stronger of the two bus kinds (a slack is not demoted).
A no-op when into == from. The other attributes of from (its voltage,
limits, name) are discarded; the topology and injections are what move.
Sourcepub fn reduce_zero_impedance(&mut self, threshold: f64) -> usize
pub fn reduce_zero_impedance(&mut self, threshold: f64) -> usize
Collapse every in-service, non-transformer branch whose series impedance
magnitude is at or below threshold by merging its endpoints (the to-bus
into the from-bus), returning the number of branches removed. Parallel
jumpers between the same pair go in the same step.
Zero-impedance branches (bus ties, breakers modeled as jumpers) carry no power flow drop, so collapsing them shrinks the network without changing its electrical behavior. An out-of-service jumper is an open switch whose endpoints are not electrically joined, so it is left in place. Transformers are never collapsed (a unity-ratio transformer is a real device, not a jumper); a jumper between two windings of the same 3-winding transformer is also skipped, since merging would collapse that transformer onto one node.
Sourcepub fn reduce_passthrough_buses(&mut self) -> usize
pub fn reduce_passthrough_buses(&mut self) -> usize
Collapse degree-2 passthrough buses, returning the number removed. A passthrough bus carries nothing but two in-service line sections, so it is an electrically inert junction: the two sections fold into one equivalent branch between their outer endpoints and the middle bus is deleted.
This is the multi-section-line reduction. Exporters often split one circuit into segments joined at dummy buses; folding them back recovers the single branch. A bus qualifies only when it carries no load, generator, shunt, or storage, is not a control reference, area swing, HVDC endpoint, or 3-winding winding bus, is not the system slack, and is touched by exactly two ordinary branches (never transformers) that are both in service and run to two distinct other buses. The equivalent branch sums the series impedance and line charging, takes the more limiting thermal rating of the two sections, and intersects their angle limits. Chains of dummy buses collapse fully, one bus per step.
Sourcepub fn retype_isolated_buses(&mut self) -> usize
pub fn retype_isolated_buses(&mut self) -> usize
Retype to BusType::Isolated every bus with no in-service electrical
connection — no in-service incident branch, HVDC line, or 3-winding
transformer — returning the number retyped.
A stranded bus (retired or not-yet-built equipment, or the residue of a topology edit) otherwise keeps a PQ/PV/slack kind that tells a solver to include it, leaving an ungrounded singleton in the system. This only demotes a disconnected bus; it never promotes a connected one, and a bus the source already marks isolated is left untouched. Connectivity is judged on in-service equipment only, so opening the last branch into a bus makes it eligible.
Source§impl BalancedNetwork
impl BalancedNetwork
Sourcepub fn to_normalized_solver_tables(&self) -> Result<NormalizedSolverTables>
pub fn to_normalized_solver_tables(&self) -> Result<NormalizedSolverTables>
Lower this balanced network into normalized dense solver tables.
§Errors
Propagates BalancedNetwork::to_normalized errors and reports
Error::UnknownBus if the derived normalized network contains an
internal dangling bus reference.
Trait Implementations§
Source§impl Clone for BalancedNetwork
impl Clone for BalancedNetwork
Source§fn clone(&self) -> BalancedNetwork
fn clone(&self) -> BalancedNetwork
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl Debug for BalancedNetwork
impl Debug for BalancedNetwork
Source§impl<'de> Deserialize<'de> for BalancedNetwork
impl<'de> Deserialize<'de> for BalancedNetwork
Source§fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>
Source§impl JsonSchema for BalancedNetwork
Available on crate feature schema only.
impl JsonSchema for BalancedNetwork
schema only.Source§fn schema_id() -> Cow<'static, str>
fn schema_id() -> Cow<'static, str>
Source§fn json_schema(generator: &mut SchemaGenerator) -> Schema
fn json_schema(generator: &mut SchemaGenerator) -> Schema
Source§fn inline_schema() -> bool
fn inline_schema() -> bool
$ref keyword. Read more