Repository navigation
Expand file tree
/
Copy pathPercolatorInfile.cpp
More file actions
1851 lines (1720 loc) · 76.8 KB
/
Copy pathPercolatorInfile.cpp
File metadata and controls
1851 lines (1720 loc) · 76.8 KB
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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Timo Sachsenberg, Johannes von Kleist $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/PercolatorInfile.h>
#include <string_view>
#include <OpenMS/CHEMISTRY/ProteaseDB.h>
#include <OpenMS/CHEMISTRY/ResidueModification.h>
#include <OpenMS/CHEMISTRY/ProteaseDigestion.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/METADATA/MetaInfoRegistry.h>
#include <OpenMS/METADATA/SpectrumLookup.h>
#include <OpenMS/FORMAT/CsvFile.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <algorithm>
#include <cctype>
#include <cmath>
#include <exception>
#include <functional>
#include <limits>
#include <optional>
#include <tuple>
#include <type_traits>
#include <regex>
#include <stdexcept>
#include <unordered_map>
#include <unordered_set>
#ifdef _OPENMP
#include <omp.h>
#endif
#if defined(__linux__)
#include <cstdint>
#include <sys/mman.h> // madvise (adviseHugePages_)
#endif
namespace OpenMS
{
using namespace std;
namespace
{
// Mass tags (e.g. Y[+79.96633]) are resolved to the closest-mass modification in ModificationsDB, which may be a different
// entry than the searched one (e.g. MOD:00254 instead of Phospho (Y)). Replace such modifications by the closest searched one.
void applyPreferredModifications_(AASequence& seq, const std::vector<const ResidueModification*>& preferred)
{
if (preferred.empty() || !seq.isModified()) return;
constexpr double max_error = 0.01;
const auto is_preferred = [&preferred](const ResidueModification* mod)
{
return std::any_of(preferred.begin(), preferred.end(), [mod](const ResidueModification* p)
{ return p == mod || p->getFullId() == mod->getFullId(); });
};
const auto find_preferred = [&preferred](const ResidueModification* mod, char residue, bool n_term, bool c_term) -> const ResidueModification*
{
const ResidueModification* best = nullptr;
double best_error = max_error;
for (const ResidueModification* p : preferred)
{
const ResidueModification::TermSpecificity ts = p->getTermSpecificity();
bool term_ok;
if (n_term) term_ok = (ts == ResidueModification::N_TERM || ts == ResidueModification::PROTEIN_N_TERM);
else if (c_term) term_ok = (ts == ResidueModification::C_TERM || ts == ResidueModification::PROTEIN_C_TERM);
else term_ok = (ts == ResidueModification::ANYWHERE);
if (!term_ok) continue;
const char origin = p->getOrigin();
if (origin != residue && origin != 'X' && origin != '.') continue;
const double error = std::fabs(p->getDiffMonoMass() - mod->getDiffMonoMass());
if (error <= best_error)
{
best_error = error;
best = p;
}
}
return best;
};
if (seq.empty()) return;
if (const ResidueModification* mod = seq.getNTerminalModification(); mod != nullptr && !is_preferred(mod))
{
if (const ResidueModification* p = find_preferred(mod, seq[0].getOneLetterCode()[0], true, false))
{
seq.setNTerminalModification(p);
}
}
if (const ResidueModification* mod = seq.getCTerminalModification(); mod != nullptr && !is_preferred(mod))
{
if (const ResidueModification* p = find_preferred(mod, seq[seq.size() - 1].getOneLetterCode()[0], false, true))
{
seq.setCTerminalModification(p);
}
}
for (Size i = 0; i < seq.size(); ++i)
{
const ResidueModification* mod = seq[i].getModification();
if (mod == nullptr || is_preferred(mod)) continue;
if (const ResidueModification* p = find_preferred(mod, seq[i].getOneLetterCode()[0], false, false))
{
seq.setModification(i, p);
}
}
}
}
void PercolatorInfile::store(const std::string& pin_file,
const PeptideIdentificationList& peptide_ids,
const StringList& feature_set,
const std::string& enz,
int min_charge,
int max_charge)
{
TextFile txt = preparePin_(peptide_ids, feature_set, enz, min_charge, max_charge);
txt.store(pin_file);
}
StringList PercolatorInfile::getStandardFeatureSet(int min_charge, int max_charge)
{
StringList fs = {
"SpecId", "Label", "ScanNr",
"ExpMass", "CalcMass", "mass", "peplen"
};
for (int c = min_charge; c <= max_charge; ++c)
{
fs.push_back("charge" + StringUtils::toStr(c));
}
fs.insert(fs.end(), {"enzN", "enzC", "enzInt", "dm", "absdm"});
return fs;
}
StringList PercolatorInfile::getFeatureSet(const ProteinIdentification::SearchParameters& search_parameters,
int min_charge, int max_charge)
{
StringList feature_set = getStandardFeatureSet(min_charge, max_charge);
if (search_parameters.metaValueExists("extra_features"))
{
const StringList extra_features = ListUtils::create<std::string>(search_parameters.getMetaValue("extra_features").toString());
feature_set.insert(feature_set.end(), extra_features.begin(), extra_features.end());
}
else
{
feature_set.push_back("score");
}
feature_set.push_back("Peptide");
feature_set.push_back("Proteins");
return feature_set;
}
// uses spectrum_reference, if empty uses spectrum_id, if also empty fall back to using index
std::string PercolatorInfile::getScanIdentifier(
const PeptideIdentification& pid, size_t index)
{
// MSGF+ uses this field, is empty if not specified
std::string scan_identifier = pid.getSpectrumReference();
if (scan_identifier.empty())
{
// XTandem uses this (integer) field
// these ids are 1-based in contrast to the index which is 0-based. This might be problematic to use for merging
if (pid.metaValueExists("spectrum_id") && !pid.getMetaValue("spectrum_id").toString().empty())
{
scan_identifier = "scan=" + pid.getMetaValue("spectrum_id").toString();
}
else
{
scan_identifier = "index=" + StringUtils::toStr(index); // fall back
OPENMS_LOG_WARN << "no known spectrum identifiers, using index [1,n] - use at own risk." << endl;
}
}
return StringUtils::removeWhitespaces(scan_identifier);
}
std::string PercolatorInfile::getFileIdentifier(const PeptideIdentification& pid)
{
const MetaInfoRegistry& registry = MetaInfoInterface::metaRegistry();
return getFileIdentifier(pid, registry.getIndex("file_origin"), registry.getIndex("id_merge_index"));
}
std::string PercolatorInfile::getFileIdentifier(const PeptideIdentification& pid, const UInt file_origin_index,
const UInt id_merge_index_index)
{
// (an unregistered name, UInt(-1), has no value: as the lookups by name)
std::string identifier = file_origin_index != UInt(-1) ? pid.getMetaValue(file_origin_index, std::string()).toString() : std::string();
// the index is a number: after the last '|', it cannot run into the file origin ("run1" vs. "run" + 1)
if (id_merge_index_index != UInt(-1) && pid.metaValueExists(id_merge_index_index))
{
identifier += "|" + pid.getMetaValue(id_merge_index_index).toString();
}
return identifier;
}
PeptideIdentificationList PercolatorInfile::load(
const std::string& pin_file,
bool higher_score_better,
const std::string& score_name,
const StringList& extra_scores,
StringList& filenames,
std::string decoy_prefix,
double threshold,
bool SageAnnotation,
const std::vector<const ResidueModification*>& preferred_modifications)
{
CsvFile csv(pin_file, '\t');
//Sage Variables, initialized in the following block if SageAnnotation is set
map<int, vector<PeptideHit::PeakAnnotation>> anno_mapping;
CsvFile tsv;
CsvFile annos;
unordered_map<std::string, size_t> to_idx_t;
if (SageAnnotation) // Block for special treatment of sage
{
std::string tsv_file_path = StringUtils::substr(pin_file, 0, pin_file.size()-3);
tsv_file_path = tsv_file_path + "tsv";
tsv = CsvFile(tsv_file_path,'\t');
std::string temp_diff = "results.sage.pin";
std::string anno_file_path = StringUtils::substr(pin_file, 0, pin_file.size()-temp_diff.length());
anno_file_path = anno_file_path + "matched_fragments.sage.tsv";
annos = CsvFile(anno_file_path, '\t');
//map PSMID to vec of PeakAnnotation
StringList sage_tsv_header;
tsv.getRow(0, sage_tsv_header);
{
int idx_t{};
for (const auto& h : sage_tsv_header) { to_idx_t[h] = idx_t++; }
}
// processs annotation file
StringList sage_annotation_header;
annos.getRow(0, sage_annotation_header);
unordered_map<std::string, size_t> to_idx_a; // map column name to column index, for full annotation file file
{
int idx_a{};
for (const auto& h : sage_annotation_header) { to_idx_a[h] = idx_a++; }
}
// map PSMs -> PeakAnnotation vector
auto num_rows = annos.rowCount();
for (size_t i = 1; i < num_rows; ++i)
{
StringList row;
annos.getRow(i, row);
//Check if mapping already has PSM, if it does add
if (!anno_mapping.contains(StringUtils::toInt32(row[to_idx_a.at("psm_id")])))
{
//Make a new vector of annotations
PeptideHit::PeakAnnotation peak_temp;
peak_temp.annotation = row[to_idx_a.at("fragment_type")] + row[to_idx_a.at("fragment_ordinals")];
peak_temp.charge = StringUtils::toInt32(row[to_idx_a.at("fragment_charge")]);
peak_temp.intensity = StringUtils::toDouble(row[to_idx_a.at("fragment_intensity")]);
peak_temp.mz = StringUtils::toDouble(row[to_idx_a.at("fragment_mz_experimental")]);
vector<PeptideHit::PeakAnnotation> temp_anno_vec;
temp_anno_vec.push_back(peak_temp);
anno_mapping[ StringUtils::toInt32(row[to_idx_a.at("psm_id")]) ] = temp_anno_vec;
}
else
{
//Add values to exisiting vector
PeptideHit::PeakAnnotation peak_temp;
peak_temp.annotation = row[to_idx_a.at("fragment_type")] + row[to_idx_a.at("fragment_ordinals")];
peak_temp.charge = StringUtils::toInt32(row[to_idx_a.at("fragment_charge")]);
peak_temp.intensity = StringUtils::toDouble(row[to_idx_a.at("fragment_intensity")]);
peak_temp.mz = StringUtils::toDouble(row[to_idx_a.at("fragment_mz_experimental")]);
anno_mapping[ StringUtils::toInt32(row[to_idx_a.at("psm_id")]) ].push_back(peak_temp);
}
}
}
StringList pin_header;
csv.getRow(0, pin_header);
unordered_map<std::string, size_t> to_idx; // map column name to column index
{
int idx{};
for (const auto& h : pin_header) { to_idx[h] = idx++; }
}
// determine file name column index in percolator in file
int file_name_column_index{-1};
if (auto it = std::find(pin_header.begin(), pin_header.end(), "FileName"); it != pin_header.end())
{
file_name_column_index = it - pin_header.begin();
}
// determine extra scores and store column indices
std::set<std::string> found_extra_scores; // additional (non-main) scores that should be stored in the PeptideHit, order important for comparable idXML
for (const std::string& s : extra_scores)
{
if (auto it = std::find(pin_header.begin(), pin_header.end(), s); it != pin_header.end())
{
found_extra_scores.insert(s);
}
else
{
OPENMS_LOG_WARN << "Extra score: " << s << " not found in Percolator input file." << endl;
}
}
// charge columns are not standardized, so we check for the format and create hash to lookup column name to charge mapping
std::regex charge_one_hot_pattern("^charge\\d+$");
std::regex sage_one_hot_pattern("^z=\\d+$");
std::string charge_prefix;
unordered_map<std::string, int> col_name_to_charge;
// Special handling for sage: sage produces an additional column for PSMs outside of the "suggested" charge search range (e.g., charge 2-5).
// The reason is that sage searches always for the charge annotated in the spectrum raw file. Only if the annotation is missing it will search
// the suggested charge range.
bool found_sage_otherz_charge_column{false};
for (const std::string& c : pin_header)
{
if (std::regex_match(c, charge_one_hot_pattern))
{
col_name_to_charge[c] = StringUtils::toInt32(StringUtils::substr(c, 6));
charge_prefix = "charge";
}
else if (std::regex_match(c, sage_one_hot_pattern))
{
col_name_to_charge[c] = StringUtils::toInt32(StringUtils::substr(c, 2));
charge_prefix = "z=";
}
else if (c == "z=other") // SAGE
{
found_sage_otherz_charge_column = true;
OPENMS_LOG_DEBUG << "Found SAGE charge column 'z=other'. Will extract charge from this column if charge was not set in the one-hot encoded charge columns." << endl;
}
}
auto n_rows = csv.rowCount();
PeptideIdentificationList pids;
pids.reserve(n_rows);
std::string spec_id;
std::string raw_file_name("UNKNOWN");
unordered_map<std::string, size_t> map_filename_to_idx; // fast lookup of filename to index in filenames vector
for (size_t i = 1; i != n_rows; ++i)
{
StringList row;
csv.getRow(i, row);
StringList t_row;
if (SageAnnotation)
{
tsv.getRow(i, t_row);
// skip if spectrum_q is above threshold
if (StringUtils::toDouble(t_row[to_idx_t.at("spectrum_q")]) > threshold ) continue;
}
if (row.size() != pin_header.size())
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Error: line " + StringUtils::toStr(i) + " of file '" + pin_file + "' does not have the same number of columns as the pin_header!",StringUtils::toStr(i));
}
if (file_name_column_index >= 0)
{
raw_file_name = row[file_name_column_index];
if (!map_filename_to_idx.contains(raw_file_name))
{
filenames.push_back(raw_file_name);
map_filename_to_idx[raw_file_name] = filenames.size() - 1;
}
}
// NOTE: In our pin files that we WRITE, SpecID will be filename + vendor spectrum native ID
// However, many search engines (e.g. Sage) choose arbitrary IDs, which is unfortunately allowed
// by this loosely defined format.
const std::string& sSpecId = row[to_idx.at("SpecId")];
double IM = 0.0;
if (auto it = to_idx.find("ion_mobility"); it != to_idx.end())
{
const std::string& sIM = row[it->second]; // read IM from e.g. Sage output
IM = StringUtils::toDouble(sIM);
}
// In theory, this should be an integer, but Sage currently cannot extract the number from all vendor spectrum IDs,
// so it writes the full ID as string
std::string sScanNr = row[to_idx.at("ScanNr")];
if (sSpecId != spec_id)
{
pids.resize(pids.size() + 1);
pids.back().setHigherScoreBetter(higher_score_better);
pids.back().setScoreType(score_name);
if (file_name_column_index >= 0) // FileName is optional; map_filename_to_idx is only populated when it is present
{
pids.back().setMetaValue(Constants::UserParam::ID_MERGE_INDEX, map_filename_to_idx.at(raw_file_name));
}
pids.back().setRT(StringUtils::toDouble(row[to_idx.at("retentiontime")]) * 60.0); // search engines typically write minutes (e.g., sage)
pids.back().setMetaValue("PinSpecId", sSpecId);
if (IM > 0.0) // Sage might annotate 0.0 if no IM is present
{
pids.back().setMetaValue(Constants::UserParam::IM, IM);
}
// Since ScanNr is the closest to help in identifying the spectrum in the file later on,
// we use it as spectrum_reference. Since it can be integer only or the complete
// vendor ID, you will need a lookup in case of number only later!!
pids.back().setSpectrumReference(sScanNr);
}
std::string sPeptide = row[to_idx.at("Peptide")];
const double score = StringUtils::toDouble(row[to_idx.at(score_name)]);
std::string target_decoy = StringUtils::toInt32(row[to_idx.at("Label")]) == 1 ? "target" : "decoy";
const std::string& sProteins = row[to_idx.at("Proteins")];
int rank = to_idx.count("rank") ? StringUtils::toInt32(row[to_idx.at("rank")]) : 1;
StringList accessions;
int charge = 0;
for (const auto& [name, z] : col_name_to_charge)
{
if (row[to_idx.at(name)] == "1")
{
charge = z;
break;
}
}
// all one-hot encoded charge columns are zero. Use value in the sage "z=other" column if it exists.
if (charge == 0 && found_sage_otherz_charge_column)
{
charge = StringUtils::toInt32(row[to_idx.at("z=other")]);
}
if (charge != 0)
{
pids.back().setMZ(StringUtils::toDouble(row[to_idx.at("ExpMass")]) / std::fabs(charge) + Constants::PROTON_MASS_U);
}
StringUtils::split(sProteins, ';', accessions);
// deduce decoy state from accessions if decoy_prefix is set
if (!decoy_prefix.empty())
{
bool dec = false;
bool tgt = false;
for (const auto& acc : accessions)
{
if (!(dec && tgt))
{
if (StringUtils::hasPrefix(acc, decoy_prefix))
{
dec = true;
}
else
{
tgt = true;
}
}
else
{
break;
}
}
if (tgt && dec)
{
target_decoy = "target+decoy";
}
else if (tgt)
{
target_decoy = "target";
}
else {
target_decoy = "decoy";
}
}
// needs to handle strings like: [+42]-MVLVQDLLHPTAASEAR, [+304.207]-ETC[+57.0215]RQLGLGTNIYNAER etc.
StringUtils::substitute(sPeptide, "]-", "]."); // we can parse [+42].MVLVQDLLHPTAASEAR
StringUtils::substitute(sPeptide, "-[", ".["); // we can parse MVLVQDLLHPTAASEAR.[+111]
AASequence aa_seq = AASequence::fromString(sPeptide);
applyPreferredModifications_(aa_seq, preferred_modifications);
PeptideHit ph(score, rank - 1, charge, std::move(aa_seq));
ph.setMetaValue("target_decoy", target_decoy);
for (const auto& name : found_extra_scores)
{
std::string value = row[to_idx.at(name)];
if (name == "ln(-poisson)" && value == "inf") value = "3.5"; // workaround for Sage
ph.setMetaValue(name, value);
}
// adding own meta values
if (SageAnnotation)
{
ph.setMetaValue("spectrum_q", StringUtils::toDouble(t_row[to_idx_t.at("spectrum_q")])); //TODO: check if column exists / SAGE specific treatment
}
ph.setMetaValue("DeltaMass", ( StringUtils::toDouble(row[to_idx.at("ExpMass")]) - StringUtils::toDouble(row[to_idx.at("CalcMass")])) );
// add annotations
if (SageAnnotation)
{
if (anno_mapping.contains(StringUtils::toInt32(sSpecId)))
{
// copy annotations from mapping to PeptideHit
vector<PeptideHit::PeakAnnotation> pep_vec;
for (const PeptideHit::PeakAnnotation& pep : anno_mapping[StringUtils::toInt32(sSpecId)])
{
pep_vec.push_back(pep) ;
}
ph.setPeakAnnotations(pep_vec);
}
}
// add link to protein (we only know the accession but not start/end, aa_before/after in protein at this point)
for (const std::string& accession : accessions)
{
ph.addPeptideEvidence(PeptideEvidence(accession));
}
pids.back().insertHit(std::move(ph));
}
return pids;
}
namespace
{
// StringUtils::toFloat(value.toString()) without the string for an int: its decimal digits parse to the float
// nearest to it, which is the conversion of the int
float isotopeErrorOf(const DataValue& value)
{
if (value.valueType() == DataValue::INT_VALUE) return static_cast<float>(static_cast<long long>(value));
return StringUtils::toFloat(value.toString());
}
// SpectrumLookup::extractScanNumber(id, RegularExpression(pattern), true) for every id, e.g. with the pattern
// SpectrumLookup::getRegExFromNativeID(first_id), without the regular expression when it is "<key>=(?<GROUP>\d+)"
// (all native ID types but the plain
// number): the number after the last "<key>=" that a digit follows (the matches cannot overlap: the keys hold no
// digit and none ends with its own beginning), converted with StringUtils::toInt32 as there (-1 if it fails).
class ScanNumberOf
{
public:
explicit ScanNumberOf(const std::string& pattern) :
pattern_(pattern)
{
static const std::string group = "=(?<GROUP>\\d+)";
if (pattern_.size() > group.size() && StringUtils::hasSuffix(pattern_, group))
{
key_ = pattern_.substr(0, pattern_.size() - group.size() + 1); // "<key>="
if (std::any_of(key_.begin(), key_.end(), [](char c) { return !std::isalpha(static_cast<unsigned char>(c)) && c != '='; }))
{
key_.clear(); // (only letters and '=': the cases above)
}
}
if (key_.empty()) regex_.assign(pattern_); // (compiled only if used)
}
Int operator()(const std::string& id) const
{
if (key_.empty()) return SpectrumLookup::extractScanNumber(id, regex_, /*no_error=*/true);
size_t last_begin = std::string::npos, last_end = 0;
for (size_t pos = id.find(key_); pos != std::string::npos; pos = id.find(key_, pos + 1))
{
size_t end = pos + key_.size();
while (end < id.size() && id[end] >= '0' && id[end] <= '9') ++end;
if (end > pos + key_.size())
{
last_begin = pos + key_.size();
last_end = end;
}
}
if (last_begin == std::string::npos) return -1;
try
{
return StringUtils::toInt32(id.substr(last_begin, last_end - last_begin));
}
catch (Exception::ConversionError&)
{
return -1;
}
}
private:
std::string pattern_;
RegularExpression regex_;
std::string key_;
};
}
struct PercolatorInfile::PinEnzyme_
{
std::string name; ///< isEnz_()'s name ("no_enzyme" if it knows none)
bool termini = true; ///< protein termini and the position after an initial Met count as cleavage sites
std::optional<ProteaseDigestion> digestion; ///< the rule of a ProteaseDB enzyme without a Percolator name
explicit PinEnzyme_(const std::string& enzyme)
{
std::string base = enzyme;
const auto strip = [&base](std::string_view modifier)
{
if (base.size() > modifier.size() && std::string_view(base).substr(base.size() - modifier.size()) == modifier)
{
base.resize(base.size() - modifier.size());
return true;
}
return false;
};
for (bool more = true; more;)
{
more = false;
if (strip("+keep_termini")) { termini = false; more = true; }
if (strip("+termini")) { more = true; } // (the default)
}
// lowercase without spaces, 'trypsin/p' as 'trypsinp', 'pepsina' as 'pepsin'
name = StringUtils::toLowered(base);
StringUtils::remove(name, ' ');
if (name == "trypsin/p") name = "trypsinp";
if (name == "pepsina") name = "pepsin";
static const std::set<std::string> pin_enzymes = {"elastase", "pepsin", "proteinasek", "thermolysin", "chymotrypsin",
"lys-n", "lys-c", "arg-c", "asp-n", "glu-c", "trypsin", "trypsinp"};
if (!pin_enzymes.contains(name)) name = "no_enzyme";
// an enzyme of ProteaseDB without a Percolator name (e.g. 'Lys-C/P', 'V8-E'): its own cleavage rule
if (name == "no_enzyme" && ProteaseDB::getInstance()->hasEnzyme(base))
{
digestion.emplace();
digestion->setEnzyme(base);
}
}
};
template <bool with_strings, typename Exists, typename Get, typename Put>
double PercolatorInfile::pinHitColumns_(const PeptideHit& hit, bool decoy, const std::string& spec_id, Int scan_number,
double exp_mass, double retention_time, const PinEnzyme_& enz, int min_charge, int max_charge,
Exists&& exists, Get&& get, Put&& put)
{
if constexpr (with_strings) put(PIN_SPEC_ID, spec_id);
put(PIN_SCAN_NR, scan_number);
put(PIN_LABEL, decoy ? -1 : 1);
const int charge = hit.getCharge();
const std::string unmodified_sequence = hit.getSequence().toUnmodifiedString();
double calc_mass;
if (!exists(LOOKUP_CALC_MASS))
{
calc_mass = hit.getSequence().getMZ(charge);
put(PIN_CALC_MASS, calc_mass);
}
else
{
calc_mass = getFeatureValue(get(LOOKUP_CALC_MASS), "CalcMass");
}
// The precursor isotope error (observed minus theoretical, in 13C spacings) is removed from the mass
// difference only. ExpMass and mass stay the observed precursor m/z, the same for every PSM of the spectrum:
// Percolator takes PSMs with the same ScanNr but different ExpMass for different spectra, so PSMs at
// different isotope errors would not compete with each other.
double isotope_corrected_mass = exp_mass;
if (exists(LOOKUP_ISOTOPE_ERROR_LEGACY)) // legacy MSGF+ adapter meta (<2.6)
{
const float isoErr = isotopeErrorOf(get(LOOKUP_ISOTOPE_ERROR_LEGACY));
isotope_corrected_mass -= (isoErr * Constants::C13C12_MASSDIFF_U) / charge;
}
else if (exists(LOOKUP_ISOTOPE_ERROR))
{
const float isoErr = isotopeErrorOf(get(LOOKUP_ISOTOPE_ERROR));
isotope_corrected_mass -= (isoErr * Constants::C13C12_MASSDIFF_U) / charge;
}
put(PIN_EXP_MASS, exp_mass);
const double delta_mass = isotope_corrected_mass - calc_mass;
put(PIN_DELTAMASS, delta_mass);
put(PIN_RETENTIONTIME, retention_time);
put(PIN_MASS, exp_mass);
put(PIN_SCORE, hit.getScore());
put(PIN_PEPLEN, static_cast<int>(unmodified_sequence.size()));
for (int i = min_charge; i <= max_charge; ++i)
{
put(PIN_CHARGE + (i - min_charge), charge == i);
}
// use first peptide evidence for flanking AAs
const PeptideEvidence& first_evidence = hit.getPeptideEvidences().front();
char aa_before = first_evidence.getAABefore();
char aa_after = first_evidence.getAAAfter();
// By default (PinEnzyme_::termini) OpenMS' protein-terminus marks '[' and ']' are Percolator's '-', which isEnz_
// counts as an enzymatic site, and so is the position after the initiator methionine (first evidence: aa_before M at
// start 1, the Met-clipped protein N-terminal peptide, as FragmentIndex and PeptideIndexer allow it): reversed decoy
// proteins rarely start with M, so without it enzN = 0 would be left (almost) only to Met-clipped targets, which the
// rescoring would learn as a target label (#10726). With "+keep_termini" the marks are compared as residues (enzN = 0
// at a protein N-terminus, enzC = 0 at a C-terminus not after a cleavage residue) and the M is a residue.
const bool met_clipped = enz.termini && aa_before == 'M' && first_evidence.getStart() == 1;
const char n_site = enz.termini && (aa_before == PeptideEvidence::N_TERMINAL_AA || met_clipped) ? '-' : aa_before;
const char c_site = enz.termini && aa_after == PeptideEvidence::C_TERMINAL_AA ? '-' : aa_after;
bool enzN, enzC;
Size enzInt;
if (enz.digestion)
{ // the peptide is a product of the enzyme at its N- (C-)terminus, when preceded (followed) by the flanking AA ('-' is
// a terminus, as for isEnz_()). An unknown residue (X) before the flanking AA serves the rules that look at two
// residues (proline endopeptidase cuts after HP, KP, RP): the evidence holds one.
const int length = static_cast<int>(unmodified_sequence.size());
const std::string with_before = std::string("X") + n_site + unmodified_sequence;
enzN = n_site == '-' || enz.digestion->isValidProduct(with_before, 2, length);
enzC = c_site == '-' || enz.digestion->isValidProduct(unmodified_sequence + c_site, 0, length);
// the sites inside the peptide, in the same context: all sites but those before its first residue
enzInt = enz.digestion->countInternalCleavageSites(with_before) - enz.digestion->countInternalCleavageSites(with_before.substr(0, 3));
}
else
{
enzN = isEnz_(n_site, StringUtils::prefix(unmodified_sequence, 1)[0], enz.name);
enzC = isEnz_(StringUtils::suffix(unmodified_sequence, 1)[0], c_site, enz.name);
enzInt = countEnzymatic_(unmodified_sequence, enz.name);
}
put(PIN_ENZ_N, enzN);
put(PIN_ENZ_C, enzC);
put(PIN_ENZ_INT, static_cast<int>(enzInt));
put(PIN_DM, delta_mass);
put(PIN_ABSDM, std::abs(delta_mass));
if constexpr (with_strings)
{
// Percolator-formatted peptide string with PTM brackets
aa_before = aa_before == '[' ? '-' : aa_before;
aa_after = aa_after == ']' ? '-' : aa_after;
std::string sequence;
sequence += aa_before;
sequence += ".";
sequence += hit.getSequence().toBracketString(false, true);
sequence += ".";
sequence += aa_after;
put(PIN_PEPTIDE, sequence);
StringList proteins;
for (const PeptideEvidence& pep : hit.getPeptideEvidences())
{
proteins.push_back(pep.getProteinAccession());
}
put(PIN_PROTEINS, ListUtils::concatenate(proteins, "\t"));
}
return calc_mass;
}
StringList PercolatorInfile::getPinColumnNames(int min_charge, int max_charge)
{
// PinColumn_ order: the fixed columns, then the charge{N} columns from min_charge on
StringList names{"SpecId", "ScanNr", "Label", "CalcMass", "ExpMass", "deltamass", "retentiontime", "mass", "score",
"peplen", "enzN", "enzC", "enzInt", "dm", "absdm", "Peptide", "Proteins"};
static_assert(PIN_CHARGE == 17, "a name per fixed PIN column (PinColumn_ order)");
for (int i = min_charge; i <= max_charge; ++i)
{
names.push_back("charge" + StringUtils::toStr(i));
}
return names;
}
namespace
{
// PeptideHit::getTargetDecoyType() with the meta value name looked up once (index): the lookup by name takes a
// lock on the registry, which threads would contend for. An unregistered name (index -1) exists on no hit.
PeptideHit::TargetDecoyType targetDecoyType(const PeptideHit& hit, UInt td_index)
{
if (td_index == UInt(-1) || !hit.metaValueExists(td_index))
{
return PeptideHit::TargetDecoyType::UNKNOWN;
}
const DataValue& value = hit.getMetaValue(td_index);
// the values PeptideIndexing writes, compared without a lower-cased copy (any other value as below)
static const DataValue decoy_value("decoy"), target_value("target"), target_decoy_value("target+decoy");
if (value == decoy_value) return PeptideHit::TargetDecoyType::DECOY;
if (value == target_value) return PeptideHit::TargetDecoyType::TARGET;
if (value == target_decoy_value) return PeptideHit::TargetDecoyType::TARGET_DECOY;
std::string td = StringUtils::toLowered(value.toString());
if (td == "decoy") return PeptideHit::TargetDecoyType::DECOY;
if (td == "target+decoy") return PeptideHit::TargetDecoyType::TARGET_DECOY;
if (td == "target") return PeptideHit::TargetDecoyType::TARGET;
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unknown value of meta value 'target_decoy'", td);
}
}
void PercolatorInfile::warnWithoutScanNumber_(const std::vector<std::string>& without_scan, const std::vector<char>& stamped)
{
// Percolator keeps the PSMs of one scan number in one cross-validation fold. The spectra without a scan number all
// get -1 and so share one fold, which can leave too few PSMs to train on (#10719: a native ID format that the scan
// number pattern of the first spectrum did not match).
const size_t spectra = static_cast<size_t>(std::count(stamped.begin(), stamped.end(), 1));
size_t count = 0;
const std::string* example = nullptr;
for (const std::string& reference : without_scan)
{
if (reference.empty()) continue;
if (example == nullptr) example = &reference;
++count;
}
if (count > 0)
{
OPENMS_LOG_WARN << "Warning: no scan number found in " << count << " of " << spectra
<< " spectrum references (e.g. '" << *example << "'). Their PSMs get ScanNr -1"
<< " and share one Percolator cross-validation fold." << endl;
}
}
std::set<std::pair<size_t, size_t>> PercolatorInfile::stampPinFeaturesOnHits(
PeptideIdentificationList& peptide_ids,
const std::string& enz,
int min_charge,
int max_charge)
{
PinFeatureMetaValueMap added_meta_values;
return stampPinFeaturesOnHits(peptide_ids, enz, min_charge, max_charge, added_meta_values);
}
namespace
{
// The ScanNr of the spectra. Percolator takes the PSMs of a spectrum file with the same ScanNr for one spectrum
// (and with the same ExpMass in target-decoy competition): train_best_positive keeps one positive per ScanNr, and
// the cross-validation splits by it. So ScanNr has to tell the spectra of a file apart:
// - Bruker TDF DDA spectra, one per precursor ("frame=F scan=S precursor=P", as BrukerTimsFile writes them), get
// the precursor P: S, the first ion mobility scan of the precursor, recurs in other frames.
// - Native IDs that number their spectra only within a part of the run get a running number per spectrum file,
// in the order of the PSMs: Bruker TDF "frame=F ... scan=S" without a precursor (a scan within a frame, e.g.
// diaPASEF), Waters "function=F process=P scan=S" (a scan within a function) and SCIEX "sample=1 period=1
// cycle=C experiment=E" (whose last number, the experiment, recurs in every cycle).
// - The others keep the number SpectrumLookup extracts (e.g. the scan number of Thermo native IDs, the frame
// number of "frame=F").
// Each spectrum file takes the scheme of its first spectrum: the spectra of a file have the same native ID format,
// but the files of one call may come from different instruments.
// The scan identifiers are those of PercolatorInfile::getScanIdentifier(), without whitespace.
class PinScanNumbers
{
public:
// the ScanNr of the spectra of one file
class FileNumbering
{
public:
explicit FileNumbering(const std::string& first_scan_identifier) :
number_(numberPattern_(first_scan_identifier))
{
if (StringUtils::hasPrefix(first_scan_identifier, "frame="))
{
if (first_scan_identifier.find("precursor=") == std::string::npos
&& first_scan_identifier.find("scan=") != std::string::npos)
{
running_scheme_ = true;
}
}
else if (StringUtils::hasPrefix(first_scan_identifier, "function=")
|| StringUtils::hasPrefix(first_scan_identifier, "sample="))
{
running_scheme_ = true;
}
}
// whether the spectra get running numbers (in their order: operator()), else numberOf()
bool running() const { return running_scheme_; }
Int operator()(const std::string& scan_identifier)
{
if (running_scheme_)
{
return running_.emplace(scan_identifier, static_cast<Int>(running_.size()) + 1).first->second;
}
return numberOf(scan_identifier);
}
// the number of the native ID or the precursor (no running number; thread-safe)
Int numberOf(const std::string& scan_identifier) const { return number_(scan_identifier); }
private:
static std::string numberPattern_(const std::string& first_scan_identifier)
{
if (StringUtils::hasPrefix(first_scan_identifier, "frame=")
&& first_scan_identifier.find("precursor=") != std::string::npos)
{
return R"(precursor=(?<GROUP>\d+))";
}
return SpectrumLookup::getRegExFromNativeID(first_scan_identifier);
}
bool running_scheme_ = false;
ScanNumberOf number_;
std::map<std::string, Int> running_; // the running number of each scan identifier
};
// the numbering of the file of a spectrum (its first spectrum chooses it)
FileNumbering& numbering(const std::string& file_identifier, const std::string& scan_identifier)
{
auto file = files_.find(file_identifier);
if (file == files_.end()) file = files_.emplace(file_identifier, FileNumbering(scan_identifier)).first;
return file->second;
}
private:
std::map<std::string, FileNumbering> files_; // by file identifier
};
// The ScanNr of every spectrum of @p peptide_ids, as PinScanNumbers gives them in the order of the spectra
// (stamping): the scan and file identifiers in parallel, the numbering of each file from its first spectrum, the
// running numbers in the order of the spectra and the other numbers in parallel. A spectrum whose identifiers
// cannot be made gets -1 and takes no part in the numbering (stamping stops at it with that error).
std::vector<Int> pinScanNumbers(const PeptideIdentificationList& peptide_ids)
{
const size_t n = peptide_ids.size();
std::vector<std::string> scan_ids(n), file_ids(n);
std::vector<char> ok(n, 0);
const UInt pin_file_origin_index = MetaInfoInterface::metaRegistry().getIndex("file_origin"); // (see getFileIdentifier())
const UInt pin_id_merge_index_index = MetaInfoInterface::metaRegistry().getIndex("id_merge_index");
#pragma omp parallel for schedule(dynamic, 256)
for (SignedSize si = 0; si < static_cast<SignedSize>(n); ++si)
{
const size_t i = static_cast<size_t>(si);
try
{
scan_ids[i] = PercolatorInfile::getScanIdentifier(peptide_ids[i], i + 1);
file_ids[i] = PercolatorInfile::getFileIdentifier(peptide_ids[i], pin_file_origin_index, pin_id_merge_index_index);
ok[i] = 1;
}
catch (...)
{
}
}
std::vector<Int> numbers(n, -1);
PinScanNumbers files;
std::vector<const PinScanNumbers::FileNumbering*> numbering_of(n, nullptr);
PinScanNumbers::FileNumbering* numbering = nullptr;
const std::string* file = nullptr; // the file of numbering
for (size_t i = 0; i < n; ++i)
{
if (!ok[i]) continue;
if (file == nullptr || *file != file_ids[i])
{
numbering = &files.numbering(file_ids[i], scan_ids[i]);
file = &file_ids[i];
}
numbering_of[i] = numbering;
if (numbering->running()) numbers[i] = (*numbering)(scan_ids[i]);
}
#pragma omp parallel for schedule(dynamic, 256)
for (SignedSize si = 0; si < static_cast<SignedSize>(n); ++si)
{
const PinScanNumbers::FileNumbering* of = numbering_of[static_cast<size_t>(si)];
if (of != nullptr && !of->running()) numbers[static_cast<size_t>(si)] = of->numberOf(scan_ids[static_cast<size_t>(si)]);
}
return numbers;
}
}
std::set<std::pair<size_t, size_t>> PercolatorInfile::stampPinFeaturesOnHits(
PeptideIdentificationList& peptide_ids,
const std::string& enz,
int min_charge,
int max_charge,
PinFeatureMetaValueMap& added_meta_values)
{
std::set<std::pair<size_t, size_t>> skipped;
added_meta_values.clear();
if (peptide_ids.empty()) return skipped;
const PinEnzyme_ rule(enz);
const std::vector<Int> scan_numbers = pinScanNumbers(peptide_ids); // ScanNr of the spectra
const UInt pin_file_origin_index = MetaInfoInterface::metaRegistry().getIndex("file_origin"); // (see getFileIdentifier())
const UInt pin_id_merge_index_index = MetaInfoInterface::metaRegistry().getIndex("id_merge_index");
// Per spectrum (PeptideIdentification): the meta values it added (hit index, keys), the values it overwrote (hit
// index, key, previous value), the hits it skipped (hit index, reason) and the error it stopped at, collected in
// spectrum order below. On an error, the spectra after the failing one are restored, as if the loop had stopped there.
enum SkipReason { NO_EVIDENCE, UNKNOWN_TARGET_DECOY };
std::vector<std::vector<std::pair<size_t, std::set<std::string>>>> added(peptide_ids.size());
std::vector<std::vector<std::tuple<size_t, std::string, DataValue>>> overwritten(peptide_ids.size());
std::vector<std::vector<std::pair<size_t, SkipReason>>> skipped_hits(peptide_ids.size());
std::vector<std::exception_ptr> errors(peptide_ids.size());
// The meta values by name index once all names below are registered (by the first stamped hit): looking names up
// takes a lock on the registry, which the threads would contend for. Unregistered names are looked up by name.
std::unordered_map<std::string, UInt> name_index;
auto exists = [&](const PeptideHit& hit, const std::string& key)
{
const auto it = name_index.find(key);
return it == name_index.end() ? hit.metaValueExists(key) : hit.metaValueExists(it->second);
};
auto get = [&](const PeptideHit& hit, const std::string& key) -> const DataValue&
{
const auto it = name_index.find(key);
return it == name_index.end() ? hit.getMetaValue(key) : hit.getMetaValue(it->second);
};
const std::vector<std::string> column_names = getPinColumnNames(min_charge, max_charge);