rdml-qpcr 0.1.1

Read, write, and validate RDML (Real-time PCR Data Markup Language) qPCR data files
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
//! The measurement chain: `experiment` → `run` → `react` → `data`, with
//! per-cycle amplification points and per-temperature melting points.
//!
//! # Plate formats
//!
//! [`PcrFormat`] keeps the schema's raw `rows`/`columns` integer pair
//! rather than an enum of known formats. The XSD types these as plain
//! `xs:int`; files contain values outside any fixed enum (`rows = -1`
//! means "display as a list", `columns = 1` suppresses the column label,
//! and instruments can introduce new geometries), so an enum would make
//! such files unrepresentable. Named constructors ([`PcrFormat::plate96`]
//! etc.) cover the common formats, and [`PcrFormat::layout`] interprets
//! the two documented display conventions.

use std::num::NonZeroU32;

use serde::{Deserialize, Serialize};

use crate::enums::{CqDetectionMethod, LabelFormat};
use crate::types::{
    DateTime, DocumentationRef, ExperimenterRef, Id, Reasons, SampleRef, TargetRef, TccRef,
};

use super::dpcr::Partitions;

/// A set of runs that belong together (root-level master element
/// `experiment`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Experiment {
    /// Unique id of this experiment.
    pub id: Id,
    /// Free-text description.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub description: Option<String>,
    /// References to shared [`Documentation`](crate::Documentation) blocks.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub documentation: Vec<DocumentationRef>,
    /// The runs of this experiment. Run ids must be unique within the
    /// experiment.
    #[serde(rename = "run", skip_serializing_if = "Vec::is_empty", default)]
    pub runs: Vec<Run>,
}

impl Experiment {
    /// Creates an empty experiment with the given id.
    #[must_use]
    pub fn new(id: Id) -> Self {
        Self {
            id,
            description: None,
            documentation: Vec::new(),
            runs: Vec::new(),
        }
    }
}

/// One run: a set of reactions performed together — one plate, one rotor,
/// one array, one chip (schema `runType`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Run {
    /// Id of this run, unique within its experiment.
    pub id: Id,
    /// Free-text description.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub description: Option<String>,
    /// References to shared [`Documentation`](crate::Documentation) blocks.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub documentation: Vec<DocumentationRef>,
    /// The people who performed this run.
    #[serde(
        rename = "experimenter",
        skip_serializing_if = "Vec::is_empty",
        default
    )]
    pub experimenters: Vec<ExperimenterRef>,
    /// Description of the instrument used to acquire the data.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub instrument: Option<String>,
    /// The software used to collect and analyse the data.
    #[serde(
        rename = "dataCollectionSoftware",
        skip_serializing_if = "Option::is_none",
        default
    )]
    pub data_collection_software: Option<DataCollectionSoftware>,
    /// Description of the method used to determine the background.
    #[serde(
        rename = "backgroundDeterminationMethod",
        skip_serializing_if = "Option::is_none",
        default
    )]
    pub background_determination_method: Option<String>,
    /// The method used to calculate quantification cycles.
    #[serde(
        rename = "cqDetectionMethod",
        skip_serializing_if = "Option::is_none",
        default
    )]
    pub cq_detection_method: Option<CqDetectionMethod>,
    /// The cycling program used to acquire the data.
    #[serde(
        rename = "thermalCyclingConditions",
        skip_serializing_if = "Option::is_none",
        default
    )]
    pub thermal_cycling_conditions: Option<TccRef>,
    /// The plate/rotor geometry of the run — required by the schema.
    #[serde(rename = "pcrFormat")]
    pub pcr_format: PcrFormat,
    /// Date and time the data was acquired.
    #[serde(rename = "runDate", skip_serializing_if = "Option::is_none", default)]
    pub run_date: Option<DateTime>,
    /// The reactions of this run. Reaction ids must be unique within the
    /// run.
    #[serde(rename = "react", skip_serializing_if = "Vec::is_empty", default)]
    pub reacts: Vec<React>,
}

impl Run {
    /// Creates an empty run with the given id and format.
    #[must_use]
    pub fn new(id: Id, pcr_format: PcrFormat) -> Self {
        Self {
            id,
            description: None,
            documentation: Vec::new(),
            experimenters: Vec::new(),
            instrument: None,
            data_collection_software: None,
            background_determination_method: None,
            cq_detection_method: None,
            thermal_cycling_conditions: None,
            pcr_format,
            run_date: None,
            reacts: Vec::new(),
        }
    }
}

/// Name and version of the software that collected/analysed the data
/// (schema `dataCollectionSoftwareType`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DataCollectionSoftware {
    /// Software name.
    pub name: String,
    /// Software version.
    pub version: String,
}

impl DataCollectionSoftware {
    /// Creates a software description.
    pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            version: version.into(),
        }
    }
}

/// The geometry of a run: how reactions are arranged for display (schema
/// `pcrFormatType`). See the [module docs](self) for why this is a raw
/// pair rather than an enum, and [`PcrFormat::layout`] for the documented
/// display conventions.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PcrFormat {
    /// Number of rows. `-1` by convention means "do not reconstruct a
    /// plate — display the reactions as a flat list".
    pub rows: i32,
    /// Number of columns. `1` by convention means "do not display a
    /// column label" (all rotors, single wells, and free format).
    pub columns: i32,
    /// How row labels are displayed.
    #[serde(rename = "rowLabel")]
    pub row_label: LabelFormat,
    /// How column labels are displayed.
    #[serde(rename = "columnLabel")]
    pub column_label: LabelFormat,
}

/// The interpreted display convention of a [`PcrFormat`]; see
/// [`PcrFormat::layout`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PlateLayout {
    /// Reconstruct a grid with this many rows and columns.
    Plate {
        /// Number of rows (> 0).
        rows: u32,
        /// Number of columns (> 0).
        columns: u32,
    },
    /// Do not reconstruct a plate; display reactions as a flat list
    /// (`rows` was `-1`, or the pair was not a positive grid).
    List,
}

impl PcrFormat {
    /// A new format with numeric labels (the most common label choice for
    /// non-plate formats).
    #[must_use]
    pub fn new(rows: i32, columns: i32) -> Self {
        Self {
            rows,
            columns,
            row_label: LabelFormat::Numbers,
            column_label: LabelFormat::Numbers,
        }
    }

    /// Single well: 1 × 1, numeric labels.
    #[must_use]
    pub fn single_well() -> Self {
        Self::new(1, 1)
    }

    /// 48-well plate: 6 × 8, rows lettered.
    #[must_use]
    pub fn plate48() -> Self {
        Self::plate(6, 8)
    }

    /// 96-well plate: 8 × 12, rows lettered.
    #[must_use]
    pub fn plate96() -> Self {
        Self::plate(8, 12)
    }

    /// 384-well plate: 16 × 24, rows lettered.
    #[must_use]
    pub fn plate384() -> Self {
        Self::plate(16, 24)
    }

    /// 1536-well plate: 32 × 48, rows lettered.
    #[must_use]
    pub fn plate1536() -> Self {
        Self::plate(32, 48)
    }

    /// 3072-well multi-array plate (e.g. BioTrove): 32 × 96 with compound
    /// `A1a1` labels.
    #[must_use]
    pub fn array3072() -> Self {
        Self {
            rows: 32,
            columns: 96,
            row_label: LabelFormat::A1a1,
            column_label: LabelFormat::A1a1,
        }
    }

    /// 5184-well chip: 72 × 72, rows lettered.
    #[must_use]
    pub fn chip5184() -> Self {
        Self::plate(72, 72)
    }

    /// A rotor with `places` positions: `places` × 1, numeric labels.
    /// Values above `i32::MAX` (not a physical rotor) saturate.
    #[must_use]
    pub fn rotor(places: u32) -> Self {
        Self::new(i32::try_from(places).unwrap_or(i32::MAX), 1)
    }

    /// Free format: `-1 × 1` — display reactions as a list.
    #[must_use]
    pub fn free_format() -> Self {
        Self::new(-1, 1)
    }

    /// A `rows` × `columns` plate with lettered rows and numeric columns.
    /// Values above `i32::MAX` (not a physical plate) saturate.
    #[must_use]
    pub fn plate(rows: u32, columns: u32) -> Self {
        Self {
            rows: i32::try_from(rows).unwrap_or(i32::MAX),
            columns: i32::try_from(columns).unwrap_or(i32::MAX),
            row_label: LabelFormat::Abc,
            column_label: LabelFormat::Numbers,
        }
    }

    /// Interprets the documented display conventions: `rows = -1` (or any
    /// non-positive pair) means a flat list; otherwise a grid.
    ///
    /// A grid with `columns == 1` is a strip (rotors; the convention says
    /// to show no column label). Note that some exporters flatten a real
    /// plate into an `N × 1` format; the file carries no way to recover
    /// the original geometry, so `layout` reports the strip as declared.
    #[must_use]
    pub fn layout(&self) -> PlateLayout {
        match (u32::try_from(self.rows), u32::try_from(self.columns)) {
            (Ok(rows), Ok(columns)) if rows > 0 && columns > 0 => {
                PlateLayout::Plate { rows, columns }
            }
            _ => PlateLayout::List,
        }
    }

    /// The reaction id at a 1-based (row, column) position, using the
    /// schema's row-first/column-second numbering. Returns `None` for list
    /// layouts or out-of-range positions.
    #[must_use]
    pub fn react_id_at(&self, row: u32, column: u32) -> Option<NonZeroU32> {
        match self.layout() {
            PlateLayout::Plate { rows, columns }
                if (1..=rows).contains(&row) && (1..=columns).contains(&column) =>
            {
                NonZeroU32::new((row - 1) * columns + column)
            }
            _ => None,
        }
    }

    /// The 1-based (row, column) position of a reaction id, or `None` for
    /// list layouts or ids beyond the plate.
    #[must_use]
    pub fn position_of(&self, react_id: NonZeroU32) -> Option<(u32, u32)> {
        match self.layout() {
            PlateLayout::Plate { rows, columns } => {
                let index = react_id.get() - 1;
                let (row, column) = (index / columns + 1, index % columns + 1);
                (row <= rows).then_some((row, column))
            }
            PlateLayout::List => None,
        }
    }

    /// A human-readable well name for a reaction id (e.g. `B3` on a
    /// 96-well plate, `17` on a rotor), following the run's label formats.
    /// Falls back to the plain id for list layouts, ids beyond the plate,
    /// and compound `A1a1` labels (whose sub-array geometry the format
    /// does not carry).
    #[must_use]
    pub fn well_name(&self, react_id: NonZeroU32) -> String {
        let fallback = react_id.to_string();
        let Some((row, column)) = self.position_of(react_id) else {
            return fallback;
        };
        let row_part = match self.row_label {
            LabelFormat::Abc => letters(row),
            LabelFormat::Numbers => row.to_string(),
            LabelFormat::A1a1 => return fallback,
        };
        match (self.columns, self.column_label) {
            // Convention: a single column means "do not show a column label".
            (1, _) => row_part,
            (_, LabelFormat::A1a1) => fallback,
            (_, LabelFormat::Abc) => format!("{row_part}{}", letters(column)),
            (_, LabelFormat::Numbers) => format!("{row_part}{column}"),
        }
    }

    /// The display label of a 1-based row, per [`row_label`](Self::row_label)
    /// (e.g. `B` for row 2 on a 96-well plate). Compound `A1a1` labels
    /// have no standalone row form and fall back to the number.
    #[must_use]
    pub fn row_name(&self, row: u32) -> String {
        match self.row_label {
            LabelFormat::Abc => letters(row),
            LabelFormat::Numbers | LabelFormat::A1a1 => row.to_string(),
        }
    }

    /// The display label of a 1-based column, per
    /// [`column_label`](Self::column_label). Compound `A1a1` labels fall
    /// back to the number.
    #[must_use]
    pub fn column_name(&self, column: u32) -> String {
        match self.column_label {
            LabelFormat::Abc => letters(column),
            LabelFormat::Numbers | LabelFormat::A1a1 => column.to_string(),
        }
    }
}

/// 1 → `A`, 26 → `Z`, 27 → `AA` (spreadsheet-style letters).
fn letters(mut n: u32) -> String {
    let mut out = Vec::new();
    while n > 0 {
        let rem = (n - 1) % 26;
        out.push(b'A' + rem as u8);
        n = (n - 1) / 26;
    }
    out.reverse();
    String::from_utf8(out).expect("ASCII letters")
}

/// One reaction: an independent chemical reaction in a well, capillary,
/// or through-hole (schema `reactType`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct React {
    /// The position of this reaction, unique within the run.
    ///
    /// Ids are assigned by *position*, not by use: on plates row-first /
    /// column-second (A1 = 1, A2 = 2, …, B1 = columns + 1, …), on rotors
    /// by place number. Empty wells simply have no `React` entry — their
    /// ids stay unused.
    pub id: NonZeroU32,
    /// The sample loaded into this reaction.
    pub sample: SampleRef,
    /// The reaction volume in microliters.
    /// *(RDML 1.4, candidate recommendation)*
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub vol: Option<f64>,
    /// The measured curves/results, one entry per target (multiplex
    /// reactions have several). Target ids must be unique within the
    /// reaction. May be empty when all data lives in
    /// [`partitions`](Self::partitions) (digital PCR).
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub data: Vec<Data>,
    /// Digital-PCR partition data. *(RDML ≥ 1.3)*
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub partitions: Option<Partitions>,
}

impl React {
    /// Creates a reaction at position `id` containing `sample`.
    #[must_use]
    pub fn new(id: NonZeroU32, sample: SampleRef) -> Self {
        Self {
            id,
            sample,
            vol: None,
            data: Vec::new(),
            partitions: None,
        }
    }
}

/// The measured data of one reaction for one target (schema `dataType`).
///
/// This crate stores *results*; it never computes them. `cq`, `amp_eff`,
/// `n0`, … are carried verbatim from whatever analysis software produced
/// them.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Data {
    /// The target this data belongs to.
    pub tar: TargetRef,
    /// Quantification cycle: the calculated fractional PCR cycle used for
    /// downstream quantification.
    ///
    /// `None` means not available. On disk, absence *or* the documented
    /// sentinel value `-1.0` both mean "not available"; this crate maps
    /// the sentinel to `None` on read and never writes it, so it cannot
    /// leak into arithmetic.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub cq: Option<f64>,
    /// N₀: target quantity per reaction in calculated arbitrary
    /// fluorescence units. `None` means not available (sentinel `-1.0` on
    /// disk, handled as for [`cq`](Self::cq)). *(RDML ≥ 1.3)*
    #[serde(rename = "N0", skip_serializing_if = "Option::is_none", default)]
    pub n0: Option<f64>,
    /// Absolute number of copies in the reaction. `None` means not
    /// available (sentinel `-1.0` on disk, handled as for
    /// [`cq`](Self::cq)). *(RDML 1.4, candidate recommendation)*
    #[serde(rename = "Ncopy", skip_serializing_if = "Option::is_none", default)]
    pub n_copy: Option<f64>,
    /// Free-text description of the amplification-efficiency method.
    /// *(RDML ≥ 1.3)*
    #[serde(rename = "ampEffMet", skip_serializing_if = "Option::is_none", default)]
    pub amp_eff_met: Option<String>,
    /// Observed amplification efficiency as fold-increase per cycle (e.g.
    /// `1.95` for 95 %). Consumers assume the ideal `2.0` when absent.
    /// *(RDML ≥ 1.3)*
    #[serde(rename = "ampEff", skip_serializing_if = "Option::is_none", default)]
    pub amp_eff: Option<f64>,
    /// Standard error of [`amp_eff`](Self::amp_eff). *(RDML ≥ 1.3)*
    #[serde(rename = "ampEffSE", skip_serializing_if = "Option::is_none", default)]
    pub amp_eff_se: Option<f64>,
    /// Correction factor for the fraction of expected product among all
    /// products (`corrN0 = N0 × corrF ÷ corrP`). Consumers assume the
    /// ideal `1.0` when absent. *(RDML ≥ 1.3)*
    #[serde(rename = "corrF", skip_serializing_if = "Option::is_none", default)]
    pub corr_f: Option<f64>,
    /// Correction factor for inter-run differences within this experiment
    /// (`corrN0 = N0 × corrF ÷ corrP`). `None` means not available
    /// (sentinel `-1.0` on disk, handled as for [`cq`](Self::cq));
    /// consumers assume the ideal `1.0` when the element is absent.
    /// *(RDML ≥ 1.3)*
    #[serde(rename = "corrP", skip_serializing_if = "Option::is_none", default)]
    pub corr_p: Option<f64>,
    /// Corrected quantification cycle. `None` means not available
    /// (sentinel `-1.0` on disk, handled as for [`cq`](Self::cq)).
    /// *(RDML ≥ 1.3)*
    #[serde(rename = "corrCq", skip_serializing_if = "Option::is_none", default)]
    pub corr_cq: Option<f64>,
    /// Observed melting temperature of the amplicon in °C. *(RDML ≥ 1.3)*
    #[serde(rename = "meltTemp", skip_serializing_if = "Option::is_none", default)]
    pub melt_temp: Option<f64>,
    /// If `Some`, this entry is excluded from evaluation; the reasons
    /// say why. Exclusion is expressed by presence: `None` writes
    /// nothing, and `<excl>false</excl>` cannot be produced. See
    /// [`Reasons`].
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub excl: Option<Reasons>,
    /// Notes that do *not* exclude the entry, `;`-joined on disk like
    /// [`excl`](Self::excl). *(RDML ≥ 1.3)*
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub note: Option<Reasons>,
    /// The amplification curve: one point per cycle, in acquisition
    /// order. Cycle numbers must be unique within this entry.
    #[serde(rename = "adp", skip_serializing_if = "Vec::is_empty", default)]
    pub adps: Vec<AmpPoint>,
    /// The melting curve: one point per temperature. Temperatures must be
    /// unique within this entry.
    #[serde(rename = "mdp", skip_serializing_if = "Vec::is_empty", default)]
    pub mdps: Vec<MeltPoint>,
    /// Result of an endpoint measurement.
    #[serde(rename = "endPt", skip_serializing_if = "Option::is_none", default)]
    pub end_pt: Option<f64>,
    /// Background fluorescence: the y-intercept of the baseline trend.
    #[serde(rename = "bgFluor", skip_serializing_if = "Option::is_none", default)]
    pub bg_fluor: Option<f64>,
    /// Slope of the baseline trend. Absent means a slope of 0.0; if
    /// present without [`bg_fluor`](Self::bg_fluor) it should be ignored.
    /// *(RDML ≥ 1.2)*
    #[serde(
        rename = "bgFluorSlp",
        skip_serializing_if = "Option::is_none",
        default
    )]
    pub bg_fluor_slp: Option<f64>,
    /// Quantification fluorescence: the fluorescence value corresponding
    /// to the threshold line.
    #[serde(
        rename = "quantFluor",
        skip_serializing_if = "Option::is_none",
        default
    )]
    pub quant_fluor: Option<f64>,
}

impl Data {
    /// Creates an empty data entry for `target`.
    #[must_use]
    pub fn new(tar: TargetRef) -> Self {
        Self {
            tar,
            cq: None,
            n0: None,
            n_copy: None,
            amp_eff_met: None,
            amp_eff: None,
            amp_eff_se: None,
            corr_f: None,
            corr_p: None,
            corr_cq: None,
            melt_temp: None,
            excl: None,
            note: None,
            adps: Vec::new(),
            mdps: Vec::new(),
            end_pt: None,
            bg_fluor: None,
            bg_fluor_slp: None,
            quant_fluor: None,
        }
    }

    /// Whether this entry is excluded from evaluation (i.e.
    /// [`excl`](Self::excl) is present).
    #[must_use]
    pub fn is_excluded(&self) -> bool {
        self.excl.is_some()
    }
}

/// One amplification data point (schema `dpAmpCurveType`, element `adp`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AmpPoint {
    /// The PCR cycle at which the point was collected. A float — points
    /// taken several times per cycle (e.g. annealing *and* elongation
    /// reads) use fractional cycles. Unique within one [`Data`].
    pub cyc: f64,
    /// Temperature in °C at the time of measurement.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub tmp: Option<f64>,
    /// The measured fluorescence intensity.
    ///
    /// This value must not be baseline-corrected. Instrument-side
    /// corrections up to but excluding baseline correction
    /// (ROX/passive-reference normalisation, empty-well correction,
    /// colour compensation) are expected to have been applied.
    /// Subtracting the baseline trend is not, because downstream
    /// analysis software fits its own baseline to the uncorrected curve.
    /// Baseline parameters go in [`Data::bg_fluor`] and
    /// [`Data::bg_fluor_slp`].
    pub fluor: f64,
}

impl AmpPoint {
    /// Creates an amplification point.
    #[must_use]
    pub fn new(cyc: f64, fluor: f64) -> Self {
        Self {
            cyc,
            tmp: None,
            fluor,
        }
    }
}

/// One melting-curve data point (schema `dpMeltingCurveType`, element
/// `mdp`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MeltPoint {
    /// Temperature in °C of this point. Unique within one [`Data`].
    pub tmp: f64,
    /// The measured fluorescence intensity, not baseline-corrected
    /// (see [`AmpPoint::fluor`]).
    pub fluor: f64,
}

impl MeltPoint {
    /// Creates a melting-curve point.
    #[must_use]
    pub fn new(tmp: f64, fluor: f64) -> Self {
        Self { tmp, fluor }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn nz(n: u32) -> NonZeroU32 {
        NonZeroU32::new(n).unwrap()
    }

    #[test]
    fn plate_position_math() {
        let f = PcrFormat::plate96();
        assert_eq!(f.react_id_at(1, 1), Some(nz(1)));
        assert_eq!(f.react_id_at(1, 12), Some(nz(12)));
        assert_eq!(f.react_id_at(2, 1), Some(nz(13)));
        assert_eq!(f.react_id_at(8, 12), Some(nz(96)));
        assert_eq!(f.react_id_at(9, 1), None);
        assert_eq!(f.position_of(nz(1)), Some((1, 1)));
        assert_eq!(f.position_of(nz(13)), Some((2, 1)));
        assert_eq!(f.position_of(nz(96)), Some((8, 12)));
        assert_eq!(f.position_of(nz(97)), None);
    }

    #[test]
    fn well_names() {
        let f = PcrFormat::plate96();
        assert_eq!(f.well_name(nz(1)), "A1");
        assert_eq!(f.well_name(nz(15)), "B3");
        assert_eq!(f.well_name(nz(96)), "H12");
        // Beyond the plate: fall back to the raw id.
        assert_eq!(f.well_name(nz(200)), "200");

        let rotor = PcrFormat::rotor(72);
        assert_eq!(rotor.well_name(nz(17)), "17"); // single column: no column label
        assert_eq!(
            rotor.layout(),
            PlateLayout::Plate {
                rows: 72,
                columns: 1
            }
        );

        let free = PcrFormat::free_format();
        assert_eq!(free.layout(), PlateLayout::List);
        assert_eq!(free.well_name(nz(5)), "5");
    }

    #[test]
    fn row_and_column_names() {
        let f = PcrFormat::plate96();
        assert_eq!(f.row_name(2), "B");
        assert_eq!(f.column_name(12), "12");
        let rotor = PcrFormat::rotor(72);
        assert_eq!(rotor.row_name(17), "17");
        let array = PcrFormat::array3072();
        assert_eq!(array.row_name(9), "9"); // A1a1: no standalone row form
    }

    #[test]
    fn letter_labels() {
        assert_eq!(letters(1), "A");
        assert_eq!(letters(26), "Z");
        assert_eq!(letters(27), "AA");
        assert_eq!(letters(52), "AZ");
        assert_eq!(letters(72), "BT");
    }
}