Skip to main content

powerio_matrix/
lindist3flow_devices.rs

1//! Device, objective, and nodal-balance preparation for LinDist3Flow.
2
3use num_complex::Complex64;
4use powerio_dist::{Configuration, DistLoad, DistLoadVoltageModel};
5use powerio_prob::{LinDist3FlowOpfInstance, ObjectiveTerm};
6
7use crate::{
8    ConnectionPowerMap, Error, LinDist3FlowNetworkData, Result, build_lindist3flow_network_data,
9    connection_power_map, cross_voltage_coefficients, winding_voltage_coefficients,
10};
11
12/// One coefficient on a squared-voltage variable.
13#[derive(Clone, Copy, Debug, PartialEq)]
14#[non_exhaustive]
15pub struct LinDist3FlowVoltageTerm {
16    pub node: usize,
17    pub coefficient: f64,
18}
19
20/// An affine scalar over the prepared squared-voltage variables.
21#[derive(Clone, Debug, Default, PartialEq)]
22#[non_exhaustive]
23pub struct LinDist3FlowAffineExpression {
24    pub constant: f64,
25    pub voltage_terms: Vec<LinDist3FlowVoltageTerm>,
26}
27
28/// Active and reactive affine power expressions.
29#[derive(Clone, Debug, Default, PartialEq)]
30#[non_exhaustive]
31pub struct LinDist3FlowComplexAffinePower {
32    pub active: LinDist3FlowAffineExpression,
33    pub reactive: LinDist3FlowAffineExpression,
34}
35
36/// One physical load and its reference-frozen terminal allocation.
37#[derive(Clone, Debug, PartialEq)]
38#[non_exhaustive]
39pub struct LinDist3FlowLoadData {
40    pub load: String,
41    pub source_load_row: usize,
42    pub terminal_nodes: Vec<usize>,
43    pub incidence: Vec<Vec<f64>>,
44    pub terminal_power_map: ConnectionPowerMap,
45    pub channel_power: Vec<LinDist3FlowComplexAffinePower>,
46}
47
48/// One affine terminal shunt-power row.
49#[derive(Clone, Debug, PartialEq)]
50#[non_exhaustive]
51pub struct LinDist3FlowShuntData {
52    pub shunt: String,
53    pub source_shunt_row: usize,
54    pub terminal_nodes: Vec<usize>,
55    pub terminal_power: Vec<LinDist3FlowComplexAffinePower>,
56}
57
58/// Bounds, objective coefficient, and SOC data for one dispatch channel.
59#[derive(Clone, Debug, PartialEq)]
60#[non_exhaustive]
61pub struct LinDist3FlowDispatchChannel {
62    pub active_min: Option<f64>,
63    pub active_max: Option<f64>,
64    pub reactive_min: Option<f64>,
65    pub reactive_max: Option<f64>,
66    pub apparent_power_limit: Option<f64>,
67    pub current_limit: Option<f64>,
68    /// Affine live `|D v|²` used by the rotated current cone.
69    pub squared_winding_voltage: LinDist3FlowAffineExpression,
70    pub reference_winding_voltage: f64,
71    /// Linear objective coefficient on active watts.
72    pub active_objective_coefficient: f64,
73}
74
75/// One dispatchable generator and its terminal allocation.
76#[derive(Clone, Debug, PartialEq)]
77#[non_exhaustive]
78pub struct LinDist3FlowGeneratorData {
79    pub generator: String,
80    pub source_generator_row: usize,
81    pub terminal_nodes: Vec<usize>,
82    pub incidence: Vec<Vec<f64>>,
83    pub terminal_power_map: ConnectionPowerMap,
84    pub channels: Vec<LinDist3FlowDispatchChannel>,
85}
86
87/// One voltage source. Its channel powers inject directly at corresponding
88/// terminals; the squared voltages are fixed in [`LinDist3FlowNetworkData`].
89#[derive(Clone, Debug, PartialEq)]
90#[non_exhaustive]
91pub struct LinDist3FlowSourceData {
92    pub source: String,
93    pub source_source_row: usize,
94    pub terminal_nodes: Vec<usize>,
95    pub active_objective_coefficient: Vec<f64>,
96}
97
98/// Semantic scalar variables used by nodal-balance rows.
99#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
100#[non_exhaustive]
101pub enum LinDist3FlowVariable {
102    LineActive { line: usize, conductor: usize },
103    LineReactive { line: usize, conductor: usize },
104    GeneratorActive { generator: usize, channel: usize },
105    GeneratorReactive { generator: usize, channel: usize },
106    SourceActive { source: usize, channel: usize },
107    SourceReactive { source: usize, channel: usize },
108}
109
110/// One coefficient on a semantic decision variable.
111#[derive(Clone, Debug, PartialEq)]
112#[non_exhaustive]
113pub struct LinDist3FlowBalanceTerm {
114    pub variable: LinDist3FlowVariable,
115    pub coefficient: f64,
116}
117
118/// One equality expression constrained to zero.
119#[derive(Clone, Debug, Default, PartialEq)]
120#[non_exhaustive]
121pub struct LinDist3FlowBalanceEquation {
122    pub affine: LinDist3FlowAffineExpression,
123    pub variable_terms: Vec<LinDist3FlowBalanceTerm>,
124}
125
126/// Active and reactive KCL at one retained bus terminal.
127#[derive(Clone, Debug, PartialEq)]
128#[non_exhaustive]
129pub struct LinDist3FlowBalanceRow {
130    pub node: usize,
131    pub active: LinDist3FlowBalanceEquation,
132    pub reactive: LinDist3FlowBalanceEquation,
133}
134
135/// All device rows and the fully expanded nodal balances.
136#[derive(Clone, Debug, PartialEq)]
137#[non_exhaustive]
138pub struct LinDist3FlowDeviceData {
139    pub loads: Vec<LinDist3FlowLoadData>,
140    pub shunts: Vec<LinDist3FlowShuntData>,
141    pub generators: Vec<LinDist3FlowGeneratorData>,
142    pub sources: Vec<LinDist3FlowSourceData>,
143    pub balances: Vec<LinDist3FlowBalanceRow>,
144}
145
146/// Complete solver-neutral preparation for the currently supported L3F slice.
147#[derive(Clone, Debug, PartialEq)]
148#[non_exhaustive]
149pub struct LinDist3FlowPreparation {
150    pub network: LinDist3FlowNetworkData,
151    pub devices: LinDist3FlowDeviceData,
152}
153
154fn invalid(reason: impl Into<String>) -> Error {
155    Error::InvalidLinDist3FlowCoefficients {
156        reason: reason.into(),
157    }
158}
159
160/// Build the physical-channel incidence matrix for a typed connection.
161///
162/// # Errors
163/// The terminal and channel arities do not describe a supported grounded-wye,
164/// single-phase, or delta connection.
165pub fn lindist3flow_connection_incidence(
166    configuration: Configuration,
167    terminal_count: usize,
168    channel_count: usize,
169) -> Result<Vec<Vec<f64>>> {
170    let carried =
171        powerio_dist::lindist3flow_carries_connection(configuration, terminal_count, channel_count);
172    let unsupported = || {
173        invalid(format!(
174            "{configuration:?} connection with {terminal_count} terminals and {channel_count} channels is unsupported"
175        ))
176    };
177    if !carried {
178        return Err(unsupported());
179    }
180    let channels =
181        powerio_dist::calc_connection_channels(configuration, terminal_count, channel_count, None)
182            .map_err(|_| unsupported())?;
183    Ok(channels
184        .iter()
185        .map(|channel| {
186            let mut row = vec![0.0; terminal_count];
187            row[channel.from] = 1.0;
188            if let Some(to) = channel.to {
189                row[to] = -1.0;
190            }
191            row
192        })
193        .collect())
194}
195
196fn resolve_nodes(
197    positions: &powerio_dist::MulticonductorTerminalIndex,
198    bus: &str,
199    terminals: &[String],
200    family: &str,
201    name: &str,
202) -> Result<Vec<usize>> {
203    terminals
204        .iter()
205        .map(|terminal| {
206            positions.resolve(bus, terminal).ok_or_else(|| {
207                invalid(format!(
208                    "{family} `{name}` names unknown terminal `{bus}/{terminal}`"
209                ))
210            })
211        })
212        .collect()
213}
214
215fn references(instance: &LinDist3FlowOpfInstance, nodes: &[usize]) -> Vec<Complex64> {
216    nodes
217        .iter()
218        .map(|&node| {
219            let reference = &instance.reference().voltages[node];
220            Complex64::from_polar(reference.magnitude, reference.angle)
221        })
222        .collect()
223}
224
225fn global_affine(
226    constant: f64,
227    scale: f64,
228    local: &crate::AffineScalarCoefficients,
229    nodes: &[usize],
230) -> LinDist3FlowAffineExpression {
231    LinDist3FlowAffineExpression {
232        constant: constant + scale * local.constant,
233        voltage_terms: local
234            .coefficients
235            .iter()
236            .zip(nodes)
237            .filter_map(|(coefficient, node)| {
238                let coefficient = scale * coefficient;
239                (coefficient.abs() > f64::EPSILON).then_some(LinDist3FlowVoltageTerm {
240                    node: *node,
241                    coefficient,
242                })
243            })
244            .collect(),
245    }
246}
247
248fn channel_value(values: &[f64], channel: usize, channels: usize, label: &str) -> Result<f64> {
249    let value = match values.len() {
250        1 => values[0],
251        length if length == channels => values[channel],
252        length => {
253            return Err(invalid(format!(
254                "{label} has length {length}, expected 1 or {channels}"
255            )));
256        }
257    };
258    if !value.is_finite() {
259        return Err(invalid(format!("{label} entry {channel} is non-finite")));
260    }
261    Ok(value)
262}
263
264fn load_channel_power(
265    load: &DistLoad,
266    incidence: &[Vec<f64>],
267    reference: &[Complex64],
268    terminal_nodes: &[usize],
269    channel: usize,
270) -> Result<LinDist3FlowComplexAffinePower> {
271    let channels = load.p_nom.len();
272    let p_nom = load.p_nom[channel];
273    let q_nom = load.q_nom[channel];
274    if !p_nom.is_finite() || !q_nom.is_finite() {
275        return Err(invalid(format!(
276            "load `{}` channel {channel} nominal power is non-finite",
277            load.name
278        )));
279    }
280    if matches!(
281        load.voltage_model,
282        DistLoadVoltageModel::ConstantPower { .. }
283    ) {
284        return Ok(LinDist3FlowComplexAffinePower {
285            active: LinDist3FlowAffineExpression {
286                constant: p_nom,
287                voltage_terms: Vec::new(),
288            },
289            reactive: LinDist3FlowAffineExpression {
290                constant: q_nom,
291                voltage_terms: Vec::new(),
292            },
293        });
294    }
295    let winding = winding_voltage_coefficients(&incidence[channel], reference)?;
296    let (v_nom, alpha_z, alpha_p, beta_z, beta_p) = match &load.voltage_model {
297        DistLoadVoltageModel::ConstantImpedance { v_nom } => (
298            channel_value(v_nom, channel, channels, "load v_nom")?,
299            1.0,
300            0.0,
301            1.0,
302            0.0,
303        ),
304        DistLoadVoltageModel::Zip {
305            v_nom,
306            alpha_z,
307            alpha_i,
308            alpha_p,
309            beta_z,
310            beta_i,
311            beta_p,
312        } => {
313            let alpha_i = channel_value(alpha_i, channel, channels, "load alpha_i")?;
314            let beta_i = channel_value(beta_i, channel, channels, "load beta_i")?;
315            if alpha_i.abs() > f64::EPSILON || beta_i.abs() > f64::EPSILON {
316                return Err(invalid(format!(
317                    "load `{}` channel {channel} has a nonzero current fraction",
318                    load.name
319                )));
320            }
321            (
322                channel_value(v_nom, channel, channels, "load v_nom")?,
323                channel_value(alpha_z, channel, channels, "load alpha_z")?,
324                channel_value(alpha_p, channel, channels, "load alpha_p")?,
325                channel_value(beta_z, channel, channels, "load beta_z")?,
326                channel_value(beta_p, channel, channels, "load beta_p")?,
327            )
328        }
329        _ => {
330            return Err(invalid(format!(
331                "load `{}` voltage model is outside the supported ZP slice",
332                load.name
333            )));
334        }
335    };
336    if !v_nom.is_finite() || v_nom <= 0.0 {
337        return Err(invalid(format!(
338            "load `{}` channel {channel} v_nom must be finite and positive",
339            load.name
340        )));
341    }
342    Ok(LinDist3FlowComplexAffinePower {
343        active: global_affine(
344            p_nom * alpha_p,
345            powerio_core::electrical::calc_rated_admittance(p_nom * alpha_z, v_nom),
346            &winding,
347            terminal_nodes,
348        ),
349        reactive: global_affine(
350            q_nom * beta_p,
351            powerio_core::electrical::calc_rated_admittance(q_nom * beta_z, v_nom),
352            &winding,
353            terminal_nodes,
354        ),
355    })
356}
357
358fn shunt_terminal_power(
359    name: &str,
360    g: &[Vec<f64>],
361    b: &[Vec<f64>],
362    reference: &[Complex64],
363    terminal_nodes: &[usize],
364    terminal: usize,
365) -> Result<LinDist3FlowComplexAffinePower> {
366    let n = terminal_nodes.len();
367    if g.len() != n || b.len() != n {
368        return Err(invalid(format!(
369            "shunt `{name}` admittance does not have {n} rows"
370        )));
371    }
372    let mut active = LinDist3FlowAffineExpression::default();
373    let mut reactive = LinDist3FlowAffineExpression::default();
374    for other in 0..n {
375        if g[terminal].len() != n || b[terminal].len() != n {
376            return Err(invalid(format!(
377                "shunt `{name}` admittance row {terminal} does not have {n} entries"
378            )));
379        }
380        let admittance = Complex64::new(g[terminal][other], b[terminal][other]);
381        if !admittance.re.is_finite() || !admittance.im.is_finite() {
382            return Err(invalid(format!(
383                "shunt `{name}` admittance entry ({terminal}, {other}) is non-finite"
384            )));
385        }
386        let cross = cross_voltage_coefficients(reference[terminal], reference[other])?;
387        let scale = admittance.conj();
388        let constant = scale * cross.constant;
389        let own = scale * cross.coefficient_phi;
390        let other_coefficient = scale * cross.coefficient_psi;
391        active.constant += constant.re;
392        reactive.constant += constant.im;
393        active.voltage_terms.push(LinDist3FlowVoltageTerm {
394            node: terminal_nodes[terminal],
395            coefficient: own.re,
396        });
397        reactive.voltage_terms.push(LinDist3FlowVoltageTerm {
398            node: terminal_nodes[terminal],
399            coefficient: own.im,
400        });
401        active.voltage_terms.push(LinDist3FlowVoltageTerm {
402            node: terminal_nodes[other],
403            coefficient: other_coefficient.re,
404        });
405        reactive.voltage_terms.push(LinDist3FlowVoltageTerm {
406            node: terminal_nodes[other],
407            coefficient: other_coefficient.im,
408        });
409    }
410    Ok(LinDist3FlowComplexAffinePower { active, reactive })
411}
412
413fn checked_vector_value(
414    values: Option<&[f64]>,
415    channel: usize,
416    channels: usize,
417    label: &str,
418) -> Result<Option<f64>> {
419    let Some(values) = values else {
420        return Ok(None);
421    };
422    if values.len() != channels {
423        return Err(invalid(format!(
424            "{label} has length {}, expected {channels}",
425            values.len()
426        )));
427    }
428    let value = values[channel];
429    if !value.is_finite() {
430        return Err(invalid(format!("{label} entry {channel} is non-finite")));
431    }
432    Ok(Some(value))
433}
434
435fn positive_limit(
436    values: Option<&[f64]>,
437    channel: usize,
438    channels: usize,
439    label: &str,
440) -> Result<Option<f64>> {
441    let value = checked_vector_value(values, channel, channels, label)?;
442    if value.is_some_and(|value| value <= 0.0) {
443        return Err(invalid(format!("{label} entry {channel} must be positive")));
444    }
445    Ok(value)
446}
447
448fn generator_bounds(
449    nominal: f64,
450    lower: Option<&[f64]>,
451    upper: Option<&[f64]>,
452    channel: usize,
453    channels: usize,
454    label: &str,
455    selected: bool,
456) -> Result<(Option<f64>, Option<f64>)> {
457    if !selected {
458        return Ok((None, None));
459    }
460    let lower = checked_vector_value(lower, channel, channels, &format!("{label} minimum"))?;
461    let upper = checked_vector_value(upper, channel, channels, &format!("{label} maximum"))?;
462    let (lower, upper) = if lower.is_none() && upper.is_none() {
463        if !nominal.is_finite() {
464            return Err(invalid(format!("{label} nominal value is non-finite")));
465        }
466        (Some(nominal), Some(nominal))
467    } else {
468        (lower, upper)
469    };
470    if lower.zip(upper).is_some_and(|(lower, upper)| lower > upper) {
471        return Err(invalid(format!("{label} bounds are inverted")));
472    }
473    Ok((lower, upper))
474}
475
476fn cost_value(values: Option<&[f64]>, channel: usize, channels: usize, label: &str) -> Result<f64> {
477    let Some(values) = values else {
478        return Ok(0.0);
479    };
480    Ok(channel_value(values, channel, channels, label)? / 1000.0)
481}
482
483fn uses_dispatch_cost(instance: &LinDist3FlowOpfInstance) -> Result<bool> {
484    let mut enabled = false;
485    for term in instance.base_instance().objective().terms() {
486        match term {
487            ObjectiveTerm::ActivePowerDispatchCost => enabled = true,
488            ObjectiveTerm::NetworkGeneratorCost => {
489                return Err(invalid(
490                    "LinDist3Flow does not compile balanced-network generator cost curves",
491                ));
492            }
493            _ => {
494                return Err(invalid(
495                    "the LinDist3Flow objective contains an unknown term",
496                ));
497            }
498        }
499    }
500    Ok(enabled)
501}
502
503fn add_affine(
504    target: &mut LinDist3FlowAffineExpression,
505    source: &LinDist3FlowAffineExpression,
506    scale: f64,
507) {
508    target.constant += scale * source.constant;
509    target
510        .voltage_terms
511        .extend(source.voltage_terms.iter().filter_map(|term| {
512            let coefficient = scale * term.coefficient;
513            (coefficient.abs() > f64::EPSILON).then_some(LinDist3FlowVoltageTerm {
514                node: term.node,
515                coefficient,
516            })
517        }));
518}
519
520fn add_variable(
521    equation: &mut LinDist3FlowBalanceEquation,
522    variable: LinDist3FlowVariable,
523    coefficient: f64,
524) {
525    if coefficient.abs() > f64::EPSILON {
526        equation.variable_terms.push(LinDist3FlowBalanceTerm {
527            variable,
528            coefficient,
529        });
530    }
531}
532
533/// Prepare load, shunt, generator, source, objective, and KCL rows against an
534/// already prepared L3F node/line axis.
535///
536/// Every balance equation is stated as an affine expression plus semantic
537/// decision-variable terms, all constrained to zero. This keeps row numbering
538/// and cone storage decisions in the solver adapter.
539///
540/// # Errors
541/// A device has an unsupported connection or voltage model, inconsistent
542/// dimensions, an invalid bound/rating, or an unresolved terminal identity.
543#[allow(clippy::too_many_lines)]
544pub fn build_lindist3flow_device_data(
545    instance: &LinDist3FlowOpfInstance,
546    network_data: &LinDist3FlowNetworkData,
547) -> Result<LinDist3FlowDeviceData> {
548    let network = instance.network();
549    // The network data's nodes are powerio-dist's flat terminal index.
550    let positions = powerio_dist::MulticonductorTerminalIndex::build(network)
551        .map_err(|error| invalid(error.to_string()))?;
552    if positions.len() != network_data.nodes.len() {
553        return Err(invalid(
554            "the network data does not index this instance's terminals".to_owned(),
555        ));
556    }
557    let dispatch_cost = uses_dispatch_cost(instance)?;
558
559    let mut loads = Vec::with_capacity(network.loads().len());
560    for (row, load) in network.loads().iter().enumerate() {
561        if load.p_nom.len() != load.q_nom.len() || load.p_nom.is_empty() {
562            return Err(invalid(format!(
563                "load `{}` active/reactive channel counts are empty or unequal",
564                load.name
565            )));
566        }
567        let terminal_nodes = resolve_nodes(
568            &positions,
569            &load.bus,
570            &load.terminal_map,
571            "load",
572            &load.name,
573        )?;
574        let incidence = lindist3flow_connection_incidence(
575            load.configuration,
576            terminal_nodes.len(),
577            load.p_nom.len(),
578        )?;
579        let reference = references(instance, &terminal_nodes);
580        let terminal_power_map = connection_power_map(&incidence, &reference)?;
581        let channel_power = (0..load.p_nom.len())
582            .map(|channel| {
583                load_channel_power(load, &incidence, &reference, &terminal_nodes, channel)
584            })
585            .collect::<Result<Vec<_>>>()?;
586        loads.push(LinDist3FlowLoadData {
587            load: load.name.clone(),
588            source_load_row: row,
589            terminal_nodes,
590            incidence,
591            terminal_power_map,
592            channel_power,
593        });
594    }
595
596    let mut shunts = Vec::with_capacity(network.shunts().len());
597    for (row, shunt) in network.shunts().iter().enumerate() {
598        let terminal_nodes = resolve_nodes(
599            &positions,
600            &shunt.bus,
601            &shunt.terminal_map,
602            "shunt",
603            &shunt.name,
604        )?;
605        let reference = references(instance, &terminal_nodes);
606        let terminal_power = (0..terminal_nodes.len())
607            .map(|terminal| {
608                shunt_terminal_power(
609                    &shunt.name,
610                    &shunt.g,
611                    &shunt.b,
612                    &reference,
613                    &terminal_nodes,
614                    terminal,
615                )
616            })
617            .collect::<Result<Vec<_>>>()?;
618        shunts.push(LinDist3FlowShuntData {
619            shunt: shunt.name.clone(),
620            source_shunt_row: row,
621            terminal_nodes,
622            terminal_power,
623        });
624    }
625
626    let mut generators = Vec::with_capacity(network.generators().len());
627    for (row, generator) in network.generators().iter().enumerate() {
628        let channels = generator.p_nom.len();
629        if channels == 0 || generator.q_nom.len() != channels {
630            return Err(invalid(format!(
631                "generator `{}` active/reactive channel counts are empty or unequal",
632                generator.name
633            )));
634        }
635        let terminal_nodes = resolve_nodes(
636            &positions,
637            &generator.bus,
638            &generator.terminal_map,
639            "generator",
640            &generator.name,
641        )?;
642        let incidence = lindist3flow_connection_incidence(
643            generator.configuration,
644            terminal_nodes.len(),
645            channels,
646        )?;
647        let reference = references(instance, &terminal_nodes);
648        let terminal_power_map = connection_power_map(&incidence, &reference)?;
649        let capability_selected = instance
650            .base_instance()
651            .constraints()
652            .generator_capability
653            .selects(&generator.name);
654        let mut prepared_channels = Vec::with_capacity(channels);
655        for (channel, incidence_row) in incidence.iter().enumerate() {
656            let winding = winding_voltage_coefficients(incidence_row, &reference)?;
657            let squared_winding_voltage = global_affine(0.0, 1.0, &winding, &terminal_nodes);
658            let reference_winding_voltage =
659                terminal_power_map.reference_winding_voltage[channel].norm();
660            let (active_min, active_max) = generator_bounds(
661                generator.p_nom[channel],
662                generator.p_min.as_deref(),
663                generator.p_max.as_deref(),
664                channel,
665                channels,
666                "generator active power",
667                capability_selected,
668            )?;
669            let (reactive_min, reactive_max) = generator_bounds(
670                generator.q_nom[channel],
671                generator.q_min.as_deref(),
672                generator.q_max.as_deref(),
673                channel,
674                channels,
675                "generator reactive power",
676                capability_selected,
677            )?;
678            prepared_channels.push(LinDist3FlowDispatchChannel {
679                active_min,
680                active_max,
681                reactive_min,
682                reactive_max,
683                apparent_power_limit: capability_selected
684                    .then(|| {
685                        positive_limit(
686                            generator.s_max.as_deref(),
687                            channel,
688                            channels,
689                            "generator apparent-power limit",
690                        )
691                    })
692                    .transpose()?
693                    .flatten(),
694                current_limit: capability_selected
695                    .then(|| {
696                        positive_limit(
697                            generator.i_max.as_deref(),
698                            channel,
699                            channels,
700                            "generator current limit",
701                        )
702                    })
703                    .transpose()?
704                    .flatten(),
705                squared_winding_voltage,
706                reference_winding_voltage,
707                active_objective_coefficient: if dispatch_cost {
708                    cost_value(
709                        generator.cost.as_deref(),
710                        channel,
711                        channels,
712                        "generator cost",
713                    )?
714                } else {
715                    0.0
716                },
717            });
718        }
719        generators.push(LinDist3FlowGeneratorData {
720            generator: generator.name.clone(),
721            source_generator_row: row,
722            terminal_nodes,
723            incidence,
724            terminal_power_map,
725            channels: prepared_channels,
726        });
727    }
728
729    let mut sources = Vec::with_capacity(network.sources().len());
730    for (row, source) in network.sources().iter().enumerate() {
731        let terminal_nodes = resolve_nodes(
732            &positions,
733            &source.bus,
734            &source.terminal_map,
735            "voltage source",
736            &source.name,
737        )?;
738        let channels = terminal_nodes.len();
739        let active_objective_coefficient = (0..channels)
740            .map(|channel| {
741                if dispatch_cost {
742                    cost_value(
743                        source.energy_cost_rate.as_deref(),
744                        channel,
745                        channels,
746                        "voltage source energy cost",
747                    )
748                } else {
749                    Ok(0.0)
750                }
751            })
752            .collect::<Result<Vec<_>>>()?;
753        sources.push(LinDist3FlowSourceData {
754            source: source.name.clone(),
755            source_source_row: row,
756            terminal_nodes,
757            active_objective_coefficient,
758        });
759    }
760
761    let mut balances = (0..network_data.nodes.len())
762        .map(|node| LinDist3FlowBalanceRow {
763            node,
764            active: LinDist3FlowBalanceEquation::default(),
765            reactive: LinDist3FlowBalanceEquation::default(),
766        })
767        .collect::<Vec<_>>();
768    for (line_index, line) in network_data.lines.iter().enumerate() {
769        for conductor in 0..line.parent_nodes.len() {
770            add_variable(
771                &mut balances[line.parent_nodes[conductor]].active,
772                LinDist3FlowVariable::LineActive {
773                    line: line_index,
774                    conductor,
775                },
776                -1.0,
777            );
778            add_variable(
779                &mut balances[line.parent_nodes[conductor]].reactive,
780                LinDist3FlowVariable::LineReactive {
781                    line: line_index,
782                    conductor,
783                },
784                -1.0,
785            );
786            add_variable(
787                &mut balances[line.child_nodes[conductor]].active,
788                LinDist3FlowVariable::LineActive {
789                    line: line_index,
790                    conductor,
791                },
792                1.0,
793            );
794            add_variable(
795                &mut balances[line.child_nodes[conductor]].reactive,
796                LinDist3FlowVariable::LineReactive {
797                    line: line_index,
798                    conductor,
799                },
800                1.0,
801            );
802        }
803    }
804    for load in &loads {
805        for terminal in 0..load.terminal_nodes.len() {
806            let balance = &mut balances[load.terminal_nodes[terminal]];
807            for channel in 0..load.channel_power.len() {
808                let power = &load.channel_power[channel];
809                let real = load.terminal_power_map.real_part[terminal][channel];
810                let imag = load.terminal_power_map.imag_part[terminal][channel];
811                add_affine(&mut balance.active.affine, &power.active, -real);
812                add_affine(&mut balance.active.affine, &power.reactive, imag);
813                add_affine(&mut balance.reactive.affine, &power.active, -imag);
814                add_affine(&mut balance.reactive.affine, &power.reactive, -real);
815            }
816        }
817    }
818    for shunt in &shunts {
819        for (terminal, &node) in shunt.terminal_nodes.iter().enumerate() {
820            add_affine(
821                &mut balances[node].active.affine,
822                &shunt.terminal_power[terminal].active,
823                -1.0,
824            );
825            add_affine(
826                &mut balances[node].reactive.affine,
827                &shunt.terminal_power[terminal].reactive,
828                -1.0,
829            );
830        }
831    }
832    for (generator_index, generator) in generators.iter().enumerate() {
833        for terminal in 0..generator.terminal_nodes.len() {
834            let balance = &mut balances[generator.terminal_nodes[terminal]];
835            for channel in 0..generator.channels.len() {
836                let real = generator.terminal_power_map.real_part[terminal][channel];
837                let imag = generator.terminal_power_map.imag_part[terminal][channel];
838                add_variable(
839                    &mut balance.active,
840                    LinDist3FlowVariable::GeneratorActive {
841                        generator: generator_index,
842                        channel,
843                    },
844                    real,
845                );
846                add_variable(
847                    &mut balance.active,
848                    LinDist3FlowVariable::GeneratorReactive {
849                        generator: generator_index,
850                        channel,
851                    },
852                    -imag,
853                );
854                add_variable(
855                    &mut balance.reactive,
856                    LinDist3FlowVariable::GeneratorActive {
857                        generator: generator_index,
858                        channel,
859                    },
860                    imag,
861                );
862                add_variable(
863                    &mut balance.reactive,
864                    LinDist3FlowVariable::GeneratorReactive {
865                        generator: generator_index,
866                        channel,
867                    },
868                    real,
869                );
870            }
871        }
872    }
873    for (source_index, source) in sources.iter().enumerate() {
874        for (channel, &node) in source.terminal_nodes.iter().enumerate() {
875            add_variable(
876                &mut balances[node].active,
877                LinDist3FlowVariable::SourceActive {
878                    source: source_index,
879                    channel,
880                },
881                1.0,
882            );
883            add_variable(
884                &mut balances[node].reactive,
885                LinDist3FlowVariable::SourceReactive {
886                    source: source_index,
887                    channel,
888                },
889                1.0,
890            );
891        }
892    }
893
894    Ok(LinDist3FlowDeviceData {
895        loads,
896        shunts,
897        generators,
898        sources,
899        balances,
900    })
901}
902
903/// Build the complete solver-neutral preparation for the supported L3F slice.
904///
905/// # Errors
906/// As [`build_lindist3flow_network_data`] and
907/// [`build_lindist3flow_device_data`].
908pub fn build_lindist3flow_preparation(
909    instance: &LinDist3FlowOpfInstance,
910) -> Result<LinDist3FlowPreparation> {
911    let network = build_lindist3flow_network_data(instance)?;
912    let devices = build_lindist3flow_device_data(instance, &network)?;
913    Ok(LinDist3FlowPreparation { network, devices })
914}
915
916#[cfg(test)]
917mod tests {
918    use std::f64::consts::PI;
919
920    use approx::assert_relative_eq;
921    use powerio_dist::{
922        Configuration, DistBus, DistGenerator, DistLine, DistLineCode, DistLoad, DistShunt,
923        MulticonductorNetwork, VoltageSource,
924    };
925    use powerio_prob::{
926        ConstraintSelection, LinDist3FlowBuildOptions, LinDist3FlowOpfInstance, McAcOpfInstance,
927        MulticonductorActiveConstraints,
928    };
929
930    use super::*;
931
932    fn one_phase_network() -> MulticonductorNetwork {
933        let terminal = vec!["1".to_owned()];
934        let mut network = MulticonductorNetwork::named("one-phase");
935        network
936            .buses_mut()
937            .push(DistBus::new("source", terminal.clone()));
938        network
939            .buses_mut()
940            .push(DistBus::new("load", terminal.clone()));
941        network
942            .line_codes_mut()
943            .push(DistLineCode::new("one", vec![vec![0.1]], vec![vec![0.2]]));
944        network.lines_mut().push(DistLine::new(
945            "line",
946            "source",
947            "load",
948            terminal.clone(),
949            terminal.clone(),
950            "one",
951            1.0,
952        ));
953        network.sources_mut().push(VoltageSource::new(
954            "grid",
955            "source",
956            terminal,
957            vec![230.0],
958            vec![0.0],
959        ));
960        network
961    }
962
963    fn three_phase_network() -> MulticonductorNetwork {
964        let terminals = vec!["1".to_owned(), "2".to_owned(), "3".to_owned()];
965        let mut network = MulticonductorNetwork::named("three-phase");
966        network
967            .buses_mut()
968            .push(DistBus::new("source", terminals.clone()));
969        network
970            .buses_mut()
971            .push(DistBus::new("load", terminals.clone()));
972        network.line_codes_mut().push(DistLineCode::new(
973            "three",
974            vec![
975                vec![0.1, 0.0, 0.0],
976                vec![0.0, 0.1, 0.0],
977                vec![0.0, 0.0, 0.1],
978            ],
979            vec![
980                vec![0.2, 0.0, 0.0],
981                vec![0.0, 0.2, 0.0],
982                vec![0.0, 0.0, 0.2],
983            ],
984        ));
985        network.lines_mut().push(DistLine::new(
986            "line",
987            "source",
988            "load",
989            terminals.clone(),
990            terminals.clone(),
991            "three",
992            1.0,
993        ));
994        network.sources_mut().push(VoltageSource::new(
995            "grid",
996            "source",
997            terminals,
998            vec![230.0; 3],
999            vec![0.0, -2.0 * PI / 3.0, 2.0 * PI / 3.0],
1000        ));
1001        network
1002    }
1003
1004    fn evaluate(expression: &LinDist3FlowAffineExpression, squared_voltage: &[f64]) -> f64 {
1005        expression.constant
1006            + expression
1007                .voltage_terms
1008                .iter()
1009                .map(|term| term.coefficient * squared_voltage[term.node])
1010                .sum::<f64>()
1011    }
1012
1013    #[test]
1014    fn connection_incidence_matches_supported_physical_channels() {
1015        assert_eq!(
1016            lindist3flow_connection_incidence(Configuration::SinglePhase, 2, 1).unwrap(),
1017            [vec![1.0, -1.0]]
1018        );
1019        assert_eq!(
1020            lindist3flow_connection_incidence(Configuration::Wye, 2, 2).unwrap(),
1021            [vec![1.0, 0.0], vec![0.0, 1.0]]
1022        );
1023        assert_eq!(
1024            lindist3flow_connection_incidence(Configuration::Delta, 3, 3).unwrap()[2],
1025            [-1.0, 0.0, 1.0]
1026        );
1027        assert!(lindist3flow_connection_incidence(Configuration::Delta, 3, 1).is_err());
1028    }
1029
1030    #[test]
1031    fn constant_power_load_and_line_flows_have_the_reference_kcl_signs() {
1032        let mut network = one_phase_network();
1033        network.loads_mut().push(DistLoad::new(
1034            "demand",
1035            "load",
1036            vec!["1".to_owned()],
1037            Configuration::Wye,
1038            vec![1_000.0],
1039            vec![200.0],
1040        ));
1041        let instance =
1042            LinDist3FlowOpfInstance::from_network(network, LinDist3FlowBuildOptions::default())
1043                .unwrap();
1044        let preparation = build_lindist3flow_preparation(&instance).unwrap();
1045
1046        let source = &preparation.devices.balances[0];
1047        assert!(
1048            source
1049                .active
1050                .variable_terms
1051                .contains(&LinDist3FlowBalanceTerm {
1052                    variable: LinDist3FlowVariable::SourceActive {
1053                        source: 0,
1054                        channel: 0,
1055                    },
1056                    coefficient: 1.0,
1057                })
1058        );
1059        assert!(
1060            source
1061                .active
1062                .variable_terms
1063                .contains(&LinDist3FlowBalanceTerm {
1064                    variable: LinDist3FlowVariable::LineActive {
1065                        line: 0,
1066                        conductor: 0,
1067                    },
1068                    coefficient: -1.0,
1069                })
1070        );
1071        let load = &preparation.devices.balances[1];
1072        assert_relative_eq!(load.active.affine.constant, -1_000.0, epsilon = 1e-12);
1073        assert_relative_eq!(load.reactive.affine.constant, -200.0, epsilon = 1e-12);
1074        assert!(
1075            load.active
1076                .variable_terms
1077                .contains(&LinDist3FlowBalanceTerm {
1078                    variable: LinDist3FlowVariable::LineActive {
1079                        line: 0,
1080                        conductor: 0,
1081                    },
1082                    coefficient: 1.0,
1083                })
1084        );
1085    }
1086
1087    #[test]
1088    fn delta_zp_load_is_affine_and_exact_at_the_reference() {
1089        let mut network = three_phase_network();
1090        let mut load = DistLoad::new(
1091            "delta",
1092            "load",
1093            vec!["1".to_owned(), "2".to_owned(), "3".to_owned()],
1094            Configuration::Delta,
1095            vec![1_000.0, 2_000.0, 3_000.0],
1096            vec![100.0, 200.0, 300.0],
1097        );
1098        load.voltage_model = DistLoadVoltageModel::Zip {
1099            v_nom: vec![230.0 * 3.0_f64.sqrt()],
1100            alpha_z: vec![0.4],
1101            alpha_i: vec![0.0],
1102            alpha_p: vec![0.6],
1103            beta_z: vec![0.25],
1104            beta_i: vec![0.0],
1105            beta_p: vec![0.75],
1106        };
1107        network.loads_mut().push(load);
1108        let instance =
1109            LinDist3FlowOpfInstance::from_network(network, LinDist3FlowBuildOptions::default())
1110                .unwrap();
1111        let preparation = build_lindist3flow_preparation(&instance).unwrap();
1112        let squared_voltage = preparation
1113            .network
1114            .nodes
1115            .iter()
1116            .map(|node| node.reference_magnitude.powi(2))
1117            .collect::<Vec<_>>();
1118        let load = &preparation.devices.loads[0];
1119
1120        for channel in 0..3 {
1121            assert_relative_eq!(
1122                evaluate(&load.channel_power[channel].active, &squared_voltage),
1123                [1_000.0, 2_000.0, 3_000.0][channel],
1124                epsilon = 1e-9
1125            );
1126            let allocation_sum = (0..3)
1127                .map(|terminal| load.terminal_power_map.matrix[terminal][channel])
1128                .sum::<Complex64>();
1129            assert_relative_eq!(allocation_sum.re, 1.0, epsilon = 1e-12);
1130            assert_relative_eq!(allocation_sum.im, 0.0, epsilon = 1e-12);
1131        }
1132    }
1133
1134    #[test]
1135    fn generator_rows_keep_bounds_cost_soc_voltage_and_terminal_map() {
1136        let mut network = one_phase_network();
1137        let mut generator = DistGenerator::new(
1138            "der",
1139            "load",
1140            vec!["1".to_owned()],
1141            Configuration::Wye,
1142            vec![500.0],
1143            vec![0.0],
1144        );
1145        generator.p_min = Some(vec![0.0]);
1146        generator.p_max = Some(vec![1_000.0]);
1147        generator.q_min = Some(vec![-300.0]);
1148        generator.q_max = Some(vec![300.0]);
1149        generator.cost = Some(vec![0.2]);
1150        generator.s_max = Some(vec![1_100.0]);
1151        generator.i_max = Some(vec![5.0]);
1152        network.generators_mut().push(generator);
1153        let instance =
1154            LinDist3FlowOpfInstance::from_network(network, LinDist3FlowBuildOptions::default())
1155                .unwrap();
1156        let preparation = build_lindist3flow_preparation(&instance).unwrap();
1157        let channel = &preparation.devices.generators[0].channels[0];
1158
1159        assert_eq!(channel.active_min, Some(0.0));
1160        assert_eq!(channel.active_max, Some(1_000.0));
1161        assert_eq!(channel.reactive_min, Some(-300.0));
1162        assert_eq!(channel.reactive_max, Some(300.0));
1163        assert_eq!(channel.apparent_power_limit, Some(1_100.0));
1164        assert_eq!(channel.current_limit, Some(5.0));
1165        assert_relative_eq!(
1166            channel.active_objective_coefficient,
1167            0.0002,
1168            epsilon = 1e-15
1169        );
1170        assert_relative_eq!(channel.reference_winding_voltage, 230.0, epsilon = 1e-12);
1171        assert_relative_eq!(
1172            evaluate(
1173                &channel.squared_winding_voltage,
1174                &[230.0_f64.powi(2), 230.0_f64.powi(2)]
1175            ),
1176            230.0_f64.powi(2),
1177            epsilon = 1e-9
1178        );
1179    }
1180
1181    #[test]
1182    fn shunt_power_enters_balance_as_an_affine_absorption() {
1183        let mut network = one_phase_network();
1184        network.shunts_mut().push(DistShunt::new(
1185            "capacitive",
1186            "load",
1187            vec!["1".to_owned()],
1188            vec![vec![0.0]],
1189            vec![vec![0.01]],
1190        ));
1191        let instance =
1192            LinDist3FlowOpfInstance::from_network(network, LinDist3FlowBuildOptions::default())
1193                .unwrap();
1194        let preparation = build_lindist3flow_preparation(&instance).unwrap();
1195        let squared_voltage = vec![230.0_f64.powi(2); 2];
1196        let shunt = &preparation.devices.shunts[0].terminal_power[0];
1197
1198        assert_relative_eq!(
1199            evaluate(&shunt.active, &squared_voltage),
1200            0.0,
1201            epsilon = 1e-9
1202        );
1203        assert_relative_eq!(
1204            evaluate(&shunt.reactive, &squared_voltage),
1205            -0.01 * 230.0_f64.powi(2),
1206            epsilon = 1e-9
1207        );
1208        assert_relative_eq!(
1209            evaluate(
1210                &preparation.devices.balances[1].reactive.affine,
1211                &squared_voltage
1212            ),
1213            0.01 * 230.0_f64.powi(2),
1214            epsilon = 1e-9
1215        );
1216    }
1217
1218    #[test]
1219    fn inactive_constraint_families_remove_only_their_numerical_limits() {
1220        let mut network = one_phase_network();
1221        network.buses_mut()[1].v_min = Some(210.0);
1222        network.lines_mut()[0].i_max = Some(vec![100.0]);
1223        let mut generator = DistGenerator::new(
1224            "der",
1225            "load",
1226            vec!["1".to_owned()],
1227            Configuration::Wye,
1228            vec![500.0],
1229            vec![0.0],
1230        );
1231        generator.p_min = Some(vec![0.0]);
1232        generator.p_max = Some(vec![1_000.0]);
1233        network.generators_mut().push(generator);
1234        let mut constraints = MulticonductorActiveConstraints::default();
1235        constraints.terminal_voltage_bounds = ConstraintSelection::None;
1236        constraints.conductor_limits = ConstraintSelection::None;
1237        constraints.generator_capability = ConstraintSelection::None;
1238        let base = McAcOpfInstance::from_network(network)
1239            .unwrap()
1240            .with_constraints(constraints);
1241        let instance =
1242            LinDist3FlowOpfInstance::from_mc_ac(base, LinDist3FlowBuildOptions::default()).unwrap();
1243        let preparation = build_lindist3flow_preparation(&instance).unwrap();
1244
1245        assert!(preparation.network.nodes[1].squared_voltage_min.is_none());
1246        assert_eq!(preparation.network.lines[0].current_limit, [None]);
1247        assert!(
1248            preparation.devices.generators[0].channels[0]
1249                .active_min
1250                .is_none()
1251        );
1252    }
1253}