powerio-prob 0.11.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
//! The balanced calculation instances: `DcPfInstance`, `AcPfInstance`,
//! `DcOpfInstance`, and `AcOpfInstance`.
//!
//! Every instance shares its reusable electrical network as a cheap owning
//! handle rather than duplicating it into solver preparation arrays: cloning
//! an instance clones no network table. Fields are private; each instance
//! exposes a borrowed `network()` accessor and typed calculation data.
//! Physical limit values stay on the network; an OPF instance selects active
//! constraints by stable element identity and states its objective as typed
//! terms.
//!
//! A power flow instance contains partial boundary specifications, never a
//! required complete operating point: the unknown voltages, injections, and
//! flows are what the calculation solves. A complete
//! [`OperatingPoint`] can be supplied as an optional solver initial point.
//! Zero impedance branches are preserved; a projection that cannot represent
//! them refuses at its own boundary and
//! [`merge_zero_impedance_buses`](super::merge_zero_impedance_buses) is the
//! explicit, checked resolution.

use std::collections::{BTreeMap, BTreeSet};

use powerio_core::Error;
use powerio_tx::{BalancedNetwork, BranchSusceptanceFormula, BusId, BusType};
use serde::{Deserialize, Serialize};

use crate::OperatingPoint;
use crate::diagnostics::codes;
use crate::instance::constraints::ActiveConstraints;
use crate::instance::objective::{Objective, ObjectiveTerm};

/// One bus of a DC power flow problem: what the calculation is told, never
/// what it solves.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
#[non_exhaustive]
pub enum DcBusSpecification {
    /// The net active power injection the bus states, MW (generation minus
    /// demand over in service elements).
    NetActivePower { p_mw: f64 },
    /// A reference bus with its stated voltage angle, degrees.
    Reference { va_degrees: f64 },
    /// An isolated bus: no equation.
    Isolated,
}

/// One bus of an AC power flow problem, the standard partial specification.
/// Powers are MW and MVAr, voltage magnitudes per unit, angles degrees, as
/// the network states them.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case", tag = "kind")]
#[non_exhaustive]
pub enum AcBusSpecification {
    /// Prescribed net active and reactive injection.
    Pq { p: f64, q: f64 },
    /// Prescribed net active injection and voltage magnitude.
    Pv { p: f64, vm: f64 },
    /// Prescribed voltage magnitude and angle.
    Reference { vm: f64, va: f64 },
    /// No equation.
    Isolated,
}

/// The DC power flow instance: the shared network plus per bus boundary
/// specifications and the selected branch susceptance formula.
#[derive(Clone, Debug)]
pub struct DcPfInstance {
    network: BalancedNetwork,
    specifications: Vec<DcBusSpecification>,
    branch_susceptance_formula: BranchSusceptanceFormula,
    initial_point: Option<OperatingPoint<BalancedNetwork>>,
}

impl DcPfInstance {
    /// Build the instance from the network's stated data: reference buses
    /// contribute their stated angle, isolated buses no equation, and every
    /// other bus its net active injection over in service generators and
    /// loads.
    ///
    /// # Errors
    /// A network with no reference bus.
    pub fn from_network(mut network: BalancedNetwork) -> Result<Self, Error> {
        network.assign_missing_component_ids();
        require_reference(&network)?;
        let totals = aggregate_bus_elements(&network);
        let specifications = network
            .buses()
            .iter()
            .map(|bus| match bus.kind {
                BusType::Ref => DcBusSpecification::Reference { va_degrees: bus.va },
                BusType::Isolated => DcBusSpecification::Isolated,
                // Every other declared kind states a net injection.
                _ => DcBusSpecification::NetActivePower {
                    p_mw: net_active_power(&totals, bus.id),
                },
            })
            .collect();
        Ok(Self {
            network,
            specifications,
            branch_susceptance_formula: BranchSusceptanceFormula::default(),
            initial_point: None,
        })
    }

    /// Select the branch susceptance formula, consuming the instance. The
    /// network handle moves; no table is copied.
    #[must_use]
    pub fn with_branch_susceptance_formula(mut self, formula: BranchSusceptanceFormula) -> Self {
        self.branch_susceptance_formula = formula;
        self
    }

    /// Supply an optional solver initial point.
    #[must_use]
    pub fn with_initial_point(mut self, point: OperatingPoint<BalancedNetwork>) -> Self {
        self.initial_point = Some(point);
        self
    }

    /// Replace the network and recalculate the fixed bus specifications while
    /// preserving the branch susceptance formula and a compatible initial
    /// point.
    ///
    /// # Errors
    /// The replacement has no reference bus or changes an identity layout used
    /// by the initial point.
    pub fn with_network(mut self, mut network: BalancedNetwork) -> Result<Self, Error> {
        network.assign_missing_component_ids();
        let mut replacement = Self::from_network(network.clone())?
            .with_branch_susceptance_formula(self.branch_susceptance_formula);
        if let Some(initial) = self.initial_point.take() {
            replacement.initial_point = Some(initial.rebind_network(network)?);
        }
        Ok(replacement)
    }

    /// The network this instance calculates on. Borrowed; never a copy.
    #[must_use]
    pub fn network(&self) -> &BalancedNetwork {
        &self.network
    }

    /// The per bus boundary specifications, in bus table order.
    #[must_use]
    pub fn specifications(&self) -> &[DcBusSpecification] {
        &self.specifications
    }

    /// The selected branch susceptance formula.
    #[must_use]
    pub const fn branch_susceptance_formula(&self) -> BranchSusceptanceFormula {
        self.branch_susceptance_formula
    }

    /// The optional solver initial point.
    #[must_use]
    pub const fn initial_point(&self) -> Option<&OperatingPoint<BalancedNetwork>> {
        self.initial_point.as_ref()
    }
}

/// The AC power flow instance: the shared network plus one
/// [`AcBusSpecification`] per bus.
#[derive(Clone, Debug)]
pub struct AcPfInstance {
    network: BalancedNetwork,
    specifications: Vec<AcBusSpecification>,
    initial_point: Option<OperatingPoint<BalancedNetwork>>,
}

impl AcPfInstance {
    /// Build an AC power flow instance from explicit bus specifications.
    /// The specification vector follows bus table order and is retained
    /// exactly; it is not inferred again from bus types, loads, or generator
    /// schedules.
    ///
    /// # Errors
    /// The specification count differs from the bus count, or no
    /// specification declares a reference bus.
    pub fn new(
        mut network: BalancedNetwork,
        specifications: Vec<AcBusSpecification>,
    ) -> Result<Self, Error> {
        network.assign_missing_component_ids();
        if specifications.len() != network.buses().len() {
            return Err(Error::new(
                &codes::BUILD_INSTANCE_SHAPE_MISMATCH,
                format!(
                    "AC power flow specifications carry {} rows; the network has {} buses",
                    specifications.len(),
                    network.buses().len()
                ),
            ));
        }
        if !specifications
            .iter()
            .any(|specification| matches!(specification, AcBusSpecification::Reference { .. }))
        {
            return Err(Error::new(
                &codes::BUILD_INSTANCE_NO_REFERENCE_BUS,
                "the AC power flow specifications state no reference (slack) bus",
            ));
        }
        Ok(Self {
            network,
            specifications,
            initial_point: None,
        })
    }

    /// Build the instance from the network's stated data. A PQ bus states
    /// its net injections; a PV bus its net active injection and the
    /// regulating generator's voltage setpoint; a reference bus its setpoint
    /// magnitude and stated angle.
    ///
    /// # Errors
    /// A network with no reference bus, or conflicting active voltage
    /// controllers: two in service generators at one bus stating different
    /// voltage setpoints are refused until an explicit edit resolves them.
    pub fn from_network(mut network: BalancedNetwork) -> Result<Self, Error> {
        network.assign_missing_component_ids();
        require_reference(&network)?;
        let totals = aggregate_bus_elements(&network);
        let specifications = network
            .buses()
            .iter()
            .map(|bus| {
                let spec = match bus.kind {
                    BusType::Isolated => AcBusSpecification::Isolated,
                    BusType::Pv => AcBusSpecification::Pv {
                        p: net_active_power(&totals, bus.id),
                        vm: controlled_magnitude(&totals, bus.id, bus.vm)?,
                    },
                    BusType::Ref => AcBusSpecification::Reference {
                        vm: controlled_magnitude(&totals, bus.id, bus.vm)?,
                        va: bus.va,
                    },
                    // Every other declared kind is the PQ specification.
                    _ => AcBusSpecification::Pq {
                        p: net_active_power(&totals, bus.id),
                        q: net_reactive_power(&totals, bus.id),
                    },
                };
                Ok(spec)
            })
            .collect::<Result<Vec<_>, Error>>()?;
        Self::new(network, specifications)
    }

    /// Supply an optional solver initial point.
    #[must_use]
    pub fn with_initial_point(mut self, point: OperatingPoint<BalancedNetwork>) -> Self {
        self.initial_point = Some(point);
        self
    }

    /// Replace the network and recalculate the fixed bus specifications while
    /// preserving a compatible initial point.
    ///
    /// # Errors
    /// The replacement has no reference bus, has conflicting voltage
    /// controllers, or changes an identity layout used by the initial point.
    pub fn with_network(mut self, mut network: BalancedNetwork) -> Result<Self, Error> {
        network.assign_missing_component_ids();
        let mut replacement = Self::from_network(network.clone())?;
        if let Some(initial) = self.initial_point.take() {
            replacement.initial_point = Some(initial.rebind_network(network)?);
        }
        Ok(replacement)
    }

    /// The network this instance calculates on. Borrowed; never a copy.
    #[must_use]
    pub fn network(&self) -> &BalancedNetwork {
        &self.network
    }

    /// The per bus specifications, in bus table order.
    #[must_use]
    pub fn specifications(&self) -> &[AcBusSpecification] {
        &self.specifications
    }

    /// The optional solver initial point.
    #[must_use]
    pub const fn initial_point(&self) -> Option<&OperatingPoint<BalancedNetwork>> {
        self.initial_point.as_ref()
    }

    /// The DC power flow instance this AC problem implies: reactive data and
    /// voltage magnitudes are discarded, and the DC model's flat voltage
    /// assumption is recorded as a diagnostic.
    #[must_use]
    pub fn to_dc_pf(&self) -> (DcPfInstance, Vec<powerio_core::Diagnostic>) {
        let instance = DcPfInstance {
            network: self.network.clone(),
            specifications: self
                .specifications
                .iter()
                .map(|specification| match *specification {
                    AcBusSpecification::Pq { p, .. } | AcBusSpecification::Pv { p, .. } => {
                        DcBusSpecification::NetActivePower { p_mw: p }
                    }
                    AcBusSpecification::Reference { va, .. } => {
                        DcBusSpecification::Reference { va_degrees: va }
                    }
                    AcBusSpecification::Isolated => DcBusSpecification::Isolated,
                })
                .collect(),
            branch_susceptance_formula: BranchSusceptanceFormula::default(),
            initial_point: self.initial_point.clone(),
        };
        let diagnostics = vec![
            transform_discarded("reactive power and voltage magnitude specifications"),
            transform_assumption(
                "the DC power flow model holds every voltage magnitude at one per unit",
            ),
        ];
        (instance, diagnostics)
    }
}

/// The DC optimal power flow instance: the shared network, the typed
/// objective, the active constraint selections, the selected DC branch
/// susceptance formula, and the reference conditions the network states.
#[derive(Clone, Debug)]
pub struct DcOpfInstance {
    network: BalancedNetwork,
    objective: Objective,
    constraints: ActiveConstraints,
    branch_susceptance_formula: BranchSusceptanceFormula,
    initial_point: Option<OperatingPoint<BalancedNetwork>>,
}

impl DcOpfInstance {
    /// Build the instance with every stated limit active. The default
    /// objective is the network's generator cost curves when at least one
    /// dispatchable generator carries cost data. A network with no applicable
    /// cost rows becomes an explicit feasibility problem instead of inventing
    /// zero cost curves. Partially populated costs still select the network
    /// objective so preparation reports the missing row.
    ///
    /// # Errors
    /// A network with no reference bus or no in service generator attached to
    /// a non-isolated bus.
    pub fn from_network(mut network: BalancedNetwork) -> Result<Self, Error> {
        network.assign_missing_component_ids();
        require_reference(&network)?;
        require_dispatchable(&network)?;
        let objective = default_opf_objective(&network);
        Ok(Self {
            network,
            objective,
            constraints: ActiveConstraints::default(),
            branch_susceptance_formula: BranchSusceptanceFormula::default(),
            initial_point: None,
        })
    }

    /// Replace the objective, consuming the instance. The shared network
    /// moves; no table is copied.
    #[must_use]
    pub fn with_objective(mut self, objective: Objective) -> Self {
        self.objective = objective;
        self
    }

    /// Append one objective term, consuming the instance.
    #[must_use]
    pub fn with_objective_term(mut self, term: ObjectiveTerm) -> Self {
        self.objective = std::mem::take(&mut self.objective).with_term(term);
        self
    }

    /// Replace the active constraint selections, consuming the instance.
    #[must_use]
    pub fn with_constraints(mut self, constraints: ActiveConstraints) -> Self {
        self.constraints = constraints;
        self
    }

    /// Select the branch susceptance formula, consuming the instance.
    #[must_use]
    pub fn with_branch_susceptance_formula(mut self, formula: BranchSusceptanceFormula) -> Self {
        self.branch_susceptance_formula = formula;
        self
    }

    /// Supply an optional solver initial point.
    #[must_use]
    pub fn with_initial_point(mut self, point: OperatingPoint<BalancedNetwork>) -> Self {
        self.initial_point = Some(point);
        self
    }

    /// Replace the network while preserving this instance's objective,
    /// constraint selections, branch susceptance formula, and compatible initial point.
    /// This is the checked path for a parameter edit such as a branch rating
    /// change; callers do not have to reconstruct the problem and risk
    /// dropping its semantics.
    ///
    /// # Errors
    /// The replacement has no reference bus or dispatchable generator, or it
    /// changes an identity layout used by the initial point.
    pub fn with_network(mut self, mut network: BalancedNetwork) -> Result<Self, Error> {
        network.assign_missing_component_ids();
        require_reference(&network)?;
        require_dispatchable(&network)?;
        if let Some(initial) = self.initial_point.take() {
            self.initial_point = Some(initial.rebind_network(network.clone())?);
        }
        self.network = network;
        Ok(self)
    }

    /// The network this instance calculates on. Borrowed; never a copy.
    #[must_use]
    pub fn network(&self) -> &BalancedNetwork {
        &self.network
    }

    /// The typed objective.
    #[must_use]
    pub const fn objective(&self) -> &Objective {
        &self.objective
    }

    /// The active constraint selections.
    #[must_use]
    pub const fn constraints(&self) -> &ActiveConstraints {
        &self.constraints
    }

    /// The selected branch susceptance formula.
    #[must_use]
    pub const fn branch_susceptance_formula(&self) -> BranchSusceptanceFormula {
        self.branch_susceptance_formula
    }

    /// The optional solver initial point.
    #[must_use]
    pub const fn initial_point(&self) -> Option<&OperatingPoint<BalancedNetwork>> {
        self.initial_point.as_ref()
    }

    /// The DC power flow instance for this problem's network at its stated
    /// injections: the objective and the constraint selections are
    /// discarded, and the discard is recorded.
    ///
    /// # Errors
    /// As [`DcPfInstance::from_network`].
    pub fn to_dc_pf(&self) -> Result<(DcPfInstance, Vec<powerio_core::Diagnostic>), Error> {
        let instance = DcPfInstance::from_network(self.network.clone())?
            .with_branch_susceptance_formula(self.branch_susceptance_formula);
        Ok((
            instance,
            vec![transform_discarded(
                "the objective and the active constraint selections",
            )],
        ))
    }
}

/// The AC optimal power flow instance: the shared network, the typed
/// objective, and the active generator capability, voltage, thermal, and
/// angle constraint selections.
#[derive(Clone, Debug)]
pub struct AcOpfInstance {
    network: BalancedNetwork,
    objective: Objective,
    constraints: ActiveConstraints,
    initial_point: Option<OperatingPoint<BalancedNetwork>>,
}

impl AcOpfInstance {
    /// Build the instance with every stated limit active. The default
    /// objective is the network's generator cost curves when at least one
    /// dispatchable generator carries cost data. A network with no applicable
    /// cost rows becomes an explicit feasibility problem instead of inventing
    /// zero cost curves. Partially populated costs still select the network
    /// objective so preparation reports the missing row.
    ///
    /// # Errors
    /// A network with no reference bus or no in service generator attached to
    /// a non-isolated bus.
    pub fn from_network(mut network: BalancedNetwork) -> Result<Self, Error> {
        network.assign_missing_component_ids();
        require_reference(&network)?;
        require_dispatchable(&network)?;
        let objective = default_opf_objective(&network);
        Ok(Self {
            network,
            objective,
            constraints: ActiveConstraints::default(),
            initial_point: None,
        })
    }

    /// Replace the objective, consuming the instance. The shared network
    /// moves; no table is copied.
    #[must_use]
    pub fn with_objective(mut self, objective: Objective) -> Self {
        self.objective = objective;
        self
    }

    /// Append one objective term, consuming the instance.
    #[must_use]
    pub fn with_objective_term(mut self, term: ObjectiveTerm) -> Self {
        self.objective = std::mem::take(&mut self.objective).with_term(term);
        self
    }

    /// Replace the active constraint selections, consuming the instance.
    #[must_use]
    pub fn with_constraints(mut self, constraints: ActiveConstraints) -> Self {
        self.constraints = constraints;
        self
    }

    /// Supply an optional solver initial point.
    #[must_use]
    pub fn with_initial_point(mut self, point: OperatingPoint<BalancedNetwork>) -> Self {
        self.initial_point = Some(point);
        self
    }

    /// Replace the network while preserving this instance's objective,
    /// constraint selections, and compatible initial point.
    ///
    /// # Errors
    /// The replacement has no reference bus or dispatchable generator, or it
    /// changes an identity layout used by the initial point.
    pub fn with_network(mut self, mut network: BalancedNetwork) -> Result<Self, Error> {
        network.assign_missing_component_ids();
        require_reference(&network)?;
        require_dispatchable(&network)?;
        if let Some(initial) = self.initial_point.take() {
            self.initial_point = Some(initial.rebind_network(network.clone())?);
        }
        self.network = network;
        Ok(self)
    }

    /// The network this instance calculates on. Borrowed; never a copy.
    #[must_use]
    pub fn network(&self) -> &BalancedNetwork {
        &self.network
    }

    /// The typed objective.
    #[must_use]
    pub const fn objective(&self) -> &Objective {
        &self.objective
    }

    /// The active constraint selections.
    #[must_use]
    pub const fn constraints(&self) -> &ActiveConstraints {
        &self.constraints
    }

    /// The optional solver initial point.
    #[must_use]
    pub const fn initial_point(&self) -> Option<&OperatingPoint<BalancedNetwork>> {
        self.initial_point.as_ref()
    }

    /// The AC power flow instance for this problem's network at its stated
    /// injections and setpoints: the objective and the constraint selections
    /// are discarded, and the discard is recorded.
    ///
    /// # Errors
    /// As [`AcPfInstance::from_network`].
    pub fn to_ac_pf(&self) -> Result<(AcPfInstance, Vec<powerio_core::Diagnostic>), Error> {
        let instance = AcPfInstance::from_network(self.network.clone())?;
        Ok((
            instance,
            vec![transform_discarded(
                "the objective and the active constraint selections",
            )],
        ))
    }

    /// The DC optimal power flow instance this AC problem implies: the
    /// objective and the generator capability, thermal, and angle selections
    /// carry over; the voltage bound selection has no DC variable and is
    /// discarded, and the flat voltage assumption is recorded.
    #[must_use]
    pub fn to_dc_opf(&self) -> (DcOpfInstance, Vec<powerio_core::Diagnostic>) {
        let constraints = ActiveConstraints {
            generator_capability: self.constraints.generator_capability.clone(),
            voltage_bounds: crate::instance::ConstraintSelection::None,
            thermal_limits: self.constraints.thermal_limits.clone(),
            angle_bounds: self.constraints.angle_bounds.clone(),
        };
        let instance = DcOpfInstance {
            network: self.network.clone(),
            objective: self.objective.clone(),
            constraints,
            branch_susceptance_formula: BranchSusceptanceFormula::default(),
            initial_point: self.initial_point.clone(),
        };
        let diagnostics = vec![
            transform_discarded("the voltage bound constraint selection"),
            transform_assumption(
                "the DC power flow model holds every voltage magnitude at one per unit",
            ),
        ];
        (instance, diagnostics)
    }
}

/// Net stated active injection at one bus, MW, over in service elements.
/// Per bus totals of the in service generators and loads, plus the voltage
/// setpoint agreement, gathered in one pass so instance construction stays
/// linear in bus plus generator plus load count.
#[derive(Default)]
struct BusAggregate {
    p_gen: f64,
    q_gen: f64,
    p_load: f64,
    q_load: f64,
    setpoint: Option<f64>,
    conflicting: Option<f64>,
}

fn aggregate_bus_elements(network: &BalancedNetwork) -> BTreeMap<BusId, BusAggregate> {
    let mut totals: BTreeMap<BusId, BusAggregate> = BTreeMap::new();
    for generator in network
        .generators()
        .iter()
        .filter(|generator| generator.in_service)
    {
        let entry = totals.entry(generator.bus).or_default();
        entry.p_gen += generator.pg;
        entry.q_gen += generator.qg;
        match entry.setpoint {
            None => entry.setpoint = Some(generator.vg),
            Some(existing) if existing.to_bits() == generator.vg.to_bits() => {}
            Some(_) => {
                if entry.conflicting.is_none() {
                    entry.conflicting = Some(generator.vg);
                }
            }
        }
    }
    for load in network.loads().iter().filter(|load| load.in_service) {
        let entry = totals.entry(load.bus).or_default();
        entry.p_load += load.p;
        entry.q_load += load.q;
    }
    totals
}

fn net_active_power(totals: &BTreeMap<BusId, BusAggregate>, bus: BusId) -> f64 {
    totals
        .get(&bus)
        .map_or(0.0, |entry| entry.p_gen - entry.p_load)
}

/// Net stated reactive injection at one bus, MVAr, over in service elements.
fn net_reactive_power(totals: &BTreeMap<BusId, BusAggregate>, bus: BusId) -> f64 {
    totals
        .get(&bus)
        .map_or(0.0, |entry| entry.q_gen - entry.q_load)
}

/// The controlled voltage magnitude at one bus: the in service generators'
/// shared setpoint, else the bus's stated magnitude. Two in service
/// generators stating different setpoints at one bus are conflicting active
/// voltage controllers and are refused.
fn controlled_magnitude(
    totals: &BTreeMap<BusId, BusAggregate>,
    bus: BusId,
    stated: f64,
) -> Result<f64, Error> {
    let Some(entry) = totals.get(&bus) else {
        return Ok(stated);
    };
    if let (Some(existing), Some(other)) = (entry.setpoint, entry.conflicting) {
        return Err(Error::new(
            &codes::BUILD_INSTANCE_VOLTAGE_CONTROL_CONFLICT,
            format!(
                "bus {bus} has in service generators stating voltage setpoints {existing} and {other}; resolve the conflict explicitly before constructing the power flow instance"
            ),
        ));
    }
    Ok(entry.setpoint.unwrap_or(stated))
}

fn require_reference(network: &BalancedNetwork) -> Result<(), Error> {
    if network.buses().iter().any(|bus| bus.kind == BusType::Ref) {
        Ok(())
    } else {
        Err(Error::new(
            &codes::BUILD_INSTANCE_NO_REFERENCE_BUS,
            "the network states no reference (slack) bus",
        ))
    }
}

fn require_dispatchable(network: &BalancedNetwork) -> Result<(), Error> {
    let active_buses = active_bus_ids(network);
    if network
        .generators()
        .iter()
        .any(|generator| generator.in_service && active_buses.contains(&generator.bus))
    {
        Ok(())
    } else {
        Err(Error::new(
            &codes::BUILD_INSTANCE_NO_GENERATORS,
            "the network has no in service generator for the problem to dispatch",
        ))
    }
}

fn default_opf_objective(network: &BalancedNetwork) -> Objective {
    let active_buses = active_bus_ids(network);
    if network.generators().iter().any(|generator| {
        generator.in_service && active_buses.contains(&generator.bus) && generator.cost.is_some()
    }) {
        Objective::network_generator_cost()
    } else {
        Objective::none()
    }
}

fn active_bus_ids(network: &BalancedNetwork) -> BTreeSet<BusId> {
    network
        .buses()
        .iter()
        .filter(|bus| bus.kind != BusType::Isolated)
        .map(|bus| bus.id)
        .collect()
}

pub(crate) fn transform_discarded(what: &str) -> powerio_core::Diagnostic {
    powerio_core::Diagnostic::of(
        &codes::TRANSFORM_INSTANCE_DATA_DISCARDED,
        format!("{what} of the source instance are not part of the derived calculation"),
    )
}

pub(crate) fn transform_assumption(what: &str) -> powerio_core::Diagnostic {
    powerio_core::Diagnostic::of(&codes::TRANSFORM_INSTANCE_ASSUMPTION, what)
}