mzdata 0.66.6

A library to read mass spectrometry data formats and a data model for mass spectra
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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
//! The majority of this code is adapted from https://github.com/jspaezp/timsrust-calibration,
//! distributed under the Apache-2.0 license.
//!
//! It is replicated to be compatible with `timsrust` v0.4.1 instead of v0.5+ which introduces
//! greater complexity, and to avoid adding a second SQLite3 implementation.
use mzdata_param::{curie, Param, Unit, Value};
use rusqlite::Connection;
use thiserror::Error;
use timsrust::converters::{ConvertableDomain, Scan2ImConverter, Tof2MzConverter};

use super::sql::{FromSQL, SQLFrame};

fn require_at<T: rusqlite::types::FromSql>(
    row: &rusqlite::Row<'_>,
    index: usize,
    table: &str,
    column: &str,
) -> Result<T, rusqlite::Error> {
    match row.get::<usize, T>(index) {
        Ok(value) => Ok(value),
        Err(_) => Err(rusqlite::Error::InvalidColumnName(format!(
            "{table} did not contain {column} at index {index}"
        ))),
    }
}

fn im_boundaries_to_parameter(im_min: f64, im_max: f64, scan_max_index: u32) -> [f64; 2] {
    let scan_intercept: f64 = im_max;
    let scan_slope: f64 = (im_min - scan_intercept) / scan_max_index as f64;
    [scan_intercept, scan_slope]
}

fn mz_boundaries_to_parameter(mz_min: f64, mz_max: f64, tof_max_index: u32) -> [f64; 2] {
    let tof_intercept: f64 = mz_min.sqrt();
    let tof_slope: f64 = (mz_max.sqrt() - tof_intercept) / tof_max_index as f64;
    [tof_intercept, tof_slope]
}

/// One row of the `MzCalibration` table (physical TOF->m/z model).
///
/// Only the columns this crate's converters actually consume are kept; see
/// the module docs for the columns dropped as unused (`T2`, `dC2`, `C2`,
/// `C3`, `C4`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MzCalibration {
    /// `MzCalibration.Id` (primary key), referenced by `Frames.MzCalibration`.
    pub id: u32,
    /// `MzCalibration.ModelType`; only `1` is supported.
    pub model_type: u8,
    /// `MzCalibration.DigitizerTimebase`.
    pub digitizer_timebase: f64,
    /// `MzCalibration.DigitizerDelay`.
    pub digitizer_delay: f64,
    /// `MzCalibration.T1`, the reference digitizer temperature the
    /// calibration was fit at.
    pub t1: f64,
    pub t2: f64,
    /// `MzCalibration.dC1`, the per-degree drift coefficient for `C1`.
    pub dc1: f64,
    pub dc2: f64,
    /// `MzCalibration.C0`
    pub c0: Option<f64>,
    /// `MzCalibration.C1`
    pub c1: Option<f64>,
    pub c2: Option<f64>,
    pub c3: Option<f64>,
    pub c4: Option<f64>,
}

impl MzCalibration {
    pub fn new(
        id: u32,
        model_type: u8,
        digitizer_timebase: f64,
        digitizer_delay: f64,
        t1: f64,
        t2: f64,
        dc1: f64,
        dc2: f64,
        c0: Option<f64>,
        c1: Option<f64>,
        c2: Option<f64>,
        c3: Option<f64>,
        c4: Option<f64>,
    ) -> Self {
        Self {
            id,
            model_type,
            digitizer_timebase,
            digitizer_delay,
            t1,
            t2,
            dc1,
            dc2,
            c0,
            c1,
            c2,
            c3,
            c4,
        }
    }
}

impl FromSQL for MzCalibration {
    fn from_row(row: &rusqlite::Row<'_>) -> Result<Self, rusqlite::Error> {
        const TABLE_NAME: &str = "MzCalibration";
        Ok(MzCalibration::new(
            row.get(0).unwrap_or_default(),
            row.get(1).unwrap_or_default(),
            require_at(row, 2, TABLE_NAME, "DigitizerTimebase")?,
            require_at(row, 3, TABLE_NAME, "DigitizerDelay")?,
            require_at(row, 4, TABLE_NAME, "T1")?,
            require_at(row, 5, TABLE_NAME, "T2")?,
            require_at(row, 6, TABLE_NAME, "dC1")?,
            require_at(row, 7, TABLE_NAME, "dC2")?,
            require_at(row, 8, TABLE_NAME, "C0")?,
            require_at(row, 9, TABLE_NAME, "C1")?,
            require_at(row, 10, TABLE_NAME, "C2")?,
            require_at(row, 11, TABLE_NAME, "C3")?,
            require_at(row, 12, TABLE_NAME, "C4")?,
        ))
    }

    fn get_sql() -> String {
        "SELECT Id, ModelType, DigitizerTimebase, DigitizerDelay, T1, T2, dC1, dC2, C0, C1, C2, C3, C4 FROM MzCalibration".into()
    }
}

/// One row of the `TimsCalibration` table (physical scan->1/K0 mobility model).
///
/// Only the columns this crate's converters actually consume are kept; see
/// the module docs for the columns dropped as unused (`C5`, `C8`, `C9`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TimsCalibration {
    /// `TimsCalibration.Id` (primary key), referenced by
    /// `Frames.TimsCalibration`.
    pub id: u32,
    /// `TimsCalibration.ModelType`; only `2` is supported
    pub model_type: u8,
    /// `TimsCalibration.C0`
    pub c0: Option<f64>,
    /// `TimsCalibration.C1`
    pub c1: Option<f64>,
    /// `TimsCalibration.C2`
    pub c2: Option<f64>,
    /// `TimsCalibration.C3`
    pub c3: Option<f64>,
    /// `TimsCalibration.C4`
    pub c4: Option<f64>,
    /// `TimsCalibration.C6`
    pub c6: Option<f64>,
    /// `TimsCalibration.C7`
    pub c7: Option<f64>,
}

impl TimsCalibration {
    pub fn new(
        id: u32,
        model_type: u8,
        c0: Option<f64>,
        c1: Option<f64>,
        c2: Option<f64>,
        c3: Option<f64>,
        c4: Option<f64>,
        c6: Option<f64>,
        c7: Option<f64>,
    ) -> Self {
        Self {
            id,
            model_type,
            c0,
            c1,
            c2,
            c3,
            c4,
            c6,
            c7,
        }
    }
}

impl FromSQL for TimsCalibration {
    fn from_row(row: &rusqlite::Row<'_>) -> Result<Self, rusqlite::Error> {
        const TABLE_NAME: &str = "TimsCalibration";
        Ok(Self::new(
            row.get(0).unwrap_or_default(),
            require_at(row, 1, TABLE_NAME, "ModelType")?,
            row.get(2).ok(),
            row.get(3).ok(),
            row.get(4).ok(),
            row.get(5).ok(),
            row.get(6).ok(),
            row.get(7).ok(),
            row.get(8).ok(),
        ))
    }

    fn get_sql() -> String {
        "SELECT Id, ModelType, C0, C1, C2, C3, C4, C6, C7 FROM TimsCalibration".into()
    }
}

/// The parameters models for converting indices to m/z or ion mobility.
///
/// There may be multiple models for each dimension, but any given frame
/// uses a single model for each dimension. Not all models use all parameters
/// and not all model types are supported.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct CalibrationParameters {
    pub mz: Vec<MzCalibration>,
    pub tims: Vec<TimsCalibration>,
    pub basic_tims_parameters: [f64; 2],
    pub basic_mz_parameters: [f64; 2],
    pub use_otof_control: bool,
    pub basic_mz_model: Tof2MzConverter,
    pub basic_im_model: Scan2ImConverter,
    pub mz_enabled: bool,
    pub im_enabled: bool,
}

impl CalibrationParameters {
    pub fn new(
        mz: Vec<MzCalibration>,
        tims: Vec<TimsCalibration>,
        basic_mz_parameters: [f64; 2],
        basic_tims_parameters: [f64; 2],
        use_otof_control: bool,
        basic_mz_model: Tof2MzConverter,
        basic_im_model: Scan2ImConverter,
        mz_enabled: bool,
        im_enabled: bool,
    ) -> Self {
        Self {
            mz,
            tims,
            basic_mz_parameters,
            basic_tims_parameters,
            use_otof_control,
            basic_mz_model,
            basic_im_model,
            mz_enabled,
            im_enabled,
        }
    }

    pub fn from_sql(
        connection: &Connection,
        metadata: &timsrust::Metadata,
    ) -> Result<Self, rusqlite::Error> {
        let mz = MzCalibration::read_from(connection, [])?;
        let tims = TimsCalibration::read_from(connection, [])?;

        let scan_max_index = connection.query_row(
            "SELECT max(Frames.NumScans) as NumScans FROM Frames",
            [],
            |row| row.get::<usize, u32>(0),
        )?;

        let tof_max_index = connection.query_row(
            "SELECT Value FROM GlobalMetadata WHERE Key == \"DigitizerNumSamples\"",
            [],
            |row| {
                row.get::<usize, String>(0)?.parse::<u32>().map_err(|e| {
                    rusqlite::Error::FromSqlConversionFailure(
                        0,
                        rusqlite::types::Type::Text,
                        Box::new(e),
                    )
                })
            },
        )?;

        let acq_sw = connection.query_row(
            "SELECT Value FROM GlobalMetadata WHERE Key == \"AcquisitionSoftware\"",
            [],
            |row| row.get::<usize, String>(0),
        )?;
        let use_otof_control = acq_sw == "Bruker otofControl";
        let basic_tims_parameters =
            im_boundaries_to_parameter(metadata.lower_im, metadata.upper_im, scan_max_index);

        let basic_mz_parameters = mz_boundaries_to_parameter(
            metadata.lower_mz,
            metadata.upper_mz,
            tof_max_index,
        );

        Ok(Self::new(
            mz,
            tims,
            basic_mz_parameters,
            basic_tims_parameters,
            use_otof_control,
            metadata.mz_converter,
            metadata.im_converter,
            true,
            true
        ))
    }

    pub(crate) fn basic_mz_parameters(&self) -> Param {
        Param::builder()
            .curie(curie!(MS:1003825))
            .name("square root grid interpolation?")
            .value(Value::from_iter(
                self.basic_mz_parameters.map(Value::Float).into_iter(),
            ))
            .unit(Unit::MZ)
            .build()
    }

    pub(crate) fn basic_tims_parameters(&self) -> Param {
        Param::builder()
            .curie(curie!(MS:1003824))
            .name("linear grid interpolation?")
            .value(Value::List(Box::new(
                self.basic_tims_parameters.map(Value::Float),
            )))
            .unit(Unit::VoltSecondPerSquareCentimeter)
            .build()
    }

    pub fn find_mz_model_for_frame(
        &self,
        frame: &SQLFrame,
    ) -> Result<MzCalibrationModel, MzCalibrationError> {
        if !self.mz_enabled {
            return Ok(MzCalibrationModel::Basic(self.basic_mz_model))
        }
        match self
            .mz
            .iter()
            .find(|m| m.id == frame.mz_calibration)
            .map(|v| MzCalibrationModel::try_from((v, frame)))
        {
            Some(value) => value,
            None => Err(MzCalibrationError::ModelNotFound(frame.mz_calibration)),
        }
    }

    pub fn find_tims_model_for_frame(
        &self,
        frame: &SQLFrame,
    ) -> Result<TimsCalibrationModel, IonMobilityCalibrationError> {
        if !self.im_enabled {
            return Ok(TimsCalibrationModel::Basic(self.basic_im_model))
        }
        match self
            .tims
            .iter()
            .find(|m| m.id == frame.tims_calibration)
            .map(|v| TimsCalibrationModel::try_from(v))
        {
            Some(value) => value,
            None => Err(IonMobilityCalibrationError::ModelNotFound(
                frame.mz_calibration,
            )),
        }
    }
}

/// Implementation details of approximated converter model type == 1 for ion mobility conversion
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TimsCalibrationModel2 {
    pub c6: f64,
    pub c7: f64,
    pub offset: f64,
    pub slope: f64,
}

impl TimsCalibrationModel2 {
    pub fn new(c6: f64, c7: f64, offset: f64, slope: f64) -> Self {
        Self {
            c6,
            c7,
            offset,
            slope,
        }
    }

    /// Convert the model to a [`Param`] that can be used to pass the values around in a tagged generic container
    pub fn as_param(&self) -> Param {
        Param::builder()
            .curie(curie!(MS:1003824))
            .name("linear grid interpolation?")
            .value(Value::List(Box::new(
                [self.c6, self.c7, self.offset, self.slope].map(Value::Float),
            )))
            .unit(Unit::VoltSecondPerSquareCentimeter)
            .build()
    }

    pub fn convert_f6(&self, value: f64) -> f64 {
        self.convert(value)
    }

    pub fn invert_f64(&self, value: f64) -> f64 {
        self.invert(value)
    }
}

/// Errors that may occur during ion mobility calibration model retrieval
#[derive(Debug, Error)]
pub enum IonMobilityCalibrationError {
    /// Indicates that the model recorded in the frame metadata doesn't have
    /// an implementation available
    #[error("Ion mobility calibration model type {0} is not supported")]
    UnsupportedModel(u8),
    /// Indicates that the reported model type is supported, but is missing required
    /// parameters in the model definition
    #[error("Missing model parameters: {0}")]
    MissingParameters(&'static str),
    /// Indicates that the model ID provided doesn't map to a set of parameters read
    /// from the model definition table
    #[error("Ion mobility model ID {0} not found")]
    ModelNotFound(u32),
}

impl TryFrom<&'_ TimsCalibration> for TimsCalibrationModel2 {
    type Error = IonMobilityCalibrationError;

    fn try_from(value: &'_ TimsCalibration) -> Result<Self, Self::Error> {
        if value.model_type != 2 {
            return Err(IonMobilityCalibrationError::UnsupportedModel(
                value.model_type,
            ));
        }
        let c0 = value
            .c0
            .ok_or(IonMobilityCalibrationError::MissingParameters("c0"))?;
        let c1 = value
            .c1
            .ok_or(IonMobilityCalibrationError::MissingParameters("c1"))?;
        let c2 = value
            .c2
            .ok_or(IonMobilityCalibrationError::MissingParameters("c2"))?;
        let c3 = value
            .c3
            .ok_or(IonMobilityCalibrationError::MissingParameters("c3"))?;
        let c4 = value
            .c4
            .ok_or(IonMobilityCalibrationError::MissingParameters("c4"))?;
        let c6 = value
            .c6
            .ok_or(IonMobilityCalibrationError::MissingParameters("c6"))?;
        let c7 = value
            .c7
            .ok_or(IonMobilityCalibrationError::MissingParameters("c7"))?;

        let slope = if c1 == 0.0 { 0.0 } else { (c3 - c2) / c1 };
        let offset = c2 - slope * (c4 + c0);
        Ok(Self::new(c6, c7, offset, slope))
    }
}

impl ConvertableDomain for TimsCalibrationModel2 {
    fn convert<T: Into<f64> + Copy>(&self, value: T) -> f64 {
        1.0 / (self.c6 + self.c7 / (self.offset + self.slope * value.into()))
    }

    fn invert<T: Into<f64> + Copy>(&self, value: T) -> f64 {
        // im = 1/(c6 + c7/(offset + slope*scan))
        // => scan = (c7/(1/im - c6) - offset) / slope
        let denom = (1.0 / value.into()) - self.c6;
        ((self.c7 / denom) - self.offset) / self.slope
    }
}

/// Implementation details of approximated converter model type == 1 for ion m/z
///
/// These parameters are specific to a particular frame's T1 value. If a global
/// model is desired, construct using [`TryFrom::try_from`] using the [`MzCalibration`]
/// and some average (mean, median) value of T1.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MzCalibrationModel1 {
    pub c0: f64,
    pub c1: f64,
    pub c2: f64,
    pub c3: f64,
    pub c4: f64,
    pub digitizer_timebase: f64,
    pub digitizer_delay: f64,
}

impl MzCalibrationModel1 {
    pub fn new(c0: f64, c1: f64, c2: f64, c3: f64, c4: f64, digitizer_timebase: f64, digitizer_delay: f64) -> Self {
        Self { c0, c1, c2, c3, c4, digitizer_timebase, digitizer_delay }
    }

    pub fn convert_f64(&self, idx: f64) -> f64 {
        let tof = (idx * self.digitizer_timebase) + self.digitizer_delay;
        let inner = tof - self.c0;
        // Incomplete attempt to follow `rustims` approach. This is still wrong, but saved for
        // future fiddling
        let lin = inner / self.c1;
        let refined = if self.c3 != 0.0 {
            let f = self.c0 + self.c1 * lin + self.c2 * lin.powi(2) + self.c3 * lin.powi(3) - tof;
            let deriv_f = self.c1 + 2.0 * self.c2 * lin + 3.0 * self.c3 * lin.powi(2);
            if deriv_f == 0.0 {
                lin
            } else {
                lin - f / deriv_f
            }
        } else if self.c2 != 0.0 {
            let d = self.c1 - 4.0 * self.c2 * (self.c0 - tof);
            if d < 0.0 {
                lin
            } else {
                let q = -0.5 * (self.c1 + d.sqrt());
                (self.c0 - tof) / q
            }
        } else {
            lin
        };
        refined.powi(2) - self.c4
    }

    pub fn invert_f64(&self, mz: f64) -> f64 {
        let lin = (mz - self.c4).max(0.0).sqrt();
        let tof = self.c0 + self.c1 * lin + self.c2 * lin.powi(2) + self.c3 * lin.powi(3);
        (tof - self.digitizer_delay) / self.digitizer_timebase
    }

    /// Convert the model to a [`Param`] that can be used to pass the values around in a tagged generic container
    pub fn as_param(&self) -> Param {
        Param::builder()
            .curie(curie!(MS:1003825))
            .name("square root grid interpolation?")
            .value(Value::List(Box::new(
                [
                    self.c0,
                    self.c1,
                    self.c2,
                    self.c3,
                    self.c4,
                    self.digitizer_timebase,
                    self.digitizer_delay,
                ]
                .map(Value::Float),
            )))
            .unit(Unit::MZ)
            .build()
    }
}

/// Errors that may occur during ion mobility calibration model retrieval
#[derive(Debug, Error)]
pub enum MzCalibrationError {
    /// Indicates that the model recorded in the frame metadata doesn't have
    /// an implementation available
    #[error("Mz calibration model type {0} is not supported")]
    UnsupportedModel(u8),
    /// Indicates that the reported model type is supported, but is missing required
    /// parameters in the model definition
    #[error("Missing model parameters: {0}")]
    MissingParameters(&'static str),
    /// Indicates that the model ID provided doesn't map to a set of parameters read
    /// from the model definition table
    #[error("Mz model ID {0} not found")]
    ModelNotFound(u32),
    /// Indicates that m/z recalibration is not permitted and the minimal quadratic transform should be used
    #[error("Mz calibration models are disabled")]
    Disabled,
}

impl TryFrom<(&'_ MzCalibration, &'_ SQLFrame)> for MzCalibrationModel1 {
    type Error = MzCalibrationError;

    fn try_from(value: (&'_ MzCalibration, &'_ SQLFrame)) -> Result<Self, Self::Error> {
        (value.0, value.1.t1, value.1.t2).try_into()
    }
}

impl TryFrom<(&'_ MzCalibration, f64, f64)> for MzCalibrationModel1 {
    type Error = MzCalibrationError;

    fn try_from(value: (&'_ MzCalibration, f64, f64)) -> Result<Self, Self::Error> {
        let (value, t1, t2) = value;
        if value.model_type != 1 {
            return Err(MzCalibrationError::UnsupportedModel(value.model_type));
        }
        let c0 = value
            .c0
            .ok_or(MzCalibrationError::MissingParameters("c0"))?;
        let c1 = value
            .c1
            .ok_or(MzCalibrationError::MissingParameters("c1"))?;
        let c2 = value.c2.ok_or(MzCalibrationError::MissingParameters("c2"))?;
        let c3 = value.c3.ok_or(MzCalibrationError::MissingParameters("c3"))?;
        let c4 = value.c4.ok_or(MzCalibrationError::MissingParameters("c4"))?;

        // The dC2 value is usually zero
        let cf = 1.0 + (value.dc1 * (value.t1 - t1) + value.dc2 * (value.t2 - t2)) / 1.0e6;
        let c1 = (1.0e12 / (c1 * cf)).sqrt();
        Ok(Self::new(
            c0,
            c1,
            c2 / cf,
            c3,
            c4,
            value.digitizer_timebase,
            value.digitizer_delay,
        ))
    }
}

impl ConvertableDomain for MzCalibrationModel1 {
    fn convert<T: Into<f64> + Copy>(&self, value: T) -> f64 {
        self.convert_f64(value.into())
    }

    fn invert<T: Into<f64> + Copy>(&self, value: T) -> f64 {
        clamp_u32(self.invert_f64(value.into())) as f64
    }
}

pub fn clamp_u32(value: f64) -> u32 {
    const MAX_INDEX: f64 = (u32::MAX - 1) as f64;
    if value.is_nan() || value < 0.0 {
        0
    } else if value >= MAX_INDEX {
        u32::MAX - 1
    } else {
        value.round() as u32
    }
}

/// A generic container for pre-parameterized ion mobility calibration models
#[derive(Debug, Clone)]
pub enum TimsCalibrationModel {
    /// The basic linear calibration in [`timsrust`]
    Basic(Scan2ImConverter),
    /// The model type == 2 implementation, adapted from https://github.com/jspaezp/timsrust-calibration.
    Model2(TimsCalibrationModel2),
}

impl TimsCalibrationModel {
    /// Convert the model to a [`Param`] that can be used to pass the values around in a tagged generic container
    pub fn as_param(&self) -> Option<Param> {
        match self {
            TimsCalibrationModel::Basic(_) => None,
            TimsCalibrationModel::Model2(tims_calibration_model1) => {
                Some(tims_calibration_model1.as_param())
            }
        }
    }

    pub fn convert_f6(&self, value: f64) -> f64 {
        self.convert(value)
    }

    pub fn invert_f64(&self, value: f64) -> f64 {
        self.invert(value)
    }
}

impl ConvertableDomain for TimsCalibrationModel {
    fn convert<T: Into<f64> + Copy>(&self, value: T) -> f64 {
        match self {
            TimsCalibrationModel::Basic(scan2_im_converter) => scan2_im_converter.convert(value),
            TimsCalibrationModel::Model2(tims_calibration_model1) => {
                tims_calibration_model1.convert(value)
            }
        }
    }

    fn invert<T: Into<f64> + Copy>(&self, value: T) -> f64 {
        match self {
            TimsCalibrationModel::Basic(scan2_im_converter) => scan2_im_converter.invert(value),
            TimsCalibrationModel::Model2(tims_calibration_model1) => {
                tims_calibration_model1.invert(value)
            }
        }
    }
}

impl From<TimsCalibrationModel2> for TimsCalibrationModel {
    fn from(v: TimsCalibrationModel2) -> Self {
        Self::Model2(v)
    }
}

impl From<Scan2ImConverter> for TimsCalibrationModel {
    fn from(v: Scan2ImConverter) -> Self {
        Self::Basic(v)
    }
}

impl TryFrom<&'_ TimsCalibration> for TimsCalibrationModel {
    type Error = IonMobilityCalibrationError;

    fn try_from(value: &'_ TimsCalibration) -> Result<Self, Self::Error> {
        TimsCalibrationModel2::try_from(value).map(|v| TimsCalibrationModel::Model2(v))
    }
}

/// A generic container for pre-parameterized m/z calibration models
#[derive(Debug, Clone, Copy)]
pub enum MzCalibrationModel {
    /// The basic quadratic calibration in [`timsrust`]
    Basic(Tof2MzConverter),
    /// The model type == 1 implementation, adapted from https://github.com/jspaezp/timsrust-calibration.
    Model1(MzCalibrationModel1),
}

impl MzCalibrationModel {
    /// Convert the model to a [`Param`] that can be used to pass the values around in a tagged generic container
    pub fn as_param(&self) -> Option<Param> {
        match self {
            MzCalibrationModel::Basic(_) => None,
            MzCalibrationModel::Model1(mz_calibration_model1) => {
                Some(mz_calibration_model1.as_param())
            }
        }
    }

    pub fn convert_f6(&self, value: f64) -> f64 {
        self.convert(value)
    }

    pub fn invert_f64(&self, value: f64) -> f64 {
        self.invert(value)
    }
}

impl TryFrom<(&'_ MzCalibration, &'_ SQLFrame)> for MzCalibrationModel {
    type Error = MzCalibrationError;

    fn try_from(value: (&'_ MzCalibration, &'_ SQLFrame)) -> Result<Self, Self::Error> {
        MzCalibrationModel1::try_from(value).map(|v| v.into())
    }
}

impl TryFrom<(&'_ MzCalibration, f64, f64)> for MzCalibrationModel {
    type Error = MzCalibrationError;

    fn try_from(value: (&'_ MzCalibration, f64, f64)) -> Result<Self, Self::Error> {
        eprintln!("Converting {value:?} to m/z calibration");
        MzCalibrationModel1::try_from(value).map(|v| v.into())
    }
}

impl ConvertableDomain for MzCalibrationModel {
    fn convert<T: Into<f64> + Copy>(&self, value: T) -> f64 {
        match self {
            MzCalibrationModel::Basic(tof2_mz_converter) => tof2_mz_converter.convert(value),
            MzCalibrationModel::Model1(mz_calibration_model1) => {
                mz_calibration_model1.convert(value)
            }
        }
    }

    fn invert<T: Into<f64> + Copy>(&self, value: T) -> f64 {
        match self {
            MzCalibrationModel::Basic(tof2_mz_converter) => tof2_mz_converter.invert(value),
            MzCalibrationModel::Model1(mz_calibration_model1) => {
                mz_calibration_model1.invert(value)
            }
        }
    }
}

impl From<MzCalibrationModel1> for MzCalibrationModel {
    fn from(v: MzCalibrationModel1) -> Self {
        Self::Model1(v)
    }
}

impl From<Tof2MzConverter> for MzCalibrationModel {
    fn from(v: Tof2MzConverter) -> Self {
        Self::Basic(v)
    }
}

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

    #[test]
    fn scan2im_matches_fork_reference() {
        let cal = TimsCalibration {
            id: 1,
            model_type: 2,
            c0: Some(1.0),
            c1: Some(708.0),
            c2: Some(241.751905250524),
            c3: Some(99.2437539638487),
            c4: Some(33.9622641509434),
            c6: Some(0.0071422641733084),
            c7: Some(164.998795925213),
        };
        let conv = TimsCalibrationModel2::try_from(&cal).unwrap();
        const TOL: f64 = 5e-2;
        let im1 = conv.convert(1u32);
        assert!((im1 - 1.45).abs() < TOL, "im1={im1}");
        let im708 = conv.convert(708u32);
        assert!((im708 - 0.64).abs() < TOL, "im708={im708}");

        // round trip
        let back = conv.invert(im708) as u32;
        assert!((back as i64 - 708).abs() <= 1);
    }
}

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

    #[test]
    fn tof2mz_matches_fork_reference() {
        let cal = MzCalibration {
            id: 1,
            model_type: 1,
            digitizer_timebase: 0.125,
            digitizer_delay: 25741.0,
            t1: 20.9410989491122,
            t2: 0.0,
            dc1: 20.0,
            dc2: 0.0,
            c0: Some(286.065160463331),
            c1: Some(154317.348188993),
            c2: Some(0.0),
            c3: Some(0.0),
            c4: Some(0.0),
        };
        let real_t1 = 20.9455139021767;
        let real_t2 = 0.0;
        let conv = MzCalibrationModel1::try_from((&cal, real_t1, real_t2)).unwrap();

        let mz0 = f64::from(conv.convert(0u32));
        let mz_max = f64::from(conv.convert(636029u32));
        const TOL: f64 = 1e-3;
        assert!((mz0 - 99.990834).abs() < TOL, "mz0={mz0}");
        assert!((mz_max - 1700.005).abs() < TOL, "mz_max={mz_max}");

        // round trip
        let back = conv.invert(mz_max);
        assert!(((back as u32) as i64 - 636029).abs() <= 1);
    }
}