mzident 0.2.1

Handle all kinds of PSM 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
use std::{
    borrow::Cow,
    marker::PhantomData,
    ops::Range,
    path::{Path, PathBuf},
    sync::OnceLock,
};

use mzcore::{
    csv::{CsvLine, parse_csv},
    ontology::Ontologies,
    sequence::{
        FlankingSequence, Peptidoform, PeptidoformIonSet, SemiAmbiguous, SloppyParsingParameters,
    },
    system::{Mass, MassOverCharge, Time, isize::Charge},
};
use serde::{Deserialize, Serialize};

use crate::{
    BoxedIdentifiedPeptideIter, KnownFileFormat, PSM, PSMData, PSMFileFormatVersion, PSMMetaData,
    PSMSource, PeptidoformPresent, SpectrumId, SpectrumIds,
    common_parser::{Location, OptionalColumn},
};

static NUMBER_ERROR: (&str, &str) = (
    "Invalid InstaNovo line",
    "This column is not a number but it is required to be a number in this format",
);

static BUILT_IN_MODIFICATIONS: OnceLock<SloppyParsingParameters> = OnceLock::new();

format_family!(
    InstaNovo,
    SemiAmbiguous, PeptidoformPresent, [
        &INSTANOVO_COMBINED_V1_2_2,
        &INSTANOVO_V1_2_2,
        &INSTANOVOPLUS_V1_2_2,
        &INSTANOVO_V1_1_0,
        &INSTANOVO_V1_1_4,
        &INSTANOVOPLUS_V1_1_4,
        &INSTANOVO_V1_0_0,
    ], b',', None;
    required {
        scan_number: usize, |location: Location, _| location.parse(NUMBER_ERROR);
        mz: MassOverCharge, |location: Location, _| location.parse::<f64>(NUMBER_ERROR).map(MassOverCharge::new::<mzcore::system::thomson>);
        z: Charge, |location: Location, _| location.parse::<isize>(NUMBER_ERROR).map(Charge::new::<mzcore::system::e>);
        raw_file: PathBuf, |location: Location, _| Ok(Path::new(&location.get_string()).to_owned());
        peptide: Peptidoform<SemiAmbiguous>, |location: Location, ontologies: &Ontologies| Peptidoform::sloppy_pro_forma_inner(
            &location.base_context(),
            location.full_line(),
            location.range.clone(),
            ontologies,
            BUILT_IN_MODIFICATIONS.get_or_init(|| SloppyParsingParameters {
                replace_mass_modifications: Some(vec![
                ontologies.unimod().get_by_index(&mzcv::AccessionCode::Numeric(35)).unwrap(),
                ontologies.unimod().get_by_index(&mzcv::AccessionCode::Numeric(21)).unwrap(),
                ontologies.unimod().get_by_index(&mzcv::AccessionCode::Numeric(4)).unwrap(),
                ]),
                ..Default::default()
            })).map_err(BoxedError::to_owned);

        score: f64, |location: Location, _| location.parse::<f64>(NUMBER_ERROR);
    }
    optional {
        local_confidence: Vec<f64>, |location: Location, _| {
            let location = location.trim_start_matches("[").trim_end_matches("]");
            location.or_empty().map_or(Ok(Vec::new()), |location| {
                location
                    .array(',')
                    .map(|l| l.parse::<f64>(NUMBER_ERROR))
                    .collect::<Result<Vec<_>, _>>()
            })
        };
        used_model: UsedModel, |location: Location, _| location.parse::<UsedModel>(("Invalid InstaNovo line", "The selected model has to be 'diffusion' or 'transformer'."));
     }

     fn post_process(source: &CsvLine, mut parsed: Self, _ontologies: &Ontologies) -> Result<Self, BoxedError<'static, BasicKind>> {
        validate_instanovo_schema(source, &parsed)?;

        if parsed.local_confidence.as_ref().is_some_and(Vec::is_empty) {
            parsed.local_confidence = None;
        }
        // Only keep the parsed local_confidence is the `UsedModel == Transformer`
        if let Some(used_model) = parsed.used_model && used_model == UsedModel::Diffusion {
            parsed.local_confidence = None;
        }
        if let Some(local_confidence) = parsed.local_confidence.as_mut() && !parsed.peptide.get_n_term().is_empty() {
            let offset = parsed.peptide.get_n_term().len();
            if local_confidence.len() >= offset {
                *local_confidence = local_confidence[offset..].to_vec();
            }
        }
        Ok(parsed)
    }
);

/// InstaNovo version 1.0.0
pub const INSTANOVO_V1_0_0: InstaNovoFormat = InstaNovoFormat {
    version: InstaNovoVersion::V1_0_0,
    scan_number: "scan_number",
    mz: "precursor_mz",
    z: "precursor_charge",
    raw_file: "experiment_name",
    peptide: "preds",
    score: "log_probs",
    local_confidence: OptionalColumn::Required("token_log_probs"),
    used_model: OptionalColumn::NotAvailable,
};

/// InstaNovo version 1.1.0
pub const INSTANOVO_V1_1_0: InstaNovoFormat = InstaNovoFormat {
    version: InstaNovoVersion::V1_1_0,
    scan_number: "scan_number",
    mz: "precursor_mz",
    z: "precursor_charge",
    raw_file: "experiment_name",
    peptide: "predictions",
    score: "log_probabilities",
    local_confidence: OptionalColumn::Required("token_log_probabilities"),
    used_model: OptionalColumn::NotAvailable,
};

/// InstaNovo version 1.1.4
pub const INSTANOVO_V1_1_4: InstaNovoFormat = InstaNovoFormat {
    version: InstaNovoVersion::V1_1_4,
    scan_number: "scan_number",
    mz: "precursor_mz",
    z: "precursor_charge",
    raw_file: "experiment_name",
    peptide: "preds",
    score: "log_probs",
    local_confidence: OptionalColumn::Required("token_log_probs"),
    used_model: OptionalColumn::NotAvailable,
};

/// The known InstaNovoPlus 1.1.4 output schema
pub const INSTANOVOPLUS_V1_1_4: InstaNovoFormat = InstaNovoFormat {
    version: InstaNovoVersion::PlusV1_1_4,
    scan_number: "scan_number",
    mz: "precursor_mz",
    z: "precursor_charge",
    raw_file: "experiment_name",
    peptide: "final_prediction",
    score: "final_log_probabilities",
    local_confidence: OptionalColumn::Optional("transformer_token_log_probabilities"),
    used_model: OptionalColumn::Required("selected_model"),
};

/// InstaNovo version 1.2.2 transformer output
pub const INSTANOVO_V1_2_2: InstaNovoFormat = InstaNovoFormat {
    version: InstaNovoVersion::V1_2_2,
    scan_number: "scan_number",
    mz: "precursor_mz",
    z: "precursor_charge",
    raw_file: "experiment_name",
    peptide: "predictions",
    score: "log_probs",
    local_confidence: OptionalColumn::Required("token_log_probs"),
    used_model: OptionalColumn::NotAvailable,
};

/// InstaNovoPlus version 1.2.2 standalone output
pub const INSTANOVOPLUS_V1_2_2: InstaNovoFormat = InstaNovoFormat {
    version: InstaNovoVersion::PlusV1_2_2,
    scan_number: "scan_number",
    mz: "precursor_mz",
    z: "precursor_charge",
    raw_file: "experiment_name",
    peptide: "predictions",
    score: "log_probs",
    local_confidence: OptionalColumn::Required("token_log_probs"),
    used_model: OptionalColumn::NotAvailable,
};

/// InstaNovo version 1.2.2 combined transformer and InstaNovoPlus refined output
pub const INSTANOVO_COMBINED_V1_2_2: InstaNovoFormat = InstaNovoFormat {
    version: InstaNovoVersion::CombinedV1_2_2,
    scan_number: "scan_number",
    mz: "precursor_mz",
    z: "precursor_charge",
    raw_file: "experiment_name",
    peptide: "predictions",
    score: "log_probs",
    local_confidence: OptionalColumn::Required("token_log_probs"),
    used_model: OptionalColumn::NotAvailable,
};

/// All possible InstaNovo versions
#[derive(
    Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default, Serialize, Deserialize,
)]
pub enum InstaNovoVersion {
    #[default]
    /// InstaNovo version 1.0.0
    V1_0_0,
    /// InstaNovo version 1.1.0
    V1_1_0,
    /// InstaNovo version 1.1.4
    V1_1_4,
    /// InstaNovoPlus version 1.1.4 using refinement
    PlusV1_1_4,
    /// InstaNovo version 1.2.2
    V1_2_2,
    /// InstaNovoPlus version 1.2.2 standalone predictions
    PlusV1_2_2,
    /// InstaNovo version 1.2.2 combined transformer and InstaNovoPlus refined predictions
    CombinedV1_2_2,
}

impl std::fmt::Display for InstaNovoVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        write!(f, "{}", self.name())
    }
}

impl PSMFileFormatVersion<InstaNovoFormat> for InstaNovoVersion {
    fn format(self) -> InstaNovoFormat {
        match self {
            Self::V1_0_0 => INSTANOVO_V1_0_0,
            Self::V1_1_0 => INSTANOVO_V1_1_0,
            Self::V1_1_4 => INSTANOVO_V1_1_4,
            Self::PlusV1_1_4 => INSTANOVOPLUS_V1_1_4,
            Self::V1_2_2 => INSTANOVO_V1_2_2,
            Self::PlusV1_2_2 => INSTANOVOPLUS_V1_2_2,
            Self::CombinedV1_2_2 => INSTANOVO_COMBINED_V1_2_2,
        }
    }

    fn name(self) -> &'static str {
        match self {
            Self::V1_0_0 => "v1.0.0",
            Self::V1_1_0 => "v1.1.0",
            Self::V1_1_4 => "v1.1.4",
            Self::PlusV1_1_4 => "Plus v1.1.4",
            Self::V1_2_2 => "v1.2.2",
            Self::PlusV1_2_2 => "Plus v1.2.2",
            Self::CombinedV1_2_2 => "Combined v1.2.2",
        }
    }
}

fn validate_instanovo_schema(
    source: &CsvLine,
    parsed: &InstaNovoPSM,
) -> Result<(), BoxedError<'static, BasicKind>> {
    match parsed.version {
        InstaNovoVersion::V1_1_0 | InstaNovoVersion::V1_1_4 => {
            if !has_column(source, "delta_mass_ppm") {
                return Err(instanovo_schema_error(
                    source,
                    "This InstaNovo version requires the 'delta_mass_ppm' column",
                ));
            }
        }
        InstaNovoVersion::V1_2_2 => {
            if has_column(source, "instanovoplus_predictions") {
                return Err(instanovo_schema_error(
                    source,
                    "This is an InstaNovo combined output, not a transformer-only output",
                ));
            }
            if parsed.local_confidence.as_ref().is_some_and(Vec::is_empty) {
                return Err(instanovo_schema_error(
                    source,
                    "This InstaNovo transformer output requires token log probabilities",
                ));
            }
        }
        InstaNovoVersion::PlusV1_2_2 => {
            if has_column(source, "instanovoplus_predictions") {
                return Err(instanovo_schema_error(
                    source,
                    "This is an InstaNovo combined output, not a standalone InstaNovoPlus output",
                ));
            }
            if parsed
                .local_confidence
                .as_ref()
                .is_some_and(|local_confidence| !local_confidence.is_empty())
            {
                return Err(instanovo_schema_error(
                    source,
                    "This is an InstaNovo transformer output, not a standalone InstaNovoPlus output",
                ));
            }
        }
        InstaNovoVersion::CombinedV1_2_2 => {
            if !has_column(source, "instanovoplus_predictions") {
                return Err(instanovo_schema_error(
                    source,
                    "This InstaNovo version requires the 'instanovoplus_predictions' column",
                ));
            }
        }
        InstaNovoVersion::V1_0_0 | InstaNovoVersion::PlusV1_1_4 => {}
    }
    Ok(())
}

fn has_column(source: &CsvLine, column: &str) -> bool {
    source.fields.iter().any(|f| f.0.eq_ignore_ascii_case(column))
}

fn instanovo_schema_error(
    source: &CsvLine,
    message: &'static str,
) -> BoxedError<'static, BasicKind> {
    BoxedError::new(
        BasicKind::Error,
        "Invalid InstaNovo line",
        message,
        source.full_context().to_owned(),
    )
}

/// The model that produced the final prediction for an InstaNovoPlus
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub enum UsedModel {
    /// The diffusion model
    Diffusion,
    /// The transformer model
    Transformer,
}

impl mzcore::space::Space for UsedModel {
    fn space(&self) -> mzcore::space::UsedSpace {
        mzcore::space::UsedSpace::stack(size_of::<Self>())
    }
}

impl std::fmt::Display for UsedModel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        write!(f, "{}", match self {
            Self::Diffusion => "diffusion",
            Self::Transformer => "transformer",
        })
    }
}

impl std::str::FromStr for UsedModel {
    type Err = ();

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        if value.eq_ignore_ascii_case("diffusion") {
            Ok(Self::Diffusion)
        } else if value.eq_ignore_ascii_case("transformer") {
            Ok(Self::Transformer)
        } else {
            Err(())
        }
    }
}

impl PSMMetaData for InstaNovoPSM {
    type Protein = crate::NoProtein;
    #[cfg(feature = "mzannotate")]
    type SpectrumOutputMode = mzcore::chemistry::OutputMolecularFormula;

    fn peptidoform_ion_set(&self) -> Option<Cow<'_, PeptidoformIonSet>> {
        Some(Cow::Owned(self.peptide.clone().into()))
    }

    fn format(&self) -> KnownFileFormat {
        KnownFileFormat::InstaNovo(self.version)
    }

    fn numerical_id(&self) -> Option<usize> {
        Some(self.scan_number)
    }

    fn id(&self) -> String {
        self.scan_number.to_string()
    }

    fn search_engine(&self) -> Option<mzcv::Term> {
        Some(match self.version {
            InstaNovoVersion::V1_0_0
            | InstaNovoVersion::V1_1_0
            | InstaNovoVersion::V1_1_4
            | InstaNovoVersion::V1_2_2 => mzcv::term!(MS:1003612|InstaNovo),
            InstaNovoVersion::PlusV1_1_4
            | InstaNovoVersion::PlusV1_2_2
            | InstaNovoVersion::CombinedV1_2_2 => {
                mzcv::term!(MS:1003613|InstaNovo+)
            }
        })
    }

    fn confidence(&self) -> Option<f64> {
        Some(2.0 / (1.0 + 1.01_f64.powf(-self.score)))
    }

    fn local_confidence(&self) -> Option<Cow<'_, [f64]>> {
        self.local_confidence
            .as_ref()
            .map(|lc| lc.iter().map(|v| 2.0 / (1.0 + 1.25_f64.powf(-v))).collect())
    }

    fn original_confidence(&self) -> Option<(f64, mzcv::Term)> {
        Some((
            self.score,
            mzcv::term!(MS:1001153|search engine specific score),
        ))
    }

    fn original_local_confidence(&self) -> Option<&[f64]> {
        self.local_confidence.as_deref()
    }

    fn charge(&self) -> Option<Charge> {
        Some(self.z)
    }

    fn mode(&self) -> Option<Cow<'_, str>> {
        None
    }

    fn retention_time(&self) -> Option<Time> {
        None
    }

    fn scans(&self) -> SpectrumIds {
        SpectrumIds::FileKnown(vec![(self.raw_file.clone(), vec![SpectrumId::Number(
            self.scan_number,
        )])])
    }

    fn experimental_mz(&self) -> Option<MassOverCharge> {
        Some(self.mz)
    }

    fn experimental_mass(&self) -> Option<Mass> {
        Some(self.mz * self.z.to_float())
    }

    fn protein_location(&self) -> Option<Range<u16>> {
        None
    }

    fn flanking_sequences(&self) -> (&FlankingSequence, &FlankingSequence) {
        (&FlankingSequence::Unknown, &FlankingSequence::Unknown)
    }

    fn database(&self) -> Option<(&str, Option<&str>)> {
        None
    }

    fn unique(&self) -> Option<bool> {
        None
    }

    fn reliability(&self) -> Option<crate::Reliability> {
        None
    }

    fn uri(&self) -> Option<String> {
        None
    }
}