ph-curves 0.3.0

no-std, no-alloc Rust for embedded: curve lookup tables, ADC-to-measurement transfer functions with inverse and calibration, temporal filters, and tickless scheduling
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
//! Programmatic transfer sources for host tools that own evaluation.

// Host-only: module-local std link (crate root stays `#![no_std]`).
extern crate std;

use std::collections::BTreeMap;
use std::prelude::v1::*;

use super::family::{
    FamilyGapDef, FamilyMemberDef, SelectorValue, TransferFamilyDef, default_family_max_knots,
};
use super::model::{DividerTopology, MODEL_INPUT_SCALE_DENOMINATOR, ModelDef};
use super::{
    BoundaryDef, GenerationPolicy, ObservationGuardDef, PhysicalPoint, SourceProvenance,
    TransferDef, default_boundary,
};

fn default_max_knots() -> usize {
    256
}

/// Dense unscaled physical samples over a contiguous `u16` observation domain.
///
/// `physical[i]` is the value at `domain_min + i`. Host tools evaluate their
/// own model into this series; ph-curves scales, fits, and emits the table.
#[derive(Clone, Debug)]
pub struct EvaluatedTruth {
    domain_min: u16,
    physical: Vec<f64>,
}

impl EvaluatedTruth {
    /// Samples covering `domain_min` through `domain_min + physical.len() - 1`.
    pub fn new(domain_min: u16, physical: Vec<f64>) -> Self {
        Self {
            domain_min,
            physical,
        }
    }

    /// First observation code in the series.
    pub fn domain_min(&self) -> u16 {
        self.domain_min
    }

    /// Unscaled physical values, one per consecutive input code.
    pub fn physical(&self) -> &[f64] {
        &self.physical
    }
}

/// Generation input that replaces a parsed formula, points table, or model.
///
/// This is not a plugin ABI: the caller evaluates device-owned truth (or
/// chooses knots) and hands the result to the existing fitter and codegen.
#[derive(Clone, Debug)]
pub enum TransferSource {
    /// Dense physical samples; the greedy fitter selects knots.
    EvaluatedTruth(EvaluatedTruth),
    /// Caller-chosen knots. The greedy fitter is skipped.
    ///
    /// Interpolation error is measured against `truth` before metadata is
    /// emitted, so prefitted tables cannot claim an unverified error bound.
    PrefittedKnots {
        /// Strictly increasing observation-domain knot codes.
        inputs: Vec<u16>,
        /// Scaled integer knot outputs (`physical * output_scale`, rounded).
        outputs: Vec<i32>,
        /// Dense unscaled truth covering the knot domain.
        truth: EvaluatedTruth,
    },
    /// Sparse physical control points, matching TOML `points`.
    Points(Vec<PhysicalPoint>),
}

impl TransferSource {
    /// Dense physical samples starting at `domain_min`.
    pub fn evaluated_truth(domain_min: u16, physical: Vec<f64>) -> Self {
        Self::EvaluatedTruth(EvaluatedTruth::new(domain_min, physical))
    }

    /// Prefitted knots verified against dense unscaled truth.
    pub fn prefitted_knots_verified(
        inputs: Vec<u16>,
        outputs: Vec<i32>,
        truth: EvaluatedTruth,
    ) -> Self {
        Self::PrefittedKnots {
            inputs,
            outputs,
            truth,
        }
    }

    /// Sparse physical control points.
    pub fn points(points: Vec<PhysicalPoint>) -> Self {
        Self::Points(points)
    }

    /// Overlay this source while intentionally using the target's declared,
    /// resolved pre-overlay citation.
    ///
    /// Use this only when the new samples are another representation of the
    /// already-cited source. Replacing an earlier overlay with this disposition
    /// restores that declared citation. The explicit choice prevents a
    /// standalone source replacement from silently retaining an unrelated
    /// citation.
    pub fn inherit_provenance(self) -> TransferSourceOverlay {
        TransferSourceOverlay::new(self, SourceProvenanceDisposition::Inherit)
    }

    /// Overlay this source and replace the target citation.
    ///
    /// A declared observation-guard citation remains resolved against the
    /// target's pre-overlay citation; replacing the generation source does not
    /// silently re-parent the guard classification.
    pub fn with_provenance(self, provenance: SourceProvenance) -> TransferSourceOverlay {
        TransferSourceOverlay::new(self, SourceProvenanceDisposition::Replace(provenance))
    }

    /// Overlay this source and remove any target citation.
    ///
    /// A declared observation-guard citation remains resolved against the
    /// target's pre-overlay citation and is not removed with the source
    /// citation.
    ///
    /// Source-backed family members cannot clear their mandatory citation.
    pub fn clear_provenance(self) -> TransferSourceOverlay {
        TransferSourceOverlay::new(self, SourceProvenanceDisposition::Clear)
    }
}

/// What a generation-source overlay does with the target source citation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SourceProvenanceDisposition {
    /// Use the target's declared, resolved pre-overlay citation intentionally.
    ///
    /// This restores that citation when replacing an earlier overlay.
    Inherit,
    /// Replace the target citation with this value.
    Replace(SourceProvenance),
    /// Remove the target citation.
    Clear,
}

/// Generation source plus an explicit citation disposition.
///
/// Construct through [`TransferSource::inherit_provenance`],
/// [`TransferSource::with_provenance`], or
/// [`TransferSource::clear_provenance`].
#[derive(Clone, Debug)]
pub struct TransferSourceOverlay {
    source: TransferSource,
    provenance: SourceProvenanceDisposition,
}

impl TransferSourceOverlay {
    fn new(source: TransferSource, provenance: SourceProvenanceDisposition) -> Self {
        Self { source, provenance }
    }

    /// Replacement formula/points/model representation.
    pub fn source(&self) -> &TransferSource {
        &self.source
    }

    /// Explicit handling of the target citation.
    pub fn provenance_disposition(&self) -> &SourceProvenanceDisposition {
        &self.provenance
    }

    pub(crate) fn effective_def(&self, def: &TransferDef) -> Result<TransferDef, String> {
        let mut effective = def.clone();
        match &self.provenance {
            SourceProvenanceDisposition::Inherit => {}
            SourceProvenanceDisposition::Replace(provenance) => {
                provenance.validate()?;
                effective.provenance = Some(provenance.clone());
            }
            SourceProvenanceDisposition::Clear => effective.provenance = None,
        }
        Ok(effective)
    }
}

/// A standalone transfer constructed without TOML.
///
/// Fit policy (`max_interpolation_error`, `max_knots`, boundaries) lives here,
/// independent of dense curve LUT options.
#[derive(Clone, Debug)]
pub struct TransferSpec {
    name: String,
    input_unit: String,
    output_unit: String,
    output_scale: u32,
    max_interpolation_error: u32,
    max_knots: usize,
    below: BoundaryDef,
    above: BoundaryDef,
    observation_guard: Option<ObservationGuardDef>,
    provenance: Option<SourceProvenance>,
    source: TransferSource,
}

impl TransferSpec {
    /// Policy defaults: `max_knots = 256`, `below`/`above` = error.
    pub fn new(
        name: impl Into<String>,
        input_unit: impl Into<String>,
        output_unit: impl Into<String>,
        output_scale: u32,
        max_interpolation_error: u32,
        source: TransferSource,
    ) -> Self {
        Self {
            name: name.into(),
            input_unit: input_unit.into(),
            output_unit: output_unit.into(),
            output_scale,
            max_interpolation_error,
            max_knots: default_max_knots(),
            below: default_boundary(),
            above: default_boundary(),
            observation_guard: None,
            provenance: None,
            source,
        }
    }

    /// Knot budget for the greedy fitter (ignored for prefitted knots except
    /// as an upper bound on the supplied table).
    pub fn with_max_knots(mut self, max_knots: usize) -> Self {
        self.max_knots = max_knots;
        self
    }

    /// Observation-domain below/above policies.
    pub fn with_boundaries(mut self, below: BoundaryDef, above: BoundaryDef) -> Self {
        self.below = below;
        self.above = above;
        self
    }

    /// Explicit observation-code guard (TOML `saturation`).
    pub fn with_observation_guard(mut self, guard: ObservationGuardDef) -> Self {
        self.observation_guard = Some(guard);
        self
    }

    /// Caller-declared source citation.
    ///
    /// This is equivalent to supplying provenance on a source overlay. The
    /// spec owns both its initial source and citation, so no overlay
    /// disposition is needed at construction time.
    pub fn with_provenance(mut self, provenance: SourceProvenance) -> Self {
        self.provenance = Some(provenance);
        self
    }

    /// TOML-style table name / generated symbol stem.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Observation-domain unit label.
    pub fn input_unit(&self) -> &str {
        &self.input_unit
    }

    /// Physical-domain unit label.
    pub fn output_unit(&self) -> &str {
        &self.output_unit
    }

    /// Integer quanta per physical unit.
    pub fn output_scale(&self) -> u32 {
        self.output_scale
    }

    /// Requested interpolation error bound in output quanta.
    pub fn max_interpolation_error(&self) -> u32 {
        self.max_interpolation_error
    }

    /// Knot budget.
    pub fn max_knots(&self) -> usize {
        self.max_knots
    }

    /// Below-domain policy.
    pub fn below(&self) -> BoundaryDef {
        self.below
    }

    /// Above-domain policy.
    pub fn above(&self) -> BoundaryDef {
        self.above
    }

    /// Explicit observation-code guard, when set.
    pub fn observation_guard(&self) -> Option<&ObservationGuardDef> {
        self.observation_guard.as_ref()
    }

    /// Caller-declared source citation, when set.
    pub fn provenance(&self) -> Option<&SourceProvenance> {
        self.provenance.as_ref()
    }

    /// Fit budget, boundaries, and observation-guard classification.
    pub fn policy(&self) -> GenerationPolicy {
        GenerationPolicy::new(
            self.max_interpolation_error,
            self.max_knots,
            self.below,
            self.above,
            self.observation_guard.as_ref(),
        )
    }

    /// Generation source.
    pub fn source(&self) -> &TransferSource {
        &self.source
    }

    pub(crate) fn into_parts(self) -> (String, TransferDef, TransferSource) {
        let def = TransferDef {
            input_unit: self.input_unit,
            output_unit: self.output_unit,
            output_scale: self.output_scale,
            max_interpolation_error: self.max_interpolation_error,
            max_knots: self.max_knots,
            below: self.below,
            above: self.above,
            observation_guard: self.observation_guard,
            provenance: self.provenance,
            resolved_guard_provenance: None,
            points: None,
            formula: None,
            model: None,
            domain: None,
            output_range: None,
        };
        (self.name, def, self.source)
    }
}

/// Exact shared source for a transfer family.
///
/// Construct this programmatically through the variant helpers, or inspect it
/// after validation through [`crate::gen::ValidatedFamily::source`]. Built-in
/// model parameters remain available here without exposing the crate-private
/// model catalog type.
#[derive(Clone, Debug)]
pub enum FamilySource {
    /// A formula over the observation-domain variable `x`.
    Formula(String),
    /// Sparse physical control points.
    Points(Vec<PhysicalPoint>),
    /// Shared scaled polynomial. Members supply `input_transform`.
    ScaledPolynomial {
        /// Coefficients `[c0, c1, ...]` for `y = c0 + c1*u + ...`.
        coefficients: Vec<f64>,
    },
    /// Shared NTC Beta-divider model. Members supply `applicability.physical`.
    NtcBetaDivider {
        /// Nominal resistance at `nominal_temperature_celsius`.
        nominal_resistance_ohms: f64,
        /// Beta constant in kelvin.
        beta_kelvin: f64,
        /// Nominal temperature in celsius.
        nominal_temperature_celsius: f64,
        /// Fixed divider resistance.
        fixed_resistance_ohms: f64,
        /// Exclusive ADC full-scale code.
        adc_max_code: u16,
        /// Divider wiring.
        topology: DividerTopology,
    },
}

impl PartialEq for FamilySource {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Formula(left), Self::Formula(right)) => left == right,
            (Self::Points(left), Self::Points(right)) => {
                left.len() == right.len()
                    && left.iter().zip(right).all(|(left, right)| {
                        left.input == right.input && left.output == right.output
                    })
            }
            (
                Self::ScaledPolynomial { coefficients: left },
                Self::ScaledPolynomial {
                    coefficients: right,
                },
            ) => left == right,
            (
                Self::NtcBetaDivider {
                    nominal_resistance_ohms: left_nominal_resistance_ohms,
                    beta_kelvin: left_beta_kelvin,
                    nominal_temperature_celsius: left_nominal_temperature_celsius,
                    fixed_resistance_ohms: left_fixed_resistance_ohms,
                    adc_max_code: left_adc_max_code,
                    topology: left_topology,
                },
                Self::NtcBetaDivider {
                    nominal_resistance_ohms: right_nominal_resistance_ohms,
                    beta_kelvin: right_beta_kelvin,
                    nominal_temperature_celsius: right_nominal_temperature_celsius,
                    fixed_resistance_ohms: right_fixed_resistance_ohms,
                    adc_max_code: right_adc_max_code,
                    topology: right_topology,
                },
            ) => {
                left_nominal_resistance_ohms == right_nominal_resistance_ohms
                    && left_beta_kelvin == right_beta_kelvin
                    && left_nominal_temperature_celsius == right_nominal_temperature_celsius
                    && left_fixed_resistance_ohms == right_fixed_resistance_ohms
                    && left_adc_max_code == right_adc_max_code
                    && left_topology == right_topology
            }
            _ => false,
        }
    }
}

impl FamilySource {
    /// Formula over the observation-domain variable `x`.
    pub fn formula(text: impl Into<String>) -> Self {
        Self::Formula(text.into())
    }

    /// Sparse physical control points.
    pub fn points(points: Vec<PhysicalPoint>) -> Self {
        Self::Points(points)
    }

    /// Shared scaled polynomial. Members supply `input_transform`.
    pub fn scaled_polynomial(coefficients: Vec<f64>) -> Self {
        Self::ScaledPolynomial { coefficients }
    }

    /// Shared NTC Beta-divider model.
    pub fn ntc_beta_divider(
        nominal_resistance_ohms: f64,
        beta_kelvin: f64,
        nominal_temperature_celsius: f64,
        fixed_resistance_ohms: f64,
        adc_max_code: u16,
        topology: DividerTopology,
    ) -> Self {
        Self::NtcBetaDivider {
            nominal_resistance_ohms,
            beta_kelvin,
            nominal_temperature_celsius,
            fixed_resistance_ohms,
            adc_max_code,
            topology,
        }
    }

    pub(crate) fn from_family(family: &TransferFamilyDef) -> Option<Self> {
        match (&family.formula, &family.points, &family.model) {
            (Some(formula), None, None) => Some(Self::Formula(formula.clone())),
            (None, Some(points), None) => Some(Self::Points(points.clone())),
            (None, None, Some(ModelDef::ScaledPolynomial { coefficients, .. })) => {
                Some(Self::ScaledPolynomial {
                    coefficients: coefficients.clone(),
                })
            }
            (
                None,
                None,
                Some(ModelDef::NtcBetaDivider {
                    nominal_resistance_ohms,
                    beta_kelvin,
                    nominal_temperature_celsius,
                    fixed_resistance_ohms,
                    adc_max_code,
                    topology,
                }),
            ) => Some(Self::NtcBetaDivider {
                nominal_resistance_ohms: *nominal_resistance_ohms,
                beta_kelvin: *beta_kelvin,
                nominal_temperature_celsius: *nominal_temperature_celsius,
                fixed_resistance_ohms: *fixed_resistance_ohms,
                adc_max_code: *adc_max_code,
                topology: *topology,
            }),
            _ => None,
        }
    }
}

/// A transfer family constructed without TOML.
///
/// Policy defaults match parsed families: `max_knots = 64`, `below`/`above` =
/// error. Provenance is required because a source-backed family must name its
/// document. Exactly one of [`Self::with_selector_axes`] or
/// [`Self::with_expected_selectors`] must be set before validation.
#[derive(Clone, Debug)]
pub struct FamilySpec {
    name: String,
    input_unit: String,
    output_unit: String,
    output_scale: u32,
    max_interpolation_error: u32,
    max_knots: usize,
    max_total_knots: Option<usize>,
    max_table_bytes: Option<usize>,
    below: BoundaryDef,
    above: BoundaryDef,
    observation_guard: Option<ObservationGuardDef>,
    provenance: SourceProvenance,
    source: FamilySource,
    selector_axes: Option<BTreeMap<String, Vec<SelectorValue>>>,
    expected_selectors: Option<Vec<BTreeMap<String, SelectorValue>>>,
    members: Vec<FamilyMemberDef>,
    gaps: Vec<FamilyGapDef>,
}

impl FamilySpec {
    /// Shared source, units, fit bound, and mandatory citation.
    pub fn new(
        name: impl Into<String>,
        input_unit: impl Into<String>,
        output_unit: impl Into<String>,
        output_scale: u32,
        max_interpolation_error: u32,
        source: FamilySource,
        provenance: SourceProvenance,
    ) -> Self {
        Self {
            name: name.into(),
            input_unit: input_unit.into(),
            output_unit: output_unit.into(),
            output_scale,
            max_interpolation_error,
            max_knots: default_family_max_knots(),
            max_total_knots: None,
            max_table_bytes: None,
            below: default_boundary(),
            above: default_boundary(),
            observation_guard: None,
            provenance,
            source,
            selector_axes: None,
            expected_selectors: None,
            members: Vec::new(),
            gaps: Vec::new(),
        }
    }

    /// Per-member knot budget (default 64, hard cap 256).
    pub fn with_max_knots(mut self, max_knots: usize) -> Self {
        self.max_knots = max_knots;
        self
    }

    /// Observation-domain below/above policies.
    pub fn with_boundaries(mut self, below: BoundaryDef, above: BoundaryDef) -> Self {
        self.below = below;
        self.above = above;
        self
    }

    /// Explicit observation-code guard (TOML `saturation`).
    pub fn with_observation_guard(mut self, guard: ObservationGuardDef) -> Self {
        self.observation_guard = Some(guard);
        self
    }

    /// Optional aggregate knot budget across every emitted member.
    pub fn with_max_total_knots(mut self, max_total_knots: usize) -> Self {
        self.max_total_knots = Some(max_total_knots);
        self
    }

    /// Optional aggregate `_INPUTS` + `_OUTPUTS` array-payload budget.
    pub fn with_max_table_bytes(mut self, max_table_bytes: usize) -> Self {
        self.max_table_bytes = Some(max_table_bytes);
        self
    }

    /// Named selector axes whose Cartesian product is the expected universe.
    pub fn with_selector_axes(mut self, axes: BTreeMap<String, Vec<SelectorValue>>) -> Self {
        self.selector_axes = Some(axes);
        self
    }

    /// Explicit expected selector maps for a non-Cartesian family.
    pub fn with_expected_selectors(
        mut self,
        identities: Vec<BTreeMap<String, SelectorValue>>,
    ) -> Self {
        self.expected_selectors = Some(identities);
        self
    }

    /// Explicit selector combinations. Never synthesized.
    pub fn with_members(mut self, members: Vec<FamilyMemberDef>) -> Self {
        self.members = members;
        self
    }

    /// Family-scoped gaps occupying expected selector identities.
    pub fn with_gaps(mut self, gaps: Vec<FamilyGapDef>) -> Self {
        self.gaps = gaps;
        self
    }

    /// Family table name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Observation-domain unit label.
    pub fn input_unit(&self) -> &str {
        &self.input_unit
    }

    /// Physical-domain unit label.
    pub fn output_unit(&self) -> &str {
        &self.output_unit
    }

    /// Integer quanta per physical unit.
    pub fn output_scale(&self) -> u32 {
        self.output_scale
    }

    /// Requested interpolation error bound in output quanta.
    pub fn max_interpolation_error(&self) -> u32 {
        self.max_interpolation_error
    }

    /// Per-member knot budget.
    pub fn max_knots(&self) -> usize {
        self.max_knots
    }

    /// Optional aggregate knot budget.
    pub fn max_total_knots(&self) -> Option<usize> {
        self.max_total_knots
    }

    /// Optional aggregate array-payload budget.
    pub fn max_table_bytes(&self) -> Option<usize> {
        self.max_table_bytes
    }

    /// Below-domain policy.
    pub fn below(&self) -> BoundaryDef {
        self.below
    }

    /// Above-domain policy.
    pub fn above(&self) -> BoundaryDef {
        self.above
    }

    /// Explicit observation-code guard, when set.
    pub fn observation_guard(&self) -> Option<&ObservationGuardDef> {
        self.observation_guard.as_ref()
    }

    /// Mandatory shared source citation.
    pub fn provenance(&self) -> &SourceProvenance {
        &self.provenance
    }

    /// Fit budget, boundaries, and observation-guard classification.
    pub fn policy(&self) -> GenerationPolicy {
        GenerationPolicy::new(
            self.max_interpolation_error,
            self.max_knots,
            self.below,
            self.above,
            self.observation_guard.as_ref(),
        )
    }

    /// Shared family source.
    pub fn source(&self) -> &FamilySource {
        &self.source
    }

    /// Declared members in construction order.
    pub fn members(&self) -> &[FamilyMemberDef] {
        &self.members
    }

    /// Family-scoped gaps in construction order.
    pub fn gaps(&self) -> &[FamilyGapDef] {
        &self.gaps
    }

    pub(crate) fn into_family(self) -> (String, TransferFamilyDef) {
        let (formula, points, model) = match self.source {
            FamilySource::Formula(text) => (Some(text), None, None),
            FamilySource::Points(points) => (None, Some(points), None),
            FamilySource::ScaledPolynomial { coefficients } => (
                None,
                None,
                Some(ModelDef::ScaledPolynomial {
                    coefficients,
                    scale: None,
                    denominator: MODEL_INPUT_SCALE_DENOMINATOR as u32,
                }),
            ),
            FamilySource::NtcBetaDivider {
                nominal_resistance_ohms,
                beta_kelvin,
                nominal_temperature_celsius,
                fixed_resistance_ohms,
                adc_max_code,
                topology,
            } => (
                None,
                None,
                Some(ModelDef::NtcBetaDivider {
                    nominal_resistance_ohms,
                    beta_kelvin,
                    nominal_temperature_celsius,
                    fixed_resistance_ohms,
                    adc_max_code,
                    topology,
                }),
            ),
        };
        let family = TransferFamilyDef {
            input_unit: self.input_unit,
            output_unit: self.output_unit,
            output_scale: self.output_scale,
            max_interpolation_error: self.max_interpolation_error,
            max_knots: self.max_knots,
            max_total_knots: self.max_total_knots,
            max_table_bytes: self.max_table_bytes,
            below: self.below,
            above: self.above,
            observation_guard: self.observation_guard,
            provenance: Some(self.provenance),
            points,
            formula,
            model,
            selector_axes: self.selector_axes,
            expected_selectors: self.expected_selectors,
            members: self.members,
            gaps: self.gaps,
        };
        (self.name, family)
    }
}