powerio_matrix/dc_operators.rs
1//! The public DC matrix operations over a [`DcPfInstance`].
2//!
3//! The instance stays matrix free; these separate operations project it. The
4//! public values carry PowerModels signs — the branch susceptance is
5//! `imag(inv(series impedance))` under the selected formula, negative
6//! for an inductive branch — and every axis carries stable element mappings:
7//! bus axes use [`BusId`] in analysis row order, and branch axes map each
8//! column to its source branch or three winding transformer winding. With
9//! voltage angles `va` in radians, the branch flow identity is
10//!
11//! ```text
12//! p_branch = -Bf * va + b .* shift
13//! ```
14//!
15//! and the nodal balance is `p_bus = -B * va + p_shift`, all in per unit on
16//! the network MVA base. The reference constrained linear system a solver
17//! factors is stated over the internal positive factor weights (the positive
18//! semidefinite Laplacian, the negation of the public susceptances), with the
19//! sign conversion confined to filling public results.
20//!
21//! Injections update in place from the instance's specifications; the network
22//! dependent matrices are built once and an operating point update never
23//! reconstructs them.
24
25use crate::{AnalysisBranchSource, SparseMatrix};
26use powerio_core::Error;
27use powerio_tx::{BranchSusceptanceFormula, BusId, IndexedNetwork};
28
29use powerio_prob::diagnostics::codes;
30use powerio_prob::{DcBusSpecification, DcPfInstance};
31
32/// The DC-relevant identity and parameters of an analysis branch. Floating-
33/// point values are compared by bits so signed-zero or non-finite changes do
34/// not silently reuse operators built from different data.
35type DcBranchSignature = (Option<String>, BusId, BusId, u64, u64, u64, u64, bool);
36
37/// The stable row identity a mapping row reports: the element uid when one
38/// exists, else `table:row`.
39fn row_identity(uid: Option<&str>, table: &str, row: usize) -> String {
40 uid.map_or_else(|| format!("{table}:{row}"), str::to_owned)
41}
42
43/// The reference constrained linear system: the positive definite matrix a
44/// sparse solver factors, its right hand side, and the mapping from reduced
45/// rows back to bus rows.
46#[derive(Clone, Debug, PartialEq)]
47#[non_exhaustive]
48pub struct ReferenceConstrainedSystem {
49 /// The reference grounded positive semidefinite matrix, `n - r` square:
50 /// the internal positive factor weights, the negation of the public bus
51 /// susceptance matrix with the reference rows and columns removed.
52 pub matrix: SparseMatrix,
53 /// The right hand side: net injection minus phase shift injection at the
54 /// retained buses, plus coupling from eliminated reference buses, per unit.
55 pub rhs: Vec<f64>,
56 /// Reduced row to dense bus row.
57 pub retained_rows: Vec<usize>,
58}
59
60/// Build options for [`DcOperators`].
61///
62/// The default refuses a zero impedance branch, because it has no finite DC
63/// operator row. `skip_zero_impedance` drops such a branch from the operator
64/// axis instead and records its analysis row in
65/// [`DcOperators::skipped_branch_rows`], the same choice
66/// `BuildOptions::skip_zero_impedance` offers the admittance builders.
67#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
68#[non_exhaustive]
69pub struct DcOperatorOptions {
70 /// Drop a zero impedance branch instead of refusing the build.
71 pub skip_zero_impedance: bool,
72}
73
74impl DcOperatorOptions {
75 /// The default options: refuse a zero impedance branch.
76 #[must_use]
77 pub const fn new() -> Self {
78 Self {
79 skip_zero_impedance: false,
80 }
81 }
82
83 /// Set whether a zero impedance branch is dropped instead of refused.
84 #[must_use]
85 pub const fn with_skip_zero_impedance(mut self, skip: bool) -> Self {
86 self.skip_zero_impedance = skip;
87 self
88 }
89}
90
91/// DC matrix operations built once from an instance.
92#[derive(Clone, Debug)]
93pub struct DcOperators {
94 bus_ids: Vec<BusId>,
95 /// Original source bus IDs and their row order, before synthetic expansion.
96 source_bus_ids: Vec<BusId>,
97 /// DC-relevant branch data, including derived transformer windings, at build time.
98 analysis_branch_signature: Vec<DcBranchSignature>,
99 /// Network base and normalization state used to build the operators.
100 network_base_mva_bits: u64,
101 network_normalized: bool,
102 branch_identities: Vec<String>,
103 /// Operator column to the analysis branch row it was built from.
104 branch_rows: Vec<usize>,
105 /// Analysis branch rows dropped under `DcOperatorOptions::skip_zero_impedance`.
106 skipped_branch_rows: Vec<usize>,
107 options: DcOperatorOptions,
108 analysis_sources: Vec<AnalysisBranchSource>,
109 /// `n × m`, `+1` at the from bus and `-1` at the to bus of each branch.
110 incidence: SparseMatrix,
111 /// Public per branch susceptance, PowerModels signs.
112 branch_susceptance: Vec<f64>,
113 /// Per branch phase shift, radians (zero when the formula carries
114 /// no shift injections).
115 shift_radians: Vec<f64>,
116 /// Per column `(from row, to row)`, stored at build so no injection or
117 /// system fill rederives it from the incidence pattern.
118 endpoints: Vec<(usize, usize)>,
119 /// Net per unit injection at each bus from the instance specifications.
120 net_injection: Vec<f64>,
121 reference_rows: Vec<usize>,
122 /// The stated reference angle, radians, dense over every bus row.
123 /// Meaningful only at a row listed in `reference_rows`; every other row
124 /// holds zero and is never read.
125 reference_va_radians: Vec<f64>,
126 branch_susceptance_formula: BranchSusceptanceFormula,
127}
128
129impl DcOperators {
130 /// Build the operators. Zero impedance branches are preserved by the
131 /// instance and have no finite DC row, so they refuse the build until
132 /// resolved explicitly with
133 /// [`merge_zero_impedance_buses`](powerio_prob::merge_zero_impedance_buses); no
134 /// branch is ever skipped silently. Out of service branches and self
135 /// loops carry no operator column.
136 ///
137 /// # Errors
138 /// A zero impedance branch, a non-finite branch value, or a branch naming
139 /// an undeclared bus.
140 pub fn build(instance: &DcPfInstance) -> Result<Self, Error> {
141 Self::build_with(instance, &DcOperatorOptions::default())
142 }
143
144 /// Build the operators under explicit [`DcOperatorOptions`]. With
145 /// `skip_zero_impedance` set, a zero impedance branch is dropped from the
146 /// operator axis and listed by [`skipped_branch_rows`](Self::skipped_branch_rows)
147 /// instead of refusing the build; every other rule of [`build`](Self::build)
148 /// holds.
149 ///
150 /// # Errors
151 /// A zero impedance branch when it is not skipped, a non-finite branch
152 /// value, or a branch naming an undeclared bus.
153 // One pass over the branch table that fills every axis and operator
154 // column; splitting it would scatter the invariants the columns share.
155 #[expect(clippy::too_many_lines)]
156 pub fn build_with(instance: &DcPfInstance, options: &DcOperatorOptions) -> Result<Self, Error> {
157 let source = instance.network();
158 let source_bus_ids: Vec<BusId> = source.buses().iter().map(|bus| bus.id).collect();
159 let view = IndexedNetwork::new(source);
160 let network = view.network();
161 let formula = instance.branch_susceptance_formula();
162 let base = network.base_mva();
163 let analysis_branch_signature: Vec<DcBranchSignature> = network
164 .branches()
165 .iter()
166 .map(|branch| {
167 (
168 branch.uid.clone(),
169 branch.from,
170 branch.to,
171 branch.r.to_bits(),
172 branch.x.to_bits(),
173 branch.tap.to_bits(),
174 branch.shift.to_bits(),
175 branch.in_service,
176 )
177 })
178 .collect();
179 let network_base_mva_bits = base.to_bits();
180 let network_normalized = network.is_normalized();
181 let bus_ids: Vec<BusId> = network.buses().iter().map(|bus| bus.id).collect();
182 let row_of: std::collections::BTreeMap<BusId, usize> = bus_ids
183 .iter()
184 .enumerate()
185 .map(|(row, &id)| (id, row))
186 .collect();
187 let position_of = |bus: BusId| row_of.get(&bus).copied();
188
189 let mut branch_identities = Vec::new();
190 let mut branch_rows = Vec::new();
191 let mut skipped_branch_rows = Vec::new();
192 let mut active_analysis_sources = Vec::new();
193 let mut branch_susceptance = Vec::new();
194 let mut shift_radians = Vec::new();
195 let mut endpoints = Vec::new();
196 let analysis_sources = crate::opf::analysis_branch_sources(source);
197 for (row, branch) in network.branches().iter().enumerate() {
198 if !branch.in_service || branch.from == branch.to {
199 continue;
200 }
201 let identity = row_identity(branch.uid.as_deref(), "branches", row);
202 let (Some(from), Some(to)) = (position_of(branch.from), position_of(branch.to)) else {
203 return Err(Error::new(
204 &codes::BUILD_INSTANCE_SHAPE_MISMATCH,
205 format!(
206 "branch `{identity}` names bus {} or {} the network does not declare",
207 branch.from, branch.to
208 ),
209 ));
210 };
211 // The one DC column rule; only the error wording and the skip
212 // policy are this builder's.
213 let column = match formula.calc_dc_column(branch, row, network.is_normalized()) {
214 Ok(column) => column,
215 Err(powerio_tx::Error::DegenerateTap { .. }) => {
216 return Err(Error::new(
217 &codes::BUILD_OPERATOR_NOT_A_NUMBER,
218 format!(
219 "branch `{identity}` states a tap the selected formula cannot divide by"
220 ),
221 ));
222 }
223 Err(_) => {
224 return Err(Error::new(
225 &codes::BUILD_OPERATOR_ZERO_IMPEDANCE,
226 format!(
227 "branch `{identity}` has no finite DC susceptance under the selected formula; resolve it explicitly with merge_zero_impedance_buses"
228 ),
229 ));
230 }
231 };
232 let Some(column) = column else {
233 if options.skip_zero_impedance {
234 skipped_branch_rows.push(row);
235 continue;
236 }
237 return Err(Error::new(
238 &codes::BUILD_OPERATOR_ZERO_IMPEDANCE,
239 format!(
240 "zero impedance branch `{identity}` has no finite DC operator row; resolve it explicitly with merge_zero_impedance_buses or build with skip_zero_impedance"
241 ),
242 ));
243 };
244 // The public susceptance is the negated factor weight.
245 let susceptance = -column.weight;
246 let shift = column.shift;
247 if !shift.is_finite() {
248 return Err(Error::new(
249 &codes::BUILD_OPERATOR_NOT_A_NUMBER,
250 format!("branch `{identity}` states a non-finite phase shift"),
251 ));
252 }
253 branch_identities.push(identity);
254 branch_rows.push(row);
255 active_analysis_sources.push(analysis_sources[row]);
256 branch_susceptance.push(susceptance);
257 shift_radians.push(shift);
258 endpoints.push((from, to));
259 }
260
261 let incidence =
262 crate::matrix::assemble_bus_branch_incidence(bus_ids.len(), endpoints.iter().copied());
263 let mut operators = Self {
264 bus_ids,
265 source_bus_ids,
266 analysis_branch_signature,
267 network_base_mva_bits,
268 network_normalized,
269 branch_identities,
270 branch_rows,
271 skipped_branch_rows,
272 options: *options,
273 analysis_sources: active_analysis_sources,
274 incidence,
275 branch_susceptance,
276 shift_radians,
277 endpoints,
278 net_injection: Vec::new(),
279 reference_rows: Vec::new(),
280 reference_va_radians: Vec::new(),
281 branch_susceptance_formula: formula,
282 };
283 operators.refresh_injections(instance, base)?;
284 Ok(operators)
285 }
286
287 /// Refresh the injection vectors and reference rows from the instance's
288 /// current specifications. The network dependent matrices are untouched:
289 /// an operating point update goes through here and reconstructs nothing.
290 ///
291 /// # Errors
292 /// The source bus specification axis differs from the built axis, or the
293 /// network base, normalization state, DC formula, topology, or branch
294 /// parameters changed after the operators were built.
295 pub fn update(&mut self, instance: &DcPfInstance) -> Result<(), Error> {
296 let view = IndexedNetwork::new(instance.network());
297 let network = view.network();
298 let branch_signature: Vec<DcBranchSignature> = network
299 .branches()
300 .iter()
301 .map(|branch| {
302 (
303 branch.uid.clone(),
304 branch.from,
305 branch.to,
306 branch.r.to_bits(),
307 branch.x.to_bits(),
308 branch.tap.to_bits(),
309 branch.shift.to_bits(),
310 branch.in_service,
311 )
312 })
313 .collect();
314 // Expanded electrical branches alone do not identify their source
315 // rows: inserting an out-of-service three-winding transformer can
316 // shift transformer_row while leaving every expanded branch unchanged.
317 // Compare the source mapping for every operator column before touching
318 // any cached injections, so a rejected update leaves operators intact.
319 let current_sources = crate::opf::analysis_branch_sources(instance.network());
320 let source_mappings_match = self
321 .branch_rows
322 .iter()
323 .zip(&self.analysis_sources)
324 .all(|(&row, saved)| current_sources.get(row) == Some(saved));
325 if network.base_mva().to_bits() != self.network_base_mva_bits
326 || network.is_normalized() != self.network_normalized
327 || instance.branch_susceptance_formula() != self.branch_susceptance_formula
328 || branch_signature != self.analysis_branch_signature
329 || !source_mappings_match
330 {
331 return Err(Error::new(
332 &codes::BUILD_INSTANCE_SHAPE_MISMATCH,
333 "the network base, normalization, branch parameters, topology, source mappings, or DC formula differ from those used to build the DC operators; rebuild the operators before updating",
334 ));
335 }
336 self.refresh_injections(instance, network.base_mva())
337 }
338
339 fn refresh_injections(&mut self, instance: &DcPfInstance, base: f64) -> Result<(), Error> {
340 let source_buses = instance.network().buses();
341 let source_bus_count = source_buses.len();
342 if instance.specifications().len() != source_bus_count
343 || source_bus_count > self.bus_ids.len()
344 {
345 return Err(Error::new(
346 &codes::BUILD_INSTANCE_SHAPE_MISMATCH,
347 format!(
348 "the instance states {} bus specifications for {} source buses; the operators were built over {} analysis buses",
349 instance.specifications().len(),
350 source_bus_count,
351 self.bus_ids.len()
352 ),
353 ));
354 }
355 if source_buses
356 .iter()
357 .map(|bus| bus.id)
358 .ne(self.source_bus_ids.iter().copied())
359 {
360 return Err(Error::new(
361 &codes::BUILD_INSTANCE_SHAPE_MISMATCH,
362 "the instance bus IDs or bus order differ from the bus axis used to build the DC operators",
363 ));
364 }
365 let mut net_injection = vec![0.0; self.bus_ids.len()];
366 let mut reference_va_radians = vec![0.0; self.bus_ids.len()];
367 let mut reference_rows = Vec::new();
368 for (row, specification) in instance.specifications().iter().enumerate() {
369 match *specification {
370 DcBusSpecification::NetActivePower { p_mw } => {
371 net_injection[row] = p_mw / base;
372 }
373 DcBusSpecification::Reference { va_degrees } => {
374 reference_rows.push(row);
375 reference_va_radians[row] = va_degrees.to_radians();
376 }
377 _ => {}
378 }
379 }
380 self.net_injection = net_injection;
381 self.reference_rows = reference_rows;
382 self.reference_va_radians = reference_va_radians;
383 Ok(())
384 }
385
386 /// The selected branch susceptance formula.
387 #[must_use]
388 pub const fn branch_susceptance_formula(&self) -> BranchSusceptanceFormula {
389 self.branch_susceptance_formula
390 }
391
392 /// Dense bus row to bus id, the row mapping of every bus axis.
393 #[must_use]
394 pub fn bus_ids(&self) -> &[BusId] {
395 &self.bus_ids
396 }
397
398 /// Operator column to stable analysis branch identity.
399 #[must_use]
400 pub fn branch_identities(&self) -> &[String] {
401 &self.branch_identities
402 }
403
404 /// Operator column to the analysis branch row it represents: the
405 /// position in the network's branch table (three winding transformer
406 /// windings follow the branches). Out of service branches, self loops,
407 /// and skipped zero impedance branches have no column, so this is the
408 /// row selection every branch axis shares.
409 #[must_use]
410 pub fn branch_rows(&self) -> &[usize] {
411 &self.branch_rows
412 }
413
414 /// Analysis branch rows dropped under
415 /// [`DcOperatorOptions::skip_zero_impedance`], in table order. Empty
416 /// unless the option was set and a zero impedance branch existed.
417 #[must_use]
418 pub fn skipped_branch_rows(&self) -> &[usize] {
419 &self.skipped_branch_rows
420 }
421
422 /// The options the operators were built with.
423 #[must_use]
424 pub const fn options(&self) -> DcOperatorOptions {
425 self.options
426 }
427
428 /// Operator column to the source branch or three winding transformer
429 /// winding represented by that column.
430 #[must_use]
431 pub fn analysis_sources(&self) -> &[AnalysisBranchSource] {
432 &self.analysis_sources
433 }
434
435 /// The PowerModels incidence matrix `A`, `m × n`: each branch row has
436 /// `+1` at its from bus and `-1` at its to bus.
437 #[must_use]
438 pub fn calc_incidence_matrix(&self) -> SparseMatrix {
439 self.incidence.transpose_view().to_csr()
440 }
441
442 /// Calculate the per branch susceptances `b`, with PowerModels signs.
443 #[must_use]
444 pub fn calc_branch_susceptances(&self) -> &[f64] {
445 &self.branch_susceptance
446 }
447
448 /// Calculate the branch flow matrix `Bf = Diagonal(b) * A`, `m × n`.
449 #[must_use]
450 pub fn calc_branch_flow_matrix(&self) -> SparseMatrix {
451 crate::matrix::calc_solver_branch_flow_matrix(&self.incidence, &self.branch_susceptance)
452 }
453
454 /// Calculate the bus susceptance matrix `B = Aᵀ * Diagonal(b) * A`, `n × n`.
455 #[must_use]
456 pub fn calc_bus_susceptance_matrix(&self) -> SparseMatrix {
457 crate::matrix::calc_weighted_laplacian(&self.incidence, &self.branch_susceptance)
458 }
459
460 /// The per bus net power injection the instance states, per unit on the
461 /// network MVA base, in bus row order.
462 #[must_use]
463 pub fn bus_power_injection(&self) -> &[f64] {
464 &self.net_injection
465 }
466
467 /// Calculate the branch phase shift injection `b .* shift` in branch
468 /// order.
469 #[must_use]
470 pub fn calc_branch_phase_shift_injection(&self) -> Vec<f64> {
471 self.branch_susceptance
472 .iter()
473 .zip(self.shift_radians.iter())
474 .map(|(&susceptance, &shift)| crate::matrix::calc_dc_flow_offset(-susceptance, shift))
475 .collect()
476 }
477
478 /// Calculate the bus phase shift injection
479 /// `p_shift = Aᵀ * (b .* shift)` in bus order.
480 #[must_use]
481 pub fn calc_bus_phase_shift_injection(&self) -> Vec<f64> {
482 // The positive factor weight is the negated public susceptance; the
483 // scatter is the crate's one phase shift withdrawal over it.
484 crate::matrix::calc_dc_phase_shift_withdrawal(
485 self.bus_ids.len(),
486 self.endpoints
487 .iter()
488 .copied()
489 .zip(self.branch_susceptance.iter())
490 .zip(self.shift_radians.iter().copied())
491 .map(|((endpoints, &susceptance), shift)| (endpoints, -susceptance, shift)),
492 )
493 }
494
495 /// Calculate DC active power flow in branch order from bus voltage angles
496 /// in radians: `p_branch = -Bf va + b .* shift`.
497 ///
498 /// # Errors
499 /// The voltage angle length differs from the bus axis length.
500 pub fn calc_branch_flow_dc(&self, voltage_angles: &[f64]) -> Result<Vec<f64>, Error> {
501 if voltage_angles.len() != self.bus_ids.len() {
502 return Err(Error::new(
503 &codes::BUILD_INSTANCE_SHAPE_MISMATCH,
504 format!(
505 "voltage_angles has length {}; expected {} for the bus axis",
506 voltage_angles.len(),
507 self.bus_ids.len()
508 ),
509 ));
510 }
511 // The positive factor weight is the negated public susceptance; the
512 // flow is the crate's one DC flow over it.
513 Ok(crate::matrix::calc_dc_branch_flow(
514 voltage_angles,
515 self.endpoints
516 .iter()
517 .copied()
518 .zip(self.branch_susceptance.iter())
519 .zip(self.shift_radians.iter().copied())
520 .map(|((endpoints, &susceptance), shift)| (endpoints, -susceptance, shift)),
521 ))
522 }
523
524 /// Calculate DC active power injection in bus order from bus voltage
525 /// angles in radians: `p_bus = -B va + p_shift`.
526 ///
527 /// # Errors
528 /// The voltage angle length differs from the bus axis length.
529 pub fn calc_bus_injection_dc(&self, voltage_angles: &[f64]) -> Result<Vec<f64>, Error> {
530 let branch_flows = self.calc_branch_flow_dc(voltage_angles)?;
531 Ok(crate::matrix::calc_bus_scatter(
532 self.bus_ids.len(),
533 self.endpoints.iter().copied().zip(branch_flows),
534 ))
535 }
536
537 /// Calculate the reference constrained linear system over the internal positive
538 /// factor weights: the reference grounded positive semidefinite matrix
539 /// `L = -B` with reference rows and columns removed, and the right hand
540 /// side at the retained buses is `p - p_shift` (from `p = -B va +
541 /// p_shift`) plus the coupling carried in from every eliminated
542 /// reference bus's stated angle, radians, so `L_grounded va = rhs`
543 /// solves the stated problem with each reference bus fixed at the angle
544 /// it states rather than at zero. Sign conversion from the public
545 /// susceptances is confined to this fill.
546 ///
547 /// # Errors
548 /// An instance with no reference row.
549 pub fn calc_reference_constrained_system(&self) -> Result<ReferenceConstrainedSystem, Error> {
550 if self.reference_rows.is_empty() {
551 return Err(Error::new(
552 &codes::BUILD_INSTANCE_NO_REFERENCE_BUS,
553 "the instance states no reference bus to ground the system",
554 ));
555 }
556 // The internal positive factor weights are the negated public
557 // susceptances; the grounded matrix is the crate's one weighted
558 // Laplacian with the reference rows and columns removed.
559 let weights: Vec<f64> = self.branch_susceptance.iter().map(|b| -b).collect();
560 let laplacian = crate::matrix::calc_weighted_laplacian(&self.incidence, &weights);
561 let shift_injection = self.calc_bus_phase_shift_injection();
562 let injection: Vec<f64> = self
563 .net_injection
564 .iter()
565 .zip(&shift_injection)
566 .map(|(p, shift)| p - shift)
567 .collect();
568 let reference_va: Vec<f64> = self
569 .reference_rows
570 .iter()
571 .map(|&row| self.reference_va_radians[row])
572 .collect();
573 Ok(calc_reference_constrained_system(
574 &laplacian,
575 &self.reference_rows,
576 &reference_va,
577 &injection,
578 ))
579 }
580}
581
582/// The reference constrained linear system of a DC power flow over a bus
583/// Laplacian `L` with positive branch weights: `L` with the reference rows and
584/// columns removed, and at each retained row the right hand side
585/// `injection - (L va_ref)`, where `va_ref` holds each reference row's angle,
586/// radians, and zero elsewhere. `injection` is the full length nodal power
587/// the angles must carry (net injection less every fixed withdrawal), per
588/// unit; `reference_va` is aligned with `reference_rows`. Solving
589/// `matrix · va = rhs` gives the retained angles with each reference fixed at
590/// its stated angle. [`DcOperators::calc_reference_constrained_system`] is this
591/// over the instance's operators.
592///
593/// # Panics
594/// `injection` shorter than the Laplacian's row count, or a reference row
595/// outside it.
596#[must_use]
597pub fn calc_reference_constrained_system(
598 laplacian: &SparseMatrix,
599 reference_rows: &[usize],
600 reference_va: &[f64],
601 injection: &[f64],
602) -> ReferenceConstrainedSystem {
603 let n = laplacian.rows();
604 let grounding = crate::matrix::Grounding::new(reference_rows);
605 let retained_rows = grounding.full_of_reduced(n);
606 // A branch to an eliminated reference bus still carries an off-diagonal
607 // Laplacian entry; since its column is gone, its contribution moves to the
608 // retained row's right hand side, carrying the reference bus's stated
609 // angle in. With every reference at zero there is nothing to carry.
610 let mut reference_angles = vec![0.0; n];
611 for (&row, &va) in reference_rows.iter().zip(reference_va) {
612 reference_angles[row] = va;
613 }
614 let reference_load = if reference_angles.iter().any(|&va| va != 0.0) {
615 crate::matrix::calc_csr_product(laplacian, &reference_angles)
616 } else {
617 vec![0.0; n]
618 };
619 let rhs = retained_rows
620 .iter()
621 .map(|&row| injection[row] - reference_load[row])
622 .collect();
623 ReferenceConstrainedSystem {
624 matrix: crate::matrix::ground_with(laplacian, &grounding),
625 rhs,
626 retained_rows,
627 }
628}