Skip to main content

powerio_tx/
dynamic_models.rs

1//! Typed views over PSS/E DYR records, and model-aware linking of DYR records
2//! to the generators of a [`crate::BalancedNetwork`].
3//!
4//! [`crate::dynamic`] keeps every DYR record loss-preserving and untyped. This
5//! module adds a schema-backed *view* on top of it for the models whose
6//! parameter layout is documented in the PSS/E Model Library: it never changes
7//! the retained records, so `DynamicCase::to_dyr_string` still writes the
8//! source back byte for byte.
9//!
10//! Parameters keep PSS/E names, order, units and bases (machine parameters
11//! are on the machine base `MBASE`). Converting them into the parameters of a
12//! particular simulator's equations is the simulator's job.
13//!
14//! Supported models: machines `GENCLS`, `GENROU`, `GENROE`, `GENSAL`,
15//! `GENSAE`; exciters `SEXS`, `ESAC1A`, `EXST1`; governors `TGOV1`, `GAST`, `HYGOV`;
16//! stabilizer `IEEEST`. Any other model name is reported as
17//! [`ModelError::Unsupported`] and stays available as a raw record.
18
19use std::collections::BTreeMap;
20use std::fmt;
21
22use crate::BalancedNetwork;
23use crate::dynamic::{DynamicCase, DynamicRecord};
24use crate::format::psse::detailed_source_property;
25use crate::network::BusId;
26
27/// Round-rotor machine data shared by `GENROU` (quadratic saturation) and
28/// `GENROE` (exponential saturation), in DYR order.
29#[derive(Clone, Copy, Debug, PartialEq)]
30#[non_exhaustive]
31pub struct RoundRotor {
32    pub td0_p: f64,
33    pub td0_pp: f64,
34    pub tq0_p: f64,
35    pub tq0_pp: f64,
36    pub h: f64,
37    pub d: f64,
38    pub xd: f64,
39    pub xq: f64,
40    pub xd_p: f64,
41    pub xq_p: f64,
42    /// `X''d = X''q`.
43    pub xd_pp: f64,
44    pub xl: f64,
45    /// Saturation at 1.0 pu flux, `S(1.0)`.
46    pub s1: f64,
47    /// Saturation at 1.2 pu flux, `S(1.2)`.
48    pub s12: f64,
49}
50
51/// Salient-pole machine data shared by `GENSAL` and `GENSAE`, in DYR order.
52#[derive(Clone, Copy, Debug, PartialEq)]
53#[non_exhaustive]
54pub struct SalientPole {
55    pub td0_p: f64,
56    pub td0_pp: f64,
57    pub tq0_pp: f64,
58    pub h: f64,
59    pub d: f64,
60    pub xd: f64,
61    pub xq: f64,
62    pub xd_p: f64,
63    /// `X''d = X''q`.
64    pub xd_pp: f64,
65    pub xl: f64,
66    pub s1: f64,
67    pub s12: f64,
68}
69
70/// Classical machine `GENCLS`: inertia and damping. The transient reactance
71/// is the generator's `ZSORCE` in the static case.
72#[derive(Clone, Copy, Debug, PartialEq)]
73#[non_exhaustive]
74pub struct Gencls {
75    pub h: f64,
76    pub d: f64,
77}
78
79/// Simplified excitation system `SEXS`.
80#[derive(Clone, Copy, Debug, PartialEq)]
81#[non_exhaustive]
82pub struct Sexs {
83    /// `TA/TB`.
84    pub ta_tb: f64,
85    pub tb: f64,
86    pub k: f64,
87    pub te: f64,
88    pub emin: f64,
89    pub emax: f64,
90}
91
92/// IEEE 421.5 AC1A excitation system `ESAC1A`.
93#[derive(Clone, Copy, Debug, PartialEq)]
94#[non_exhaustive]
95pub struct Esac1a {
96    pub tr: f64,
97    pub tb: f64,
98    pub tc: f64,
99    pub ka: f64,
100    pub ta: f64,
101    pub vamax: f64,
102    pub vamin: f64,
103    pub te: f64,
104    pub kf: f64,
105    pub tf: f64,
106    pub kc: f64,
107    pub kd: f64,
108    pub ke: f64,
109    pub e1: f64,
110    pub se_e1: f64,
111    pub e2: f64,
112    pub se_e2: f64,
113    pub vrmax: f64,
114    pub vrmin: f64,
115}
116
117/// IEEE type ST1 static excitation system `EXST1`.
118#[derive(Clone, Copy, Debug, PartialEq)]
119#[non_exhaustive]
120pub struct Exst1 {
121    pub tr: f64,
122    pub vimax: f64,
123    pub vimin: f64,
124    pub tc: f64,
125    pub tb: f64,
126    pub ka: f64,
127    pub ta: f64,
128    pub vrmax: f64,
129    pub vrmin: f64,
130    pub kc: f64,
131    pub kf: f64,
132    pub tf: f64,
133}
134
135/// Steam turbine-governor `TGOV1`.
136#[derive(Clone, Copy, Debug, PartialEq)]
137#[non_exhaustive]
138pub struct Tgov1 {
139    pub r: f64,
140    pub t1: f64,
141    pub vmax: f64,
142    pub vmin: f64,
143    pub t2: f64,
144    pub t3: f64,
145    pub dt: f64,
146}
147
148/// Gas turbine-governor `GAST`.
149#[derive(Clone, Copy, Debug, PartialEq)]
150#[non_exhaustive]
151pub struct Gast {
152    pub r: f64,
153    pub t1: f64,
154    pub t2: f64,
155    pub t3: f64,
156    pub at: f64,
157    pub kt: f64,
158    pub vmax: f64,
159    pub vmin: f64,
160    pub dturb: f64,
161}
162
163/// Hydro turbine-governor `HYGOV`.
164#[derive(Clone, Copy, Debug, PartialEq)]
165#[non_exhaustive]
166pub struct Hygov {
167    pub r: f64,
168    pub r_temp: f64,
169    pub tr: f64,
170    pub tf: f64,
171    pub tg: f64,
172    pub velm: f64,
173    pub gmax: f64,
174    pub gmin: f64,
175    pub tw: f64,
176    pub at: f64,
177    pub dturb: f64,
178    pub qnl: f64,
179}
180
181/// IEEE stabilizer `IEEEST`.
182#[derive(Clone, Copy, Debug, PartialEq)]
183#[non_exhaustive]
184pub struct Ieeest {
185    /// `ICS`, in `1..=6`: 1 rotor speed deviation, 2 bus frequency
186    /// deviation, 3 generator electrical power, 4 accelerating power, 5 bus
187    /// voltage, 6 bus voltage derivative.
188    pub input_code: u8,
189    /// `IB`: remote bus for the input signal; `None` when the record states 0,
190    /// the generator's own bus.
191    pub remote_bus: Option<BusId>,
192    pub a1: f64,
193    pub a2: f64,
194    pub a3: f64,
195    pub a4: f64,
196    pub a5: f64,
197    pub a6: f64,
198    pub t1: f64,
199    pub t2: f64,
200    pub t3: f64,
201    pub t4: f64,
202    pub t5: f64,
203    pub t6: f64,
204    pub ks: f64,
205    pub lsmax: f64,
206    pub lsmin: f64,
207    pub vcu: f64,
208    pub vcl: f64,
209}
210
211/// A DYR record read through its PSS/E parameter schema.
212#[derive(Clone, Debug, PartialEq)]
213#[non_exhaustive]
214pub enum DynamicModel {
215    Gencls(Gencls),
216    Genrou(RoundRotor),
217    Genroe(RoundRotor),
218    Gensal(SalientPole),
219    Gensae(SalientPole),
220    Sexs(Sexs),
221    Esac1a(Esac1a),
222    Exst1(Exst1),
223    Tgov1(Tgov1),
224    Gast(Gast),
225    Hygov(Hygov),
226    Ieeest(Ieeest),
227}
228
229/// The role a model plays in a generating unit.
230#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
231#[non_exhaustive]
232pub enum ModelRole {
233    Machine,
234    Exciter,
235    Governor,
236    Stabilizer,
237}
238
239impl DynamicModel {
240    /// The PSS/E model name.
241    #[must_use]
242    pub fn name(&self) -> &'static str {
243        match self {
244            Self::Gencls(_) => "GENCLS",
245            Self::Genrou(_) => "GENROU",
246            Self::Genroe(_) => "GENROE",
247            Self::Gensal(_) => "GENSAL",
248            Self::Gensae(_) => "GENSAE",
249            Self::Sexs(_) => "SEXS",
250            Self::Esac1a(_) => "ESAC1A",
251            Self::Exst1(_) => "EXST1",
252            Self::Tgov1(_) => "TGOV1",
253            Self::Gast(_) => "GAST",
254            Self::Hygov(_) => "HYGOV",
255            Self::Ieeest(_) => "IEEEST",
256        }
257    }
258
259    /// Machine, exciter, governor or stabilizer.
260    #[must_use]
261    pub fn role(&self) -> ModelRole {
262        match self {
263            Self::Gencls(_)
264            | Self::Genrou(_)
265            | Self::Genroe(_)
266            | Self::Gensal(_)
267            | Self::Gensae(_) => ModelRole::Machine,
268            Self::Sexs(_) | Self::Esac1a(_) | Self::Exst1(_) => ModelRole::Exciter,
269            Self::Tgov1(_) | Self::Gast(_) | Self::Hygov(_) => ModelRole::Governor,
270            Self::Ieeest(_) => ModelRole::Stabilizer,
271        }
272    }
273}
274
275/// The model names this module reads, with the parameter count each record
276/// states after its device id.
277pub const SUPPORTED_MODELS: &[(&str, usize)] = &[
278    ("GENCLS", 2),
279    ("GENROU", 14),
280    ("GENROE", 14),
281    ("GENSAL", 12),
282    ("GENSAE", 12),
283    ("SEXS", 6),
284    ("ESAC1A", 19),
285    ("EXST1", 12),
286    ("TGOV1", 7),
287    ("GAST", 9),
288    ("HYGOV", 12),
289    ("IEEEST", 19),
290];
291
292/// Why a record has no typed view.
293#[derive(Clone, Debug, PartialEq, Eq)]
294#[non_exhaustive]
295pub enum ModelError {
296    /// The model is not in [`SUPPORTED_MODELS`]; the record stays raw.
297    Unsupported { model_name: String },
298    /// The record states another number of parameters than the schema.
299    Arity {
300        model_name: String,
301        expected: usize,
302        found: usize,
303    },
304    /// A parameter token is not a finite number.
305    NotANumber {
306        model_name: String,
307        index: usize,
308        token: String,
309    },
310    /// An integer parameter (`ICON`) is not an integer, or is outside the
311    /// range the model accepts: `IEEEST` `ICS` must be in `1..=6`, and `IB`
312    /// a bus number from 0 to `u32::MAX`.
313    InvalidIcon {
314        model_name: String,
315        index: usize,
316        token: String,
317    },
318}
319
320impl fmt::Display for ModelError {
321    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
322        match self {
323            Self::Unsupported { model_name } => write!(f, "model {model_name} has no typed view"),
324            Self::Arity {
325                model_name,
326                expected,
327                found,
328            } => write!(
329                f,
330                "{model_name} states {found} parameters, the PSS/E schema has {expected}"
331            ),
332            Self::NotANumber {
333                model_name,
334                index,
335                token,
336            } => write!(
337                f,
338                "{model_name} parameter {} ({token:?}) is not a finite number",
339                index + 1
340            ),
341            Self::InvalidIcon {
342                model_name,
343                index,
344                token,
345            } => write!(
346                f,
347                "{model_name} parameter {} ({token:?}) is not a valid integer code",
348                index + 1
349            ),
350        }
351    }
352}
353
354impl std::error::Error for ModelError {}
355
356fn numbers(record: &DynamicRecord, expected: usize) -> Result<Vec<f64>, ModelError> {
357    let name = record.model_name().to_ascii_uppercase();
358    let params = record.parameters();
359    if params.len() != expected {
360        return Err(ModelError::Arity {
361            model_name: name,
362            expected,
363            found: params.len(),
364        });
365    }
366    params
367        .iter()
368        .enumerate()
369        .map(|(index, token)| {
370            // Fortran list-directed output may write `1.0D0` for `1.0E0`.
371            token
372                .trim()
373                .replacen(['D', 'd'], "E", 1)
374                .parse::<f64>()
375                .ok()
376                .filter(|v| v.is_finite())
377                .ok_or_else(|| ModelError::NotANumber {
378                    model_name: name.clone(),
379                    index,
380                    token: token.clone(),
381                })
382        })
383        .collect()
384}
385
386/// An integer parameter of an already finite value: the value must be exactly
387/// integral (`1` or `1.0`) and inside `range`.
388#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
389fn icon(
390    record: &DynamicRecord,
391    p: &[f64],
392    index: usize,
393    range: std::ops::RangeInclusive<u32>,
394) -> Result<u32, ModelError> {
395    let value = p[index];
396    let in_range = value.fract() == 0.0
397        && value >= f64::from(*range.start())
398        && value <= f64::from(*range.end());
399    if in_range {
400        // Exact: an integral value inside a `u32` range.
401        Ok(value as u32)
402    } else {
403        Err(ModelError::InvalidIcon {
404            model_name: record.model_name().trim().to_ascii_uppercase(),
405            index,
406            token: record.parameters()[index].clone(),
407        })
408    }
409}
410
411fn round_rotor(p: &[f64]) -> RoundRotor {
412    RoundRotor {
413        td0_p: p[0],
414        td0_pp: p[1],
415        tq0_p: p[2],
416        tq0_pp: p[3],
417        h: p[4],
418        d: p[5],
419        xd: p[6],
420        xq: p[7],
421        xd_p: p[8],
422        xq_p: p[9],
423        xd_pp: p[10],
424        xl: p[11],
425        s1: p[12],
426        s12: p[13],
427    }
428}
429
430fn salient_pole(p: &[f64]) -> SalientPole {
431    SalientPole {
432        td0_p: p[0],
433        td0_pp: p[1],
434        tq0_pp: p[2],
435        h: p[3],
436        d: p[4],
437        xd: p[5],
438        xq: p[6],
439        xd_p: p[7],
440        xd_pp: p[8],
441        xl: p[9],
442        s1: p[10],
443        s12: p[11],
444    }
445}
446
447/// Read a DYR record through its PSS/E parameter schema.
448///
449/// # Errors
450/// [`ModelError::Unsupported`] for a model outside [`SUPPORTED_MODELS`],
451/// [`ModelError::Arity`] or [`ModelError::NotANumber`] when the record does
452/// not match the schema, [`ModelError::InvalidIcon`] for an integer parameter
453/// that is not an integer in range. Other parameter values pass through
454/// unchecked: several zeros carry PSS/E meaning (a zero time constant
455/// bypasses its block, `GENCLS` `H = 0` is an infinite bus).
456#[allow(clippy::cast_possible_truncation, clippy::too_many_lines)] // one arm per schema
457pub fn typed_model(record: &DynamicRecord) -> Result<DynamicModel, ModelError> {
458    let name = record.model_name().trim().to_ascii_uppercase();
459    let Some(&(_, arity)) = SUPPORTED_MODELS.iter().find(|(n, _)| *n == name) else {
460        return Err(ModelError::Unsupported { model_name: name });
461    };
462    let p = numbers(record, arity)?;
463    Ok(match name.as_str() {
464        "GENCLS" => DynamicModel::Gencls(Gencls { h: p[0], d: p[1] }),
465        "GENROU" => DynamicModel::Genrou(round_rotor(&p)),
466        "GENROE" => DynamicModel::Genroe(round_rotor(&p)),
467        "GENSAL" => DynamicModel::Gensal(salient_pole(&p)),
468        "GENSAE" => DynamicModel::Gensae(salient_pole(&p)),
469        "SEXS" => DynamicModel::Sexs(Sexs {
470            ta_tb: p[0],
471            tb: p[1],
472            k: p[2],
473            te: p[3],
474            emin: p[4],
475            emax: p[5],
476        }),
477        "ESAC1A" => DynamicModel::Esac1a(Esac1a {
478            tr: p[0],
479            tb: p[1],
480            tc: p[2],
481            ka: p[3],
482            ta: p[4],
483            vamax: p[5],
484            vamin: p[6],
485            te: p[7],
486            kf: p[8],
487            tf: p[9],
488            kc: p[10],
489            kd: p[11],
490            ke: p[12],
491            e1: p[13],
492            se_e1: p[14],
493            e2: p[15],
494            se_e2: p[16],
495            vrmax: p[17],
496            vrmin: p[18],
497        }),
498        "EXST1" => DynamicModel::Exst1(Exst1 {
499            tr: p[0],
500            vimax: p[1],
501            vimin: p[2],
502            tc: p[3],
503            tb: p[4],
504            ka: p[5],
505            ta: p[6],
506            vrmax: p[7],
507            vrmin: p[8],
508            kc: p[9],
509            kf: p[10],
510            tf: p[11],
511        }),
512        "TGOV1" => DynamicModel::Tgov1(Tgov1 {
513            r: p[0],
514            t1: p[1],
515            vmax: p[2],
516            vmin: p[3],
517            t2: p[4],
518            t3: p[5],
519            dt: p[6],
520        }),
521        "GAST" => DynamicModel::Gast(Gast {
522            r: p[0],
523            t1: p[1],
524            t2: p[2],
525            t3: p[3],
526            at: p[4],
527            kt: p[5],
528            vmax: p[6],
529            vmin: p[7],
530            dturb: p[8],
531        }),
532        "HYGOV" => DynamicModel::Hygov(Hygov {
533            r: p[0],
534            r_temp: p[1],
535            tr: p[2],
536            tf: p[3],
537            tg: p[4],
538            velm: p[5],
539            gmax: p[6],
540            gmin: p[7],
541            tw: p[8],
542            at: p[9],
543            dturb: p[10],
544            qnl: p[11],
545        }),
546        "IEEEST" => DynamicModel::Ieeest(Ieeest {
547            // Exact: ICS is in 1..=6.
548            input_code: icon(record, &p, 0, 1..=6)? as u8,
549            remote_bus: Some(icon(record, &p, 1, 0..=u32::MAX)?)
550                .filter(|&bus| bus != 0)
551                .map(|bus| BusId(bus as usize)),
552            a1: p[2],
553            a2: p[3],
554            a3: p[4],
555            a4: p[5],
556            a5: p[6],
557            a6: p[7],
558            t1: p[8],
559            t2: p[9],
560            t3: p[10],
561            t4: p[11],
562            t5: p[12],
563            t6: p[13],
564            ks: p[14],
565            lsmax: p[15],
566            lsmin: p[16],
567            vcu: p[17],
568            vcl: p[18],
569        }),
570        _ => unreachable!("every supported model has a schema arm"),
571    })
572}
573
574/// The PSS/E machine id of every generator, aligned with
575/// [`BalancedNetwork::generators`], trimmed: the id the PSS/E writer states for
576/// it and the `.con` resolver matches (the retained id, else the lowest
577/// positional id still free on the bus). DYR records name generators by
578/// `(bus, machine id)`.
579#[must_use]
580pub fn psse_machine_ids(net: &BalancedNetwork) -> Vec<String> {
581    let (ids, _) = crate::contingency::machine_index(net, &mut 0);
582    ids.into_iter().map(|id| id.trim().to_owned()).collect()
583}
584
585/// The generator's source impedance `ZSORCE = ZR + jZX` on its machine base,
586/// as the static case states it (PSS/E defaults `0 + j1` when absent); `None`
587/// when the network has no such generator.
588#[must_use]
589pub fn generator_source_impedance(net: &BalancedNetwork, generator: usize) -> Option<(f64, f64)> {
590    let g = net.generators().get(generator)?;
591    let read = |key: &str, default: f64| {
592        detailed_source_property(net, "generator", g.uid.as_deref(), key)
593            .and_then(|v| v.trim().parse::<f64>().ok())
594            .filter(|v| v.is_finite())
595            .unwrap_or(default)
596    };
597    Some((read("psse_zr", 0.0), read("psse_zx", 1.0)))
598}
599
600/// One typed model and the DYR line it came from.
601#[derive(Clone, Debug, PartialEq)]
602#[non_exhaustive]
603pub struct LinkedModel {
604    pub model: DynamicModel,
605    pub line: usize,
606}
607
608/// The dynamic models attached to one generator of the static case.
609#[derive(Clone, Debug, PartialEq)]
610#[non_exhaustive]
611pub struct MachineDynamics {
612    /// Index into [`BalancedNetwork::generators`].
613    pub generator: usize,
614    pub bus: BusId,
615    /// The generator's PSS/E machine id, trimmed (see [`psse_machine_ids`]).
616    pub machine_id: String,
617    /// Machine base in MVA.
618    pub mbase: f64,
619    /// `ZSORCE` on the machine base.
620    pub zsource: (f64, f64),
621    pub machine: Option<LinkedModel>,
622    pub exciter: Option<LinkedModel>,
623    pub governor: Option<LinkedModel>,
624    pub stabilizer: Option<LinkedModel>,
625}
626
627/// Model names without a typed view that PSS/E attaches to a generator by
628/// `(bus, machine id)`: machines, exciters, governors, stabilizers, limiters,
629/// compensators and the renewable generator, electrical and plant controls.
630/// A record of one of these names an existing unit even though it is not
631/// linked; any other untyped record (load, dc line, relay, user model, ...)
632/// may key something else.
633#[rustfmt::skip]
634const GENERATOR_ATTACHED: &[&str] = &[
635    // Machines.
636    "GENTPJ", "GENTPF", "GENQEC", "GENDCO", "GENTRA", "CIMTR1", "CIMTR3",
637    // Exciters.
638    "IEEET1", "IEEET2", "IEEET3", "IEEET4", "IEEET5", "IEEEX1", "IEEEX2", "IEEEX3", "IEEEX4",
639    "EXAC1", "EXAC1A", "EXAC2", "EXAC3", "EXAC4", "EXDC2", "EXELI", "EXPIC1", "EXST2",
640    "EXST2A", "EXST3", "ESAC2A", "ESAC3A", "ESAC4A", "ESAC5A", "ESAC6A", "ESAC7B", "ESAC8B",
641    "ESDC1A", "ESDC2A", "ESDC3A", "ESDC4B", "ESST1A", "ESST2A", "ESST3A", "ESST4B", "ESST5B",
642    "ESST6B", "ESST7B", "SCRX", "REXS", "URST5T",
643    // Governors.
644    "IEEEG1", "IEEEG2", "IEEEG3", "IEESGO", "GGOV1", "TGOV2", "TGOV3", "TGOV5", "HYGOV2",
645    "HYGOV4", "WEHGOV", "WSIEG1", "PIDGOV", "GAST2A", "GASTWD", "DEGOV", "DEGOV1", "CRCMGV",
646    // Stabilizers.
647    "STAB1", "STAB2A", "STAB3", "STAB4", "PSS1A", "PSS2A", "PSS2B", "PSS2C", "PSS3B", "PSS4B",
648    "IEE2ST", "ST2CUT",
649    // Limiters and compensators.
650    "MAXEX1", "MAXEX2", "MNLEX1", "MNLEX2", "MNLEX3", "UEL1", "UEL2", "OEL1B", "COMP", "IEEEVC",
651];
652
653/// Name prefixes of generator-attached model families without a typed view:
654/// the WECC renewable generator/converter, electrical and plant controllers,
655/// and the generic wind models.
656const GENERATOR_ATTACHED_PREFIXES: &[&str] = &["REGC", "REEC", "REPC", "WT1", "WT2", "WT3", "WT4"];
657
658/// Whether a record of this model names a generator: every supported model
659/// does, and so do the known generator-attached models without a typed view.
660fn names_a_generator(error: &ModelError) -> bool {
661    match error {
662        ModelError::Unsupported { model_name } => {
663            GENERATOR_ATTACHED.contains(&model_name.as_str())
664                || GENERATOR_ATTACHED_PREFIXES
665                    .iter()
666                    .any(|prefix| model_name.starts_with(prefix))
667        }
668        _ => true,
669    }
670}
671
672/// A DYR record that did not attach to a generator as a typed model, or
673/// replaced one that had.
674#[derive(Clone, Debug, PartialEq, Eq)]
675#[non_exhaustive]
676pub enum LinkIssue {
677    /// The record has no typed view; it is kept raw and not linked. `bus` and
678    /// `machine_id` are the generator it names when the model is known to
679    /// attach to one (a supported model that failed its schema, or a
680    /// generator-attached model without a typed view, whose role on that
681    /// unit stays empty); `None` for any other record, whose keys may name a
682    /// load, a dc line or another device.
683    Untyped {
684        line: usize,
685        bus: Option<BusId>,
686        machine_id: Option<String>,
687        error: ModelError,
688    },
689    /// No generator of the static case has this `(bus, id)`.
690    NoGenerator {
691        line: usize,
692        model_name: String,
693        bus: BusId,
694        machine_id: String,
695    },
696    /// The generator exists but is out of service; its records are kept and
697    /// not linked.
698    OutOfService {
699        line: usize,
700        model_name: String,
701        bus: BusId,
702        machine_id: String,
703    },
704    /// No generator on the bus has this id exactly, and several match it
705    /// ignoring ASCII case; the record is not linked.
706    AmbiguousMachineId {
707        line: usize,
708        model_name: String,
709        bus: BusId,
710        machine_id: String,
711        /// The ids of the generators that match, in network order.
712        candidates: Vec<String>,
713    },
714    /// A later record of the same role for one generator replaced the
715    /// earlier one, as PSS/E does when it reads the DYR file. The record at
716    /// `line` is linked; the one at `replaced_line` is not.
717    Replaced {
718        line: usize,
719        replaced_line: usize,
720        bus: BusId,
721        /// The generator's machine id.
722        machine_id: String,
723        /// The model of the record at `line`.
724        model_name: String,
725        role: ModelRole,
726    },
727}
728
729impl fmt::Display for LinkIssue {
730    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
731        match self {
732            Self::Untyped {
733                line,
734                bus,
735                machine_id,
736                error,
737            } => match (bus, machine_id) {
738                (Some(bus), Some(id)) => {
739                    write!(f, "line {line}: {error} (generator ({bus}, '{id}'))")
740                }
741                _ => write!(f, "line {line}: record not linked: {error}"),
742            },
743            Self::NoGenerator {
744                line,
745                model_name,
746                bus,
747                machine_id,
748            } => write!(
749                f,
750                "line {line}: {model_name} names generator ({bus}, '{machine_id}'), which the static case does not hold"
751            ),
752            Self::OutOfService {
753                line,
754                model_name,
755                bus,
756                machine_id,
757            } => write!(
758                f,
759                "line {line}: {model_name} names generator ({bus}, '{machine_id}'), which is out of service"
760            ),
761            Self::AmbiguousMachineId {
762                line,
763                model_name,
764                bus,
765                machine_id,
766                candidates,
767            } => write!(
768                f,
769                "line {line}: {model_name} names generator ({bus}, '{machine_id}'), which matches ids {candidates:?} on that bus only ignoring case"
770            ),
771            Self::Replaced {
772                line,
773                replaced_line,
774                bus,
775                machine_id,
776                model_name,
777                role,
778            } => write!(
779                f,
780                "line {line}: {model_name} replaces the {role:?} model of line {replaced_line} for generator ({bus}, '{machine_id}')"
781            ),
782        }
783    }
784}
785
786/// The result of linking a [`DynamicCase`] to a network's generators.
787#[derive(Clone, Debug, PartialEq)]
788#[non_exhaustive]
789pub struct MachineLinking {
790    /// One entry per in-service generator, in network order, with or without
791    /// dynamic models.
792    pub machines: Vec<MachineDynamics>,
793    /// In record order.
794    pub issues: Vec<LinkIssue>,
795}
796
797/// One generator on a bus: its trimmed machine id, and its slot in
798/// [`MachineLinking::machines`] (`None` when out of service).
799type BusGenerators = Vec<(String, Option<usize>)>;
800
801/// The generator a record names on its bus: the exact id, else the one
802/// generator whose id matches ignoring ASCII case. `Err` holds the candidate
803/// ids when several do.
804fn find_generator<'a>(
805    on_bus: &'a [(String, Option<usize>)],
806    machine_id: &str,
807) -> Result<Option<&'a (String, Option<usize>)>, Vec<String>> {
808    if let Some(exact) = on_bus.iter().find(|(id, _)| id == machine_id) {
809        return Ok(Some(exact));
810    }
811    let folded: Vec<_> = on_bus
812        .iter()
813        .filter(|(id, _)| id.eq_ignore_ascii_case(machine_id))
814        .collect();
815    match folded.as_slice() {
816        [] => Ok(None),
817        [one] => Ok(Some(one)),
818        many => Err(many.iter().map(|(id, _)| id.clone()).collect()),
819    }
820}
821
822/// Attach the typed DYR models to the generators they name by
823/// `(bus, machine id)`.
824///
825/// The machine id matches exactly; when no generator on the bus has it, the
826/// one generator whose id matches ignoring ASCII case is used. When several
827/// records of one role name the same generator, the last one wins and each
828/// replacement is reported as [`LinkIssue::Replaced`], as PSS/E replaces a
829/// model of the same category when it reads a DYR file.
830#[must_use]
831pub fn link_machines(net: &BalancedNetwork, dynamics: &DynamicCase) -> MachineLinking {
832    let ids = psse_machine_ids(net);
833    let mut machines: Vec<MachineDynamics> = Vec::new();
834    let mut by_bus: BTreeMap<BusId, BusGenerators> = BTreeMap::new();
835    for (index, (g, id)) in net.generators().iter().zip(&ids).enumerate() {
836        let slot = g.in_service.then_some(machines.len());
837        by_bus.entry(g.bus).or_default().push((id.clone(), slot));
838        if !g.in_service {
839            continue;
840        }
841        machines.push(MachineDynamics {
842            generator: index,
843            bus: g.bus,
844            machine_id: id.clone(),
845            mbase: g.mbase,
846            zsource: generator_source_impedance(net, index).unwrap_or((0.0, 1.0)),
847            machine: None,
848            exciter: None,
849            governor: None,
850            stabilizer: None,
851        });
852    }
853    let mut issues = Vec::new();
854    for record in dynamics.records() {
855        let line = record.line();
856        let machine_id = record.device_id().unwrap_or("1").trim().to_owned();
857        let model = match typed_model(record) {
858            Ok(model) => model,
859            Err(error) => {
860                let named = record
861                    .bus_id()
862                    .filter(|_| names_a_generator(&error))
863                    .map(|bus| BusId(bus as usize));
864                issues.push(LinkIssue::Untyped {
865                    line,
866                    bus: named,
867                    machine_id: named.map(|_| machine_id),
868                    error,
869                });
870                continue;
871            }
872        };
873        let model_name = model.name().to_owned();
874        let bus = BusId(record.bus_id().unwrap_or(0) as usize);
875        let on_bus = by_bus.get(&bus).map_or(&[][..], Vec::as_slice);
876        let slot = match find_generator(on_bus, &machine_id) {
877            Ok(Some((_, Some(slot)))) => *slot,
878            Ok(Some((_, None))) => {
879                issues.push(LinkIssue::OutOfService {
880                    line,
881                    model_name,
882                    bus,
883                    machine_id,
884                });
885                continue;
886            }
887            Ok(None) => {
888                issues.push(LinkIssue::NoGenerator {
889                    line,
890                    model_name,
891                    bus,
892                    machine_id,
893                });
894                continue;
895            }
896            Err(candidates) => {
897                issues.push(LinkIssue::AmbiguousMachineId {
898                    line,
899                    model_name,
900                    bus,
901                    machine_id,
902                    candidates,
903                });
904                continue;
905            }
906        };
907        let entry = &mut machines[slot];
908        let role = model.role();
909        let target = match role {
910            ModelRole::Machine => &mut entry.machine,
911            ModelRole::Exciter => &mut entry.exciter,
912            ModelRole::Governor => &mut entry.governor,
913            ModelRole::Stabilizer => &mut entry.stabilizer,
914        };
915        if let Some(replaced) = target.replace(LinkedModel { model, line }) {
916            issues.push(LinkIssue::Replaced {
917                line,
918                replaced_line: replaced.line,
919                bus: entry.bus,
920                machine_id: entry.machine_id.clone(),
921                model_name,
922                role,
923            });
924        }
925    }
926    MachineLinking { machines, issues }
927}
928
929#[cfg(test)]
930mod tests {
931    use super::*;
932    use crate::dynamic::parse_dyr;
933
934    const DYR: &str = "    101 'GENCLS' 1     0.0000       0.0000      /
935    102 'GENROU' 1     8.0000      0.30000E-01  0.40000      0.50000E-01
936          6.1750      0.50000E-01   1.8000       1.7000      0.30000
937         0.55000      0.25000      0.20000      0.10000      0.80000      /
938    102 'SEXS' 1    0.4    5.0      20.0     1.0     -50.0       50.0 /
939    102 'IEEEST' 1  1  0  0  0  0  0  0  0.0  0  0  0  0.02  1.65  1.65  100  0.1  -0.1  0  0 /
940    102 'USRMDL' 1 'X' 1 2 /
941";
942
943    #[test]
944    fn reads_psse_schemas() {
945        let case = parse_dyr(DYR).unwrap();
946        let models: Vec<_> = case.records().iter().map(typed_model).collect();
947        assert_eq!(
948            models[0],
949            Ok(DynamicModel::Gencls(Gencls { h: 0.0, d: 0.0 }))
950        );
951        let Ok(DynamicModel::Genrou(g)) = &models[1] else {
952            panic!("GENROU not typed: {:?}", models[1]);
953        };
954        assert!((g.td0_p - 8.0).abs() < 1e-12 && (g.h - 6.175).abs() < 1e-12);
955        assert!((g.xl - 0.2).abs() < 1e-12 && (g.s12 - 0.8).abs() < 1e-12);
956        let Ok(DynamicModel::Sexs(s)) = &models[2] else {
957            panic!("SEXS not typed");
958        };
959        assert!((s.k - 20.0).abs() < 1e-12 && (s.emax - 50.0).abs() < 1e-12);
960        let Ok(DynamicModel::Ieeest(p)) = &models[3] else {
961            panic!("IEEEST not typed");
962        };
963        assert_eq!(p.input_code, 1);
964        assert!((p.ks - 100.0).abs() < 1e-12 && (p.lsmin + 0.1).abs() < 1e-12);
965        assert!(matches!(models[4], Err(ModelError::Unsupported { .. })));
966    }
967
968    #[test]
969    fn arity_is_checked() {
970        let case = parse_dyr("1 'SEXS' 1 0.1 10 /").unwrap();
971        assert_eq!(
972            typed_model(&case.records()[0]),
973            Err(ModelError::Arity {
974                model_name: "SEXS".into(),
975                expected: 6,
976                found: 2
977            })
978        );
979    }
980
981    /// Every schema: a record with parameters 1, 2, ... lands field by field
982    /// in PSS/E Model Library order.
983    #[test]
984    fn every_schema_reads_in_record_order() {
985        for (name, arity) in SUPPORTED_MODELS {
986            let params: Vec<String> = (1..=*arity).map(|i| i.to_string()).collect();
987            let text = format!("7 '{name}' 1 {} /", params.join(" "));
988            let case = parse_dyr(&text).unwrap();
989            let model = typed_model(&case.records()[0]).unwrap_or_else(|e| panic!("{name}: {e}"));
990            assert_eq!(model.name(), *name);
991            let fields: Vec<f64> = match model {
992                DynamicModel::Gencls(m) => vec![m.h, m.d],
993                DynamicModel::Genrou(m) | DynamicModel::Genroe(m) => vec![
994                    m.td0_p, m.td0_pp, m.tq0_p, m.tq0_pp, m.h, m.d, m.xd, m.xq, m.xd_p, m.xq_p,
995                    m.xd_pp, m.xl, m.s1, m.s12,
996                ],
997                DynamicModel::Gensal(m) | DynamicModel::Gensae(m) => vec![
998                    m.td0_p, m.td0_pp, m.tq0_pp, m.h, m.d, m.xd, m.xq, m.xd_p, m.xd_pp, m.xl, m.s1,
999                    m.s12,
1000                ],
1001                DynamicModel::Sexs(m) => vec![m.ta_tb, m.tb, m.k, m.te, m.emin, m.emax],
1002                DynamicModel::Esac1a(m) => vec![
1003                    m.tr, m.tb, m.tc, m.ka, m.ta, m.vamax, m.vamin, m.te, m.kf, m.tf, m.kc, m.kd,
1004                    m.ke, m.e1, m.se_e1, m.e2, m.se_e2, m.vrmax, m.vrmin,
1005                ],
1006                DynamicModel::Exst1(m) => vec![
1007                    m.tr, m.vimax, m.vimin, m.tc, m.tb, m.ka, m.ta, m.vrmax, m.vrmin, m.kc, m.kf,
1008                    m.tf,
1009                ],
1010                DynamicModel::Tgov1(m) => vec![m.r, m.t1, m.vmax, m.vmin, m.t2, m.t3, m.dt],
1011                DynamicModel::Gast(m) => {
1012                    vec![m.r, m.t1, m.t2, m.t3, m.at, m.kt, m.vmax, m.vmin, m.dturb]
1013                }
1014                DynamicModel::Hygov(m) => vec![
1015                    m.r, m.r_temp, m.tr, m.tf, m.tg, m.velm, m.gmax, m.gmin, m.tw, m.at, m.dturb,
1016                    m.qnl,
1017                ],
1018                DynamicModel::Ieeest(m) => vec![
1019                    f64::from(m.input_code),
1020                    m.remote_bus.map_or(0.0, |b| b.0 as f64),
1021                    m.a1,
1022                    m.a2,
1023                    m.a3,
1024                    m.a4,
1025                    m.a5,
1026                    m.a6,
1027                    m.t1,
1028                    m.t2,
1029                    m.t3,
1030                    m.t4,
1031                    m.t5,
1032                    m.t6,
1033                    m.ks,
1034                    m.lsmax,
1035                    m.lsmin,
1036                    m.vcu,
1037                    m.vcl,
1038                ],
1039            };
1040            let expected: Vec<f64> = (1..=*arity).map(|i| i as f64).collect();
1041            assert_eq!(fields, expected, "{name}");
1042        }
1043    }
1044
1045    #[test]
1046    fn a_token_that_is_not_a_number_is_named() {
1047        let case = parse_dyr("1 'SEXS' 1 0.1 10 x 0.1 0 3 /").unwrap();
1048        assert_eq!(
1049            typed_model(&case.records()[0]),
1050            Err(ModelError::NotANumber {
1051                model_name: "SEXS".into(),
1052                index: 2,
1053                token: "x".into()
1054            })
1055        );
1056    }
1057
1058    fn ieeest(ics: &str, ib: &str) -> Result<DynamicModel, ModelError> {
1059        let text =
1060            format!("1 'IEEEST' 1 {ics} {ib} 0 0 0 0 0 0 0 0 0 0.02 1.65 1.65 100 0.1 -0.1 0 0 /");
1061        typed_model(&parse_dyr(&text).unwrap().records()[0])
1062    }
1063
1064    #[test]
1065    fn ieeest_icons_are_integers_in_range() {
1066        let Ok(DynamicModel::Ieeest(p)) = ieeest("2", "0") else {
1067            panic!("IEEEST not typed");
1068        };
1069        assert_eq!((p.input_code, p.remote_bus), (2, None));
1070        // An exactly integral float is an integer code.
1071        let Ok(DynamicModel::Ieeest(p)) = ieeest("6.0", "4294967295") else {
1072            panic!("IEEEST not typed");
1073        };
1074        assert_eq!(
1075            (p.input_code, p.remote_bus),
1076            (6, Some(BusId(4_294_967_295)))
1077        );
1078        let Ok(DynamicModel::Ieeest(p)) = ieeest("1", "1.0D2") else {
1079            panic!("IEEEST not typed");
1080        };
1081        assert_eq!(p.remote_bus, Some(BusId(100)));
1082        let invalid = |index: usize, token: &str| {
1083            Err(ModelError::InvalidIcon {
1084                model_name: "IEEEST".into(),
1085                index,
1086                token: token.into(),
1087            })
1088        };
1089        assert_eq!(ieeest("1.5", "0"), invalid(0, "1.5"));
1090        assert_eq!(ieeest("0", "0"), invalid(0, "0"));
1091        assert_eq!(ieeest("7", "0"), invalid(0, "7"));
1092        assert_eq!(ieeest("1", "-1"), invalid(1, "-1"));
1093        assert_eq!(ieeest("1", "4294967296"), invalid(1, "4294967296"));
1094        assert_eq!(ieeest("1", "2.5"), invalid(1, "2.5"));
1095        // A token that is no number at all stays NotANumber.
1096        assert!(matches!(
1097            ieeest("x", "0"),
1098            Err(ModelError::NotANumber { index: 0, .. })
1099        ));
1100        assert_eq!(
1101            invalid(0, "7").unwrap_err().to_string(),
1102            "IEEEST parameter 1 (\"7\") is not a valid integer code"
1103        );
1104    }
1105
1106    #[test]
1107    fn fortran_d_exponents_are_numbers() {
1108        let case = parse_dyr("1 'SEXS' 1 1.0D-1 1.0d1 2.0D+1 0.1 -5.0D0 5D0 /").unwrap();
1109        let Ok(DynamicModel::Sexs(s)) = typed_model(&case.records()[0]) else {
1110            panic!("SEXS not typed");
1111        };
1112        let read = [s.ta_tb, s.tb, s.k, s.te, s.emin, s.emax];
1113        let expected = [0.1, 10.0, 20.0, 0.1, -5.0, 5.0];
1114        assert!(
1115            read.iter()
1116                .zip(expected)
1117                .all(|(a, b)| (a - b).abs() < 1e-12),
1118            "{read:?}"
1119        );
1120        // Errors keep the source token; a second D, or an overflow, is refused.
1121        for bad in ["1.0D0D0", "1D999", "D"] {
1122            let text = format!("1 'SEXS' 1 0.1 10 {bad} 0.1 0 3 /");
1123            let case = parse_dyr(&text).unwrap();
1124            assert_eq!(
1125                typed_model(&case.records()[0]),
1126                Err(ModelError::NotANumber {
1127                    model_name: "SEXS".into(),
1128                    index: 2,
1129                    token: bad.into()
1130                }),
1131                "{bad}"
1132            );
1133        }
1134    }
1135
1136    /// Buses 101 to 104; bus 102 holds 'G2', '1' and the out-of-service
1137    /// 'OS', bus 103 'ab' and 'AB', bus 104 'C' and 'Gt'.
1138    fn network() -> BalancedNetwork {
1139        use std::fmt::Write as _;
1140        let generator = |bus: u32, id: &str, status: u8| {
1141            format!(
1142                "{bus},'{id}', 10.0, 0.0, 100.0, -100.0, 1.0, 0, 200.0, 1.0E-3, 0.3, 0.0, 0.0, 1.0, {status}, 100.0, 100.0, 0.0, 1, 1.0\n"
1143            )
1144        };
1145        let mut raw = String::from("0, 100.00, 33, 0, 0, 60.00 / test\nfirst\nsecond\n");
1146        for bus in 101..=104 {
1147            let kind = if bus == 101 { 3 } else { 2 };
1148            writeln!(raw, "{bus},'B{bus}', 230.0, {kind}, 1, 1, 1, 1.0, 0.0").unwrap();
1149        }
1150        raw += "0 / End of Bus data\n0 / End of Load data\n0 / End of Fixed shunt data\n";
1151        for (bus, id, status) in [
1152            (101, "1", 1),
1153            (102, "G2", 1),
1154            (102, "1", 1),
1155            (102, "OS", 0),
1156            (103, "ab", 1),
1157            (103, "AB", 1),
1158            (104, "C", 1),
1159            (104, "Gt", 1),
1160        ] {
1161            raw += &generator(bus, id, status);
1162        }
1163        raw += "0 / End of Generator data\n";
1164        for to in 102..=104 {
1165            writeln!(raw, "101, {to},'1', 0.0, 0.1, 0.0, 100.0, 100.0, 100.0, 0.0, 0.0, 0.0, 0.0, 1, 1, 0.0, 1, 1.0").unwrap();
1166        }
1167        raw += "0 / End of Branch data\n0 / End of Transformer data\nQ\n";
1168        crate::format::psse::parse_psse_source(
1169            &raw,
1170            None,
1171            &mut crate::diagnostics::Diagnostics::default(),
1172        )
1173        .unwrap()
1174    }
1175
1176    fn link(dyr: &str) -> MachineLinking {
1177        link_machines(&network(), &parse_dyr(dyr).unwrap())
1178    }
1179
1180    fn unit<'a>(linking: &'a MachineLinking, bus: usize, id: &str) -> &'a MachineDynamics {
1181        linking
1182            .machines
1183            .iter()
1184            .find(|m| m.bus == BusId(bus) && m.machine_id == id)
1185            .unwrap_or_else(|| panic!("no unit ({bus}, {id})"))
1186    }
1187
1188    #[test]
1189    fn machines_carry_static_bus_ids() {
1190        let net = network();
1191        assert_eq!(
1192            psse_machine_ids(&net),
1193            ["1", "G2", "1", "OS", "ab", "AB", "C", "Gt"]
1194        );
1195        let linking = link("");
1196        assert_eq!(linking.machines.len(), 7);
1197        let g2 = unit(&linking, 102, "G2");
1198        assert_eq!((g2.generator, g2.bus, g2.mbase), (1, BusId(102), 200.0));
1199        assert_eq!(linking.issues, []);
1200    }
1201
1202    /// PSS/E replaces an earlier model of the same category for one machine
1203    /// with a later one; so does the linking, and it says so.
1204    #[test]
1205    fn a_later_record_of_one_role_replaces_the_earlier() {
1206        let linking = link(
1207            "102 'GENROU' 1 8 0.03 0.4 0.05 6 0 1.8 1.7 0.3 0.55 0.25 0.2 0.1 0.8 /
1208102 'SEXS' 1 0.1 10 100 0.1 0 4 /
1209102 'GENCLS' 1 5.0 1.0 /
1210102 'SEXS' '1 ' 0.2 10 100 0.1 0 4 /
1211",
1212        );
1213        let g = unit(&linking, 102, "1");
1214        assert!(matches!(
1215            g.machine,
1216            Some(LinkedModel {
1217                model: DynamicModel::Gencls(_),
1218                line: 3
1219            })
1220        ));
1221        assert!(matches!(
1222            &g.exciter,
1223            Some(LinkedModel { model: DynamicModel::Sexs(s), line: 4 }) if (s.ta_tb - 0.2).abs() < 1e-12
1224        ));
1225        assert_eq!(
1226            linking.issues,
1227            [
1228                LinkIssue::Replaced {
1229                    line: 3,
1230                    replaced_line: 1,
1231                    bus: BusId(102),
1232                    machine_id: "1".into(),
1233                    model_name: "GENCLS".into(),
1234                    role: ModelRole::Machine,
1235                },
1236                LinkIssue::Replaced {
1237                    line: 4,
1238                    replaced_line: 2,
1239                    bus: BusId(102),
1240                    machine_id: "1".into(),
1241                    model_name: "SEXS".into(),
1242                    role: ModelRole::Exciter,
1243                },
1244            ]
1245        );
1246        assert_eq!(
1247            linking.issues[0].to_string(),
1248            "line 3: GENCLS replaces the Machine model of line 1 for generator (102, '1')"
1249        );
1250    }
1251
1252    /// Unquoted alphabetic ids, as WECC 240 writes them, and ids that differ
1253    /// from the static case only in ASCII case.
1254    #[test]
1255    fn machine_ids_match_exactly_then_ignoring_case() {
1256        let linking = link(
1257            "104 'GENCLS' C 3.0 0.0 /
1258104 'GENCLS' GT 4.0 0.0 /
1259104 'SEXS' gt 0.1 10 100 0.1 0 4 /
1260103 'GENCLS' ab 1.0 0.0 /
1261103 'GENCLS' AB 2.0 0.0 /
1262103 'GENCLS' Ab 9.0 0.0 /
1263102 'GENCLS' os 1.0 0.0 /
1264102 'GENCLS' G 1.0 0.0 /
1265",
1266        );
1267        let h = |bus, id| match &unit(&linking, bus, id).machine {
1268            Some(LinkedModel {
1269                model: DynamicModel::Gencls(g),
1270                ..
1271            }) => g.h,
1272            other => panic!("({bus}, {id}): {other:?}"),
1273        };
1274        assert!((h(104, "C") - 3.0).abs() < 1e-12);
1275        // 'GT' is no id on bus 104; the one id equal ignoring case is 'Gt'.
1276        assert!((h(104, "Gt") - 4.0).abs() < 1e-12);
1277        assert!(unit(&linking, 104, "Gt").exciter.is_some());
1278        // Exact matches win over the case-folded ones.
1279        assert!((h(103, "ab") - 1.0).abs() < 1e-12);
1280        assert!((h(103, "AB") - 2.0).abs() < 1e-12);
1281        assert_eq!(
1282            linking.issues,
1283            [
1284                LinkIssue::AmbiguousMachineId {
1285                    line: 6,
1286                    model_name: "GENCLS".into(),
1287                    bus: BusId(103),
1288                    machine_id: "Ab".into(),
1289                    candidates: vec!["ab".into(), "AB".into()],
1290                },
1291                LinkIssue::OutOfService {
1292                    line: 7,
1293                    model_name: "GENCLS".into(),
1294                    bus: BusId(102),
1295                    machine_id: "os".into(),
1296                },
1297                LinkIssue::NoGenerator {
1298                    line: 8,
1299                    model_name: "GENCLS".into(),
1300                    bus: BusId(102),
1301                    machine_id: "G".into(),
1302                },
1303            ]
1304        );
1305        // The stored ids are never folded.
1306        assert_eq!(unit(&linking, 104, "Gt").machine_id, "Gt");
1307    }
1308
1309    /// An untyped record names a generator only when its model is known to
1310    /// attach to one.
1311    #[test]
1312    fn untyped_records_name_a_generator_only_for_generator_models() {
1313        let linking = link(
1314            "102 'IEEET1' 1 0 400 0.04 7.3 -7.3 1 0.8 0 0.03 1 0 0 0 0 /
1315102 'REECA1' 'G2' 1 2 /
1316102 'SEXS' 1 0.1 10 /
1317102 'CLODBL' 1 1 2 /
13182 'LDS3BL' * 1 2 /
1319'DC1' 'CDC4T' 1 2 /
1320102 'USRMDL' 1 'X' 1 2 /
1321",
1322        );
1323        let named: Vec<_> = linking
1324            .issues
1325            .iter()
1326            .map(|issue| match issue {
1327                LinkIssue::Untyped {
1328                    bus, machine_id, ..
1329                } => (*bus, machine_id.clone()),
1330                other => panic!("{other:?}"),
1331            })
1332            .collect();
1333        let generator = |id: &str| (Some(BusId(102)), Some(id.to_owned()));
1334        assert_eq!(
1335            named,
1336            [
1337                generator("1"),
1338                generator("G2"),
1339                generator("1"),
1340                (None, None),
1341                (None, None),
1342                (None, None),
1343                (None, None),
1344            ]
1345        );
1346        assert_eq!(
1347            linking.issues[0].to_string(),
1348            "line 1: model IEEET1 has no typed view (generator (102, '1'))"
1349        );
1350        assert_eq!(
1351            linking.issues[3].to_string(),
1352            "line 4: record not linked: model CLODBL has no typed view"
1353        );
1354    }
1355}