powerio-prob 0.10.0

Problem instance builders for power system analysis and optimization.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
//! The balanced solutions: `DcPfSolution`, `AcPfSolution`, `DcOpfSolution`,
//! and `AcOpfSolution`.
//!
//! Values are stored in the shared network's table order and read back by
//! stable identity: buses by [`BusId`], branches and generators by payload
//! identity (`uid`, else `{table}:{row}`). Bus injections, bus voltages, and
//! branch flows are required on the power flow solutions; individual
//! generator outputs stay optional unless the instance determines them
//! uniquely or the source records an explicit allocation, and the OPF
//! solutions require the dispatch they optimized.

use std::sync::Arc;

use powerio_core::Error;
use powerio_tx::{BalancedNetwork, BusId};

use crate::diagnostics::codes;
use crate::instance::{AcOpfInstance, AcPfInstance, DcOpfInstance, DcPfInstance};
use crate::solution::{Producer, Residuals, Termination};
use crate::state::row_identity;

/// Optional per generator dispatch, in generator table order.
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct GeneratorDispatch {
    /// Active power per generator, MW.
    pub p_mw: Vec<f64>,
    /// Reactive power per generator, MVAr; empty for a DC result.
    pub q_mvar: Vec<f64>,
}

fn check_length(what: &'static str, got: usize, expected: usize) -> Result<(), Error> {
    if got == expected {
        Ok(())
    } else {
        Err(Error::new(
            &codes::BUILD_SOLUTION_SHAPE_MISMATCH,
            format!("{what} carries {got} values; the instance's table has {expected} rows"),
        ))
    }
}

/// Identity to row position over one network's tables, built once per
/// solution on first keyed access so repeated reads never rescan a table.
#[derive(Clone, Debug, Default)]
struct SolutionIndex {
    bus: std::collections::BTreeMap<BusId, usize>,
    branch: std::collections::BTreeMap<String, usize>,
    generator: std::collections::BTreeMap<String, usize>,
}

impl SolutionIndex {
    fn build(network: &BalancedNetwork) -> Result<Self, Error> {
        let mut index = Self::default();
        for (row, bus) in network.buses().iter().enumerate() {
            if index.bus.insert(bus.id, row).is_some() {
                return Err(duplicate_identity("bus", &bus.id.to_string()));
            }
        }
        for (row, branch) in network.branches().iter().enumerate() {
            let identity = row_identity(branch.uid.as_deref(), "branches", row);
            if index.branch.insert(identity.clone(), row).is_some() {
                return Err(duplicate_identity("branch", &identity));
            }
        }
        for (row, generator) in network.generators().iter().enumerate() {
            let identity = row_identity(generator.uid.as_deref(), "generators", row);
            if index.generator.insert(identity.clone(), row).is_some() {
                return Err(duplicate_identity("generator", &identity));
            }
        }
        Ok(index)
    }
}

/// The identity index a solution constructor builds once, refusing a network
/// whose resolved identities are not all distinct so every keyed accessor
/// reads its own row.
fn solution_index<I>(instance: &std::sync::Arc<I>) -> Result<SolutionIndex, Error>
where
    I: NetworkCarrier,
{
    SolutionIndex::build(instance.network())
}

/// The one thing solution_index needs from each instance type.
trait NetworkCarrier {
    fn network(&self) -> &BalancedNetwork;
}

impl NetworkCarrier for DcPfInstance {
    fn network(&self) -> &BalancedNetwork {
        DcPfInstance::network(self)
    }
}
impl NetworkCarrier for AcPfInstance {
    fn network(&self) -> &BalancedNetwork {
        AcPfInstance::network(self)
    }
}
impl NetworkCarrier for DcOpfInstance {
    fn network(&self) -> &BalancedNetwork {
        DcOpfInstance::network(self)
    }
}
impl NetworkCarrier for AcOpfInstance {
    fn network(&self) -> &BalancedNetwork {
        AcOpfInstance::network(self)
    }
}

fn duplicate_identity(kind: &str, identity: &str) -> Error {
    Error::new(
        &codes::BUILD_STATE_IDENTITY_UNKNOWN,
        format!("{kind}: duplicate element identity `{identity}`"),
    )
}

fn bus_position(index: &SolutionIndex, bus: BusId) -> Option<usize> {
    index.bus.get(&bus).copied()
}

fn branch_position(index: &SolutionIndex, identity: &str) -> Option<usize> {
    index.branch.get(identity).copied()
}

fn generator_position(index: &SolutionIndex, identity: &str) -> Option<usize> {
    index.generator.get(identity).copied()
}

macro_rules! shared_solution_accessors {
    ($instance_type:ty) => {
        /// The immutable instance this solution solves. Borrowed; never a
        /// copy.
        #[must_use]
        pub fn instance(&self) -> &$instance_type {
            &self.instance
        }

        /// The shared instance owner, for another solution of the same
        /// problem.
        #[must_use]
        pub fn shared_instance(&self) -> Arc<$instance_type> {
            Arc::clone(&self.instance)
        }

        /// The network the solved instance calculates on.
        #[must_use]
        pub fn network(&self) -> &BalancedNetwork {
            self.instance.network()
        }

        fn row_index(&self) -> &SolutionIndex {
            &self.index
        }

        /// Bus IDs in the column order every bulk accessor uses.
        #[must_use]
        pub fn bus_order(&self) -> Vec<BusId> {
            self.network().buses().iter().map(|bus| bus.id).collect()
        }

        /// Stable branch identities in bulk column order.
        #[must_use]
        pub fn branch_order(&self) -> Vec<String> {
            self.network()
                .branches()
                .iter()
                .enumerate()
                .map(|(row, branch)| row_identity(branch.uid.as_deref(), "branches", row))
                .collect()
        }

        /// Stable generator identities in bulk column order.
        #[must_use]
        pub fn generator_order(&self) -> Vec<String> {
            self.network()
                .generators()
                .iter()
                .enumerate()
                .map(|(row, generator)| row_identity(generator.uid.as_deref(), "generators", row))
                .collect()
        }

        /// How the producing calculation ended.
        #[must_use]
        pub fn termination(&self) -> &Termination {
            &self.termination
        }

        /// The reported numerical residuals.
        #[must_use]
        pub fn residuals(&self) -> &Residuals {
            &self.residuals
        }

        /// The producer or solver identity, when recorded.
        #[must_use]
        pub fn producer(&self) -> Option<&str> {
            self.producer.as_deref()
        }

        /// Record the producer identity.
        #[must_use]
        pub fn with_producer(mut self, producer: impl Into<String>) -> Self {
            self.producer = Some(producer.into());
            self
        }

        /// Record the numerical residuals.
        #[must_use]
        pub fn with_residuals(mut self, residuals: Residuals) -> Self {
            self.residuals = residuals;
            self
        }

        /// The branch identities the flow columns follow, in table order.
        pub fn branch_identity_order(&self) -> impl Iterator<Item = String> + '_ {
            self.network()
                .branches()
                .iter()
                .enumerate()
                .map(|(row, branch)| row_identity(branch.uid.as_deref(), "branches", row))
        }
    };
}

macro_rules! optional_dispatch_accessors {
    () => {
        /// Per generator dispatch, when the instance determines it uniquely
        /// or the source records an explicit allocation.
        #[must_use]
        pub fn generator_dispatch(&self) -> Option<&GeneratorDispatch> {
            self.generator_dispatch.as_ref()
        }

        /// Record an explicit per generator allocation.
        ///
        /// # Errors
        /// A dispatch whose length disagrees with the generator table.
        pub fn with_generator_dispatch(
            mut self,
            dispatch: GeneratorDispatch,
        ) -> Result<Self, Error> {
            check_length(
                "generator dispatch",
                dispatch.p_mw.len(),
                self.network().generators().len(),
            )?;
            if !dispatch.q_mvar.is_empty() {
                check_length(
                    "generator reactive dispatch",
                    dispatch.q_mvar.len(),
                    self.network().generators().len(),
                )?;
            }
            self.generator_dispatch = Some(dispatch);
            Ok(self)
        }
    };
}

/// The DC power flow solution: bus angles and injections and branch terminal
/// active flows over the shared instance.
#[derive(Clone, Debug)]
pub struct DcPfSolution {
    instance: Arc<DcPfInstance>,
    termination: Termination,
    residuals: Residuals,
    producer: Producer,
    bus_voltage_angle: Vec<f64>,
    bus_active_injection: Vec<f64>,
    branch_from_active_flow: Vec<f64>,
    branch_to_active_flow: Vec<f64>,
    generator_dispatch: Option<GeneratorDispatch>,
    index: SolutionIndex,
}

impl DcPfSolution {
    /// Assemble the required results: per bus voltage angles (degrees) and
    /// net active injections (MW) in bus table order, and per branch terminal
    /// active flows (MW, into the branch at each terminal) in branch table
    /// order.
    ///
    /// # Errors
    /// A column whose length disagrees with the instance's tables.
    pub fn new(
        instance: Arc<DcPfInstance>,
        termination: Termination,
        bus_voltage_angle: Vec<f64>,
        bus_active_injection: Vec<f64>,
        branch_from_active_flow: Vec<f64>,
        branch_to_active_flow: Vec<f64>,
    ) -> Result<Self, Error> {
        let buses = instance.network().buses().len();
        let branches = instance.network().branches().len();
        check_length("bus voltage angles", bus_voltage_angle.len(), buses)?;
        check_length("bus active injections", bus_active_injection.len(), buses)?;
        check_length(
            "branch from-side flows",
            branch_from_active_flow.len(),
            branches,
        )?;
        check_length(
            "branch to-side flows",
            branch_to_active_flow.len(),
            branches,
        )?;
        let index = solution_index(&instance)?;
        Ok(Self {
            instance,
            termination,
            residuals: Residuals::default(),
            producer: None,
            bus_voltage_angle,
            bus_active_injection,
            branch_from_active_flow,
            branch_to_active_flow,
            generator_dispatch: None,
            index,
        })
    }

    shared_solution_accessors!(DcPfInstance);
    optional_dispatch_accessors!();

    /// Voltage angle at one bus, degrees.
    #[must_use]
    pub fn bus_voltage_angle(&self, bus: BusId) -> Option<f64> {
        Some(self.bus_voltage_angle[bus_position(self.row_index(), bus)?])
    }

    /// Net active injection at one bus, MW.
    #[must_use]
    pub fn bus_active_injection(&self, bus: BusId) -> Option<f64> {
        Some(self.bus_active_injection[bus_position(self.row_index(), bus)?])
    }

    /// Active flow into the branch at its from terminal, MW, by stable
    /// branch identity.
    #[must_use]
    pub fn branch_from_active_flow(&self, identity: &str) -> Option<f64> {
        Some(self.branch_from_active_flow[branch_position(self.row_index(), identity)?])
    }

    /// Active flow into the branch at its to terminal, MW.
    #[must_use]
    pub fn branch_to_active_flow(&self, identity: &str) -> Option<f64> {
        Some(self.branch_to_active_flow[branch_position(self.row_index(), identity)?])
    }

    /// The complete `bus_voltage_angle` column, in `bus_order`.
    #[must_use]
    pub fn bus_voltage_angles(&self) -> &[f64] {
        &self.bus_voltage_angle
    }
    /// The complete `bus_active_injection` column, in `bus_order`.
    #[must_use]
    pub fn bus_active_injections(&self) -> &[f64] {
        &self.bus_active_injection
    }
    /// The complete `branch_from_active_flow` column, in `branch_order`.
    #[must_use]
    pub fn branch_from_active_flows(&self) -> &[f64] {
        &self.branch_from_active_flow
    }
    /// The complete `branch_to_active_flow` column, in `branch_order`.
    #[must_use]
    pub fn branch_to_active_flows(&self) -> &[f64] {
        &self.branch_to_active_flow
    }
}

/// The AC power flow solution: complex bus voltages, active and reactive bus
/// injections, and terminal branch flows over the shared instance.
#[derive(Clone, Debug)]
pub struct AcPfSolution {
    instance: Arc<AcPfInstance>,
    termination: Termination,
    residuals: Residuals,
    producer: Producer,
    bus_voltage_magnitude: Vec<f64>,
    bus_voltage_angle: Vec<f64>,
    bus_active_injection: Vec<f64>,
    bus_reactive_injection: Vec<f64>,
    branch_from_active_flow: Vec<f64>,
    branch_from_reactive_flow: Vec<f64>,
    branch_to_active_flow: Vec<f64>,
    branch_to_reactive_flow: Vec<f64>,
    generator_dispatch: Option<GeneratorDispatch>,
    index: SolutionIndex,
}

impl AcPfSolution {
    /// Assemble the required results: per bus voltage magnitudes (per unit)
    /// and angles (degrees), net injections (MW, MVAr) in bus table order,
    /// and per branch terminal flows (MW, MVAr into the branch at each
    /// terminal) in branch table order.
    ///
    /// # Errors
    /// A column whose length disagrees with the instance's tables.
    #[allow(clippy::too_many_arguments)] // the required result set is the signature
    pub fn new(
        instance: Arc<AcPfInstance>,
        termination: Termination,
        bus_voltage_magnitude: Vec<f64>,
        bus_voltage_angle: Vec<f64>,
        bus_active_injection: Vec<f64>,
        bus_reactive_injection: Vec<f64>,
        branch_from_active_flow: Vec<f64>,
        branch_from_reactive_flow: Vec<f64>,
        branch_to_active_flow: Vec<f64>,
        branch_to_reactive_flow: Vec<f64>,
    ) -> Result<Self, Error> {
        let buses = instance.network().buses().len();
        let branches = instance.network().branches().len();
        check_length("bus voltage magnitudes", bus_voltage_magnitude.len(), buses)?;
        check_length("bus voltage angles", bus_voltage_angle.len(), buses)?;
        check_length("bus active injections", bus_active_injection.len(), buses)?;
        check_length(
            "bus reactive injections",
            bus_reactive_injection.len(),
            buses,
        )?;
        check_length(
            "branch from-side active flows",
            branch_from_active_flow.len(),
            branches,
        )?;
        check_length(
            "branch from-side reactive flows",
            branch_from_reactive_flow.len(),
            branches,
        )?;
        check_length(
            "branch to-side active flows",
            branch_to_active_flow.len(),
            branches,
        )?;
        check_length(
            "branch to-side reactive flows",
            branch_to_reactive_flow.len(),
            branches,
        )?;
        let index = solution_index(&instance)?;
        Ok(Self {
            instance,
            termination,
            residuals: Residuals::default(),
            producer: None,
            bus_voltage_magnitude,
            bus_voltage_angle,
            bus_active_injection,
            bus_reactive_injection,
            branch_from_active_flow,
            branch_from_reactive_flow,
            branch_to_active_flow,
            branch_to_reactive_flow,
            generator_dispatch: None,
            index,
        })
    }

    shared_solution_accessors!(AcPfInstance);
    optional_dispatch_accessors!();

    /// Voltage magnitude at one bus, per unit.
    #[must_use]
    pub fn bus_voltage_magnitude(&self, bus: BusId) -> Option<f64> {
        Some(self.bus_voltage_magnitude[bus_position(self.row_index(), bus)?])
    }

    /// Voltage angle at one bus, degrees.
    #[must_use]
    pub fn bus_voltage_angle(&self, bus: BusId) -> Option<f64> {
        Some(self.bus_voltage_angle[bus_position(self.row_index(), bus)?])
    }

    /// Net active injection at one bus, MW.
    #[must_use]
    pub fn bus_active_injection(&self, bus: BusId) -> Option<f64> {
        Some(self.bus_active_injection[bus_position(self.row_index(), bus)?])
    }

    /// Net reactive injection at one bus, MVAr.
    #[must_use]
    pub fn bus_reactive_injection(&self, bus: BusId) -> Option<f64> {
        Some(self.bus_reactive_injection[bus_position(self.row_index(), bus)?])
    }

    /// Active flow into the branch at its from terminal, MW, by stable
    /// branch identity.
    #[must_use]
    pub fn branch_from_active_flow(&self, identity: &str) -> Option<f64> {
        Some(self.branch_from_active_flow[branch_position(self.row_index(), identity)?])
    }

    /// Reactive flow into the branch at its from terminal, MVAr.
    #[must_use]
    pub fn branch_from_reactive_flow(&self, identity: &str) -> Option<f64> {
        Some(self.branch_from_reactive_flow[branch_position(self.row_index(), identity)?])
    }

    /// Active flow into the branch at its to terminal, MW.
    #[must_use]
    pub fn branch_to_active_flow(&self, identity: &str) -> Option<f64> {
        Some(self.branch_to_active_flow[branch_position(self.row_index(), identity)?])
    }

    /// Reactive flow into the branch at its to terminal, MVAr.
    #[must_use]
    pub fn branch_to_reactive_flow(&self, identity: &str) -> Option<f64> {
        Some(self.branch_to_reactive_flow[branch_position(self.row_index(), identity)?])
    }
}

/// The DC optimal power flow solution: the DC power flow results plus the
/// optimized generator active dispatch and the objective value.
#[derive(Clone, Debug)]
pub struct DcOpfSolution {
    instance: Arc<DcOpfInstance>,
    termination: Termination,
    residuals: Residuals,
    producer: Producer,
    bus_voltage_angle: Vec<f64>,
    bus_active_injection: Vec<f64>,
    branch_from_active_flow: Vec<f64>,
    branch_to_active_flow: Vec<f64>,
    generator_active_power: Vec<f64>,
    objective: f64,
    index: SolutionIndex,
}

impl DcOpfSolution {
    /// Assemble the results: the DC power flow columns, the optimized per
    /// generator active dispatch (MW, generator table order), and the
    /// objective value.
    ///
    /// # Errors
    /// A column whose length disagrees with the instance's tables.
    #[allow(clippy::too_many_arguments)] // the required result set is the signature
    pub fn new(
        instance: Arc<DcOpfInstance>,
        termination: Termination,
        bus_voltage_angle: Vec<f64>,
        bus_active_injection: Vec<f64>,
        branch_from_active_flow: Vec<f64>,
        branch_to_active_flow: Vec<f64>,
        generator_active_power: Vec<f64>,
        objective: f64,
    ) -> Result<Self, Error> {
        let buses = instance.network().buses().len();
        let branches = instance.network().branches().len();
        check_length("bus voltage angles", bus_voltage_angle.len(), buses)?;
        check_length("bus active injections", bus_active_injection.len(), buses)?;
        check_length(
            "branch from-side flows",
            branch_from_active_flow.len(),
            branches,
        )?;
        check_length(
            "branch to-side flows",
            branch_to_active_flow.len(),
            branches,
        )?;
        check_length(
            "generator active dispatch",
            generator_active_power.len(),
            instance.network().generators().len(),
        )?;
        let index = solution_index(&instance)?;
        Ok(Self {
            instance,
            termination,
            residuals: Residuals::default(),
            producer: None,
            bus_voltage_angle,
            bus_active_injection,
            branch_from_active_flow,
            branch_to_active_flow,
            generator_active_power,
            objective,
            index,
        })
    }

    shared_solution_accessors!(DcOpfInstance);

    /// The optimized objective value.
    #[must_use]
    pub const fn objective(&self) -> f64 {
        self.objective
    }

    /// Optimized active power of one generator, MW, by stable identity.
    #[must_use]
    pub fn generator_active_power(&self, identity: &str) -> Option<f64> {
        Some(self.generator_active_power[generator_position(self.row_index(), identity)?])
    }

    /// Voltage angle at one bus, degrees.
    #[must_use]
    pub fn bus_voltage_angle(&self, bus: BusId) -> Option<f64> {
        Some(self.bus_voltage_angle[bus_position(self.row_index(), bus)?])
    }

    /// Net active injection at one bus, MW.
    #[must_use]
    pub fn bus_active_injection(&self, bus: BusId) -> Option<f64> {
        Some(self.bus_active_injection[bus_position(self.row_index(), bus)?])
    }

    /// Active flow into the branch at its from terminal, MW.
    #[must_use]
    pub fn branch_from_active_flow(&self, identity: &str) -> Option<f64> {
        Some(self.branch_from_active_flow[branch_position(self.row_index(), identity)?])
    }

    /// Active flow into the branch at its to terminal, MW.
    #[must_use]
    pub fn branch_to_active_flow(&self, identity: &str) -> Option<f64> {
        Some(self.branch_to_active_flow[branch_position(self.row_index(), identity)?])
    }
}

/// The AC optimal power flow solution: the AC power flow results plus the
/// optimized generator active and reactive dispatch and the objective value.
#[derive(Clone, Debug)]
pub struct AcOpfSolution {
    instance: Arc<AcOpfInstance>,
    termination: Termination,
    residuals: Residuals,
    producer: Producer,
    bus_voltage_magnitude: Vec<f64>,
    bus_voltage_angle: Vec<f64>,
    bus_active_injection: Vec<f64>,
    bus_reactive_injection: Vec<f64>,
    branch_from_active_flow: Vec<f64>,
    branch_from_reactive_flow: Vec<f64>,
    branch_to_active_flow: Vec<f64>,
    branch_to_reactive_flow: Vec<f64>,
    generator_active_power: Vec<f64>,
    generator_reactive_power: Vec<f64>,
    objective: f64,
    index: SolutionIndex,
}

impl AcOpfSolution {
    /// Assemble the results: the AC power flow columns, the optimized per
    /// generator dispatch (MW and MVAr, generator table order), and the
    /// objective value.
    ///
    /// # Errors
    /// A column whose length disagrees with the instance's tables.
    #[allow(clippy::too_many_arguments)] // the required result set is the signature
    pub fn new(
        instance: Arc<AcOpfInstance>,
        termination: Termination,
        bus_voltage_magnitude: Vec<f64>,
        bus_voltage_angle: Vec<f64>,
        bus_active_injection: Vec<f64>,
        bus_reactive_injection: Vec<f64>,
        branch_from_active_flow: Vec<f64>,
        branch_from_reactive_flow: Vec<f64>,
        branch_to_active_flow: Vec<f64>,
        branch_to_reactive_flow: Vec<f64>,
        generator_active_power: Vec<f64>,
        generator_reactive_power: Vec<f64>,
        objective: f64,
    ) -> Result<Self, Error> {
        let buses = instance.network().buses().len();
        let branches = instance.network().branches().len();
        let generators = instance.network().generators().len();
        check_length("bus voltage magnitudes", bus_voltage_magnitude.len(), buses)?;
        check_length("bus voltage angles", bus_voltage_angle.len(), buses)?;
        check_length("bus active injections", bus_active_injection.len(), buses)?;
        check_length(
            "bus reactive injections",
            bus_reactive_injection.len(),
            buses,
        )?;
        check_length(
            "branch from-side active flows",
            branch_from_active_flow.len(),
            branches,
        )?;
        check_length(
            "branch from-side reactive flows",
            branch_from_reactive_flow.len(),
            branches,
        )?;
        check_length(
            "branch to-side active flows",
            branch_to_active_flow.len(),
            branches,
        )?;
        check_length(
            "branch to-side reactive flows",
            branch_to_reactive_flow.len(),
            branches,
        )?;
        check_length(
            "generator active dispatch",
            generator_active_power.len(),
            generators,
        )?;
        check_length(
            "generator reactive dispatch",
            generator_reactive_power.len(),
            generators,
        )?;
        let index = solution_index(&instance)?;
        Ok(Self {
            instance,
            termination,
            residuals: Residuals::default(),
            producer: None,
            bus_voltage_magnitude,
            bus_voltage_angle,
            bus_active_injection,
            bus_reactive_injection,
            branch_from_active_flow,
            branch_from_reactive_flow,
            branch_to_active_flow,
            branch_to_reactive_flow,
            generator_active_power,
            generator_reactive_power,
            objective,
            index,
        })
    }

    shared_solution_accessors!(AcOpfInstance);

    /// The optimized objective value.
    #[must_use]
    pub const fn objective(&self) -> f64 {
        self.objective
    }

    /// Optimized active power of one generator, MW, by stable identity.
    #[must_use]
    pub fn generator_active_power(&self, identity: &str) -> Option<f64> {
        Some(self.generator_active_power[generator_position(self.row_index(), identity)?])
    }

    /// Optimized reactive power of one generator, MVAr.
    #[must_use]
    pub fn generator_reactive_power(&self, identity: &str) -> Option<f64> {
        Some(self.generator_reactive_power[generator_position(self.row_index(), identity)?])
    }

    /// Voltage magnitude at one bus, per unit.
    #[must_use]
    pub fn bus_voltage_magnitude(&self, bus: BusId) -> Option<f64> {
        Some(self.bus_voltage_magnitude[bus_position(self.row_index(), bus)?])
    }

    /// Voltage angle at one bus, degrees.
    #[must_use]
    pub fn bus_voltage_angle(&self, bus: BusId) -> Option<f64> {
        Some(self.bus_voltage_angle[bus_position(self.row_index(), bus)?])
    }

    /// Net active injection at one bus, MW.
    #[must_use]
    pub fn bus_active_injection(&self, bus: BusId) -> Option<f64> {
        Some(self.bus_active_injection[bus_position(self.row_index(), bus)?])
    }

    /// Net reactive injection at one bus, MVAr.
    #[must_use]
    pub fn bus_reactive_injection(&self, bus: BusId) -> Option<f64> {
        Some(self.bus_reactive_injection[bus_position(self.row_index(), bus)?])
    }

    /// Active flow into the branch at its from terminal, MW.
    #[must_use]
    pub fn branch_from_active_flow(&self, identity: &str) -> Option<f64> {
        Some(self.branch_from_active_flow[branch_position(self.row_index(), identity)?])
    }

    /// Reactive flow into the branch at its from terminal, MVAr.
    #[must_use]
    pub fn branch_from_reactive_flow(&self, identity: &str) -> Option<f64> {
        Some(self.branch_from_reactive_flow[branch_position(self.row_index(), identity)?])
    }

    /// Active flow into the branch at its to terminal, MW.
    #[must_use]
    pub fn branch_to_active_flow(&self, identity: &str) -> Option<f64> {
        Some(self.branch_to_active_flow[branch_position(self.row_index(), identity)?])
    }

    /// Reactive flow into the branch at its to terminal, MVAr.
    #[must_use]
    pub fn branch_to_reactive_flow(&self, identity: &str) -> Option<f64> {
        Some(self.branch_to_reactive_flow[branch_position(self.row_index(), identity)?])
    }

    /// The complete `bus_voltage_magnitude` column, in `bus_order`.
    #[must_use]
    pub fn bus_voltage_magnitudes(&self) -> &[f64] {
        &self.bus_voltage_magnitude
    }
    /// The complete `bus_voltage_angle` column, in `bus_order`.
    #[must_use]
    pub fn bus_voltage_angles(&self) -> &[f64] {
        &self.bus_voltage_angle
    }
    /// The complete `bus_active_injection` column, in `bus_order`.
    #[must_use]
    pub fn bus_active_injections(&self) -> &[f64] {
        &self.bus_active_injection
    }
    /// The complete `bus_reactive_injection` column, in `bus_order`.
    #[must_use]
    pub fn bus_reactive_injections(&self) -> &[f64] {
        &self.bus_reactive_injection
    }
    /// The complete `branch_from_active_flow` column, in `branch_order`.
    #[must_use]
    pub fn branch_from_active_flows(&self) -> &[f64] {
        &self.branch_from_active_flow
    }
    /// The complete `branch_from_reactive_flow` column, in `branch_order`.
    #[must_use]
    pub fn branch_from_reactive_flows(&self) -> &[f64] {
        &self.branch_from_reactive_flow
    }
    /// The complete `branch_to_active_flow` column, in `branch_order`.
    #[must_use]
    pub fn branch_to_active_flows(&self) -> &[f64] {
        &self.branch_to_active_flow
    }
    /// The complete `branch_to_reactive_flow` column, in `branch_order`.
    #[must_use]
    pub fn branch_to_reactive_flows(&self) -> &[f64] {
        &self.branch_to_reactive_flow
    }
    /// The complete `generator_active_power` column, in `generator_order`.
    #[must_use]
    pub fn generator_active_powers(&self) -> &[f64] {
        &self.generator_active_power
    }
    /// The complete `generator_reactive_power` column, in `generator_order`.
    #[must_use]
    pub fn generator_reactive_powers(&self) -> &[f64] {
        &self.generator_reactive_power
    }
}