-
Notifications
You must be signed in to change notification settings - Fork 0
/
mzrecal.go
1695 lines (1531 loc) · 49.6 KB
/
mzrecal.go
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 2018 Rob Marissen.
// SPDX-License-Identifier: MIT
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"log"
"math"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/524D/mzrecal/internal/mzidentml"
"github.com/524D/mzrecal/internal/mzml"
"gonum.org/v1/gonum/optimize"
// flag "github.com/spf13/pflag"
)
// Program name and version, appended to software list in mzML output
const progName = "mzRecal"
var progVersion = `Unknown`
// Format of output, if it ever changes we should still be able to parse
// output from old versions
const outputFormatVersion = "1.0"
// Peptides m/z values within mergeMzTol are merged
const mergeMzTol = float64(1e-7)
const massProton = float64(1.007276466879)
const massH2O = float64(18.0105647)
// CV parameters names
const cvParamSelectedIonMz = `MS:1000744`
const cvIsolationWindowTargetMz = `MS:1000827`
const cvFTICRSpectrometer = `MS:1000079`
const cvTOFSpectrometer = `MS:1000084`
const cvOrbiTrapSpectrometer = `MS:1000484`
// The calibration types that we can handle
type calibType int
const (
calibNone calibType = iota
calibFTICR
calibTOF
calibOrbitrap
calibOffset
calibPoly1
calibPoly2
calibPoly3
calibPoly4
calibPoly5
)
const (
infoDefault = iota
infoSilent
infoVerbose
)
// Command line parameters
type params struct {
stage *int // Compute recal parameters (1), recalibrate (2) or both (0)
mzMLFilename *string
mzMLRecalFilename *string
mzIdentMlFilename *string
calFilename *string // Filename where JSON calibration parameters will be written
emptyNonCalibrated *bool // Empty MS2 spectra for which the precursor was not recalibrated
minCal *int // minimum number of calibrants a spectrum should have to be recalibrated
minPeak *float64 // minimum intensity of peaks to be considered for recalibrating
calPeaks *int // number of peaks per potential calibrant to consider
rtWindow *string // retention time window
lowRT float64 // lower rt window boundary
upRT float64 // upper rt window boundary
mzErrPPM *float64 // max mz error for trying a calibrant in calibration
mzTargetPPM *float64 // max mz error for accepting a calibrant in calibration
recalMethod *string // Recal method as specified by user
scoreFilter *string // PSM score filter to apply
charge *string // Charge range for calibrants
useIdentCharge bool // Use only charge as found in identification
minCharge int // min charge for calibrants
maxCharge int // max charge for calibrants
specFilter *string // Range of spectra to recalibrate
minSpecIdx int // Lowest spectrum index to recalibrate
maxSpecIdx int // Highest spectrum index to recalibrate
verbosity int // Verbosity of progress messages (infoDefault...)
args []string // Additional values passed on the command line
debug bool // Enable debug info (environment variable MZRECAL_DEBUG=1)
acceptProfile *bool // Accept non-peak picked profile spectra
}
// Calibrant as read from mzid file (or build in), with uncharged mass
type identifiedCalibrant struct {
name string
mass float64 // Uncharged mass
retentionTime float64
idCharge int // Charge state at identification
singleCharged bool // true if only charge state 1 should be considered
}
// m/z value for calibrant
type chargedCalibrant struct {
idCal *identifiedCalibrant
charge int // assumed charge for finding m/z peak
mz float64 // m/z value, computed from uncharged mass and charge
}
// Calibrants with same m/z
type calibrant struct {
chargedCals []chargedCalibrant
mz float64 // computed mz of the calibrant (copy of chargedCals[0])
mzMeasured float64 // mz of the best candidate peak
}
// recalParams contains recalibration parameters for each spectrum,
// in addition to generic recalibration data for the whole file
type recalParams struct {
// Version of recalibration parameters, used when storing/loading
// parameters in JSON format for different version of the software
MzRecalVersion string
RecalMethod string // Recalibration method used (TOF/FTICR/Orbitrap)
CalibShiftPPM float64 // RMS of m/z shift in ppm of calibrants that where used for calibration
SpecRecalPar []specRecalParams
}
type specDebugInfo struct {
CalsInRTWindow int
CalsInMassWindow int
CalsUsed int
TotalIonCurrent float64 `json:",omitempty"`
IonInjectionTime float64 `json:",omitempty"`
}
// specRecalParams contain the recalibration parameters for each
// spectrum. RecalMethod (from type recalParams) determines which
// computation must be done with these parameters to obtain the
// final calibration
type specRecalParams struct {
SpecIndex int
P []float64
DebugInfo []specDebugInfo `json:",omitempty"`
}
type scoreRange struct {
minScore float64 // Minimum score to accept
maxScore float64 // Maximum score to accept
priority int // Priority of the score, lowest is best
}
type scoreFilter map[string]scoreRange
type mzRange struct {
min float64
max float64
}
var fixedCalibrants = []identifiedCalibrant{
// cyclosiloxanes, H6nC2nOnSin
{
name: `cyclosiloxane6`,
mass: 444.1127481,
retentionTime: -math.MaxFloat64, // Indicates any retention time
idCharge: 1,
singleCharged: true,
},
{
name: `cyclosiloxane7`,
mass: 518.1315394,
retentionTime: -math.MaxFloat64,
idCharge: 1,
singleCharged: true,
},
{
name: `cyclosiloxane8`,
mass: 592.1503308,
retentionTime: -math.MaxFloat64,
idCharge: 1,
singleCharged: true,
},
{
name: `cyclosiloxane9`,
mass: 666.1691221,
retentionTime: -math.MaxFloat64,
idCharge: 1,
singleCharged: true,
},
{
name: `cyclosiloxane10`,
mass: 740.1879134,
retentionTime: -math.MaxFloat64,
idCharge: 1,
singleCharged: true,
},
{
name: `cyclosiloxane11`,
mass: 814.2067048,
retentionTime: -math.MaxFloat64,
idCharge: 1,
singleCharged: true,
},
{
name: `cyclosiloxane12`,
mass: 888.2254961,
retentionTime: -math.MaxFloat64,
idCharge: 1,
singleCharged: true,
},
}
// Masses of amino acids (minus H2O)
var aaMass = map[rune]float64{
'A': 71.0371138,
'C': 103.0091848,
'D': 115.0269430,
'E': 129.0425931,
'F': 147.0684139,
'G': 57.0214637,
'H': 137.0589119,
'I': 113.0840640,
'K': 128.0949630,
'L': 113.0840640,
'M': 131.0404849,
'N': 114.0429274,
'P': 97.0527638,
'O': 237.1477269, // Pyrrolysine
'Q': 128.0585775,
'R': 156.1011110,
'S': 87.0320284,
'T': 101.0476785,
'U': 144.9595902, // Selenocysteine
'V': 99.0684139,
'W': 186.0793129,
'Y': 163.0633285,
}
var ErrRangeSpec = errors.New("invalid range specified")
// Data processing steps to be added to mzML file
var mzRecalProcessing mzml.DataProcessing = mzml.DataProcessing{
ID: progName,
ProcessingMeth: []mzml.ProcessingMethod{
{
Count: 0,
SoftwareRef: progName,
CvPar: []mzml.CVParam{
{
Accession: `MS:1001485`,
Name: `m/z calibration`,
},
},
},
{
Count: 1,
SoftwareRef: progName,
CvPar: []mzml.CVParam{
{
Accession: `MS:1000780`,
Name: `precursor recalculation`,
},
},
},
},
}
// Parse string like "-12:6" into 2 values, -12 and 6
// Parameters min and max are the "default" min/max values,
// when a value is not specified (e.g. "-12:"), the default is assigned
func parseIntRange(r string, min int, max int) (int, int, error) {
re := regexp.MustCompile(`\s*(\-?\d*):(\-?\d*)`)
m := re.FindStringSubmatch(r)
minOut := min
maxOut := max
if len(m) >= 2 && m[1] != "" {
minOut, _ = strconv.Atoi(m[1])
if minOut < min {
minOut = min
}
}
if len(m) >= 3 && m[2] != "" {
maxOut, _ = strconv.Atoi(m[2])
if maxOut > max {
maxOut = max
}
}
var err error
if minOut > maxOut {
err = ErrRangeSpec
minOut = maxOut
}
return minOut, maxOut, err
}
// Parse string like "-12.01e1:+6" into 2 values, -120.1 and 6.0
// Parameters min and max are the "default" min/max values,
// when a value is not specified (e.g. "-12.01e1:"), the default is assigned
func parseFloat64Range(r string, min float64, max float64) (
float64, float64, error) {
re := regexp.MustCompile(`\s*([-+]?[0-9]*\.?[0-9]*([eE][-+]?[0-9]+)?):([-+]?[0-9]*\.?[0-9]*([eE][-+]?[0-9]+)?)`)
m := re.FindStringSubmatch(r)
minOut := min
maxOut := max
if len(m) >= 2 && m[1] != "" {
minOut, _ = strconv.ParseFloat(m[1], 64)
if minOut < min {
minOut = min
}
}
if len(m) >= 4 && m[3] != "" {
maxOut, _ = strconv.ParseFloat(m[3], 64)
if maxOut > max {
maxOut = max
}
}
var err error
if minOut > maxOut {
err = ErrRangeSpec
minOut = maxOut
}
return minOut, maxOut, err
}
// Compute the lowest isotope mass of the peptide
func pepMass(pepSeq string) (float64, error) {
m := massH2O
for _, aa := range pepSeq {
aam, ok := aaMass[aa]
if !ok {
return 0.0, errors.New("invalid amino acid")
}
m += aam
}
return m, nil
}
// This function creates a slice with potential calibrants
// Calibrants are obtained from 2 sources:
// - Identified peptides (from mzid file)
// - Build-in list of fixed calibrants (cyclosiloxanes)
// Identified peptides are only used if they pass the score filter
// For each calibrant, it:
// - computes the mass of the lightest isotope
// - get the retention name, retentionTime, spectrum
func makeCalibrantList(mzIdentML *mzidentml.MzIdentML, scoreFilt scoreFilter,
par params) ([]identifiedCalibrant, error) {
// Create slice for the number of calibrants that we expect to have
cals := make([]identifiedCalibrant, 0, mzIdentML.NumIdents()+len(fixedCalibrants))
for i := 0; i < mzIdentML.NumIdents(); i++ {
ident, err := mzIdentML.Ident(i)
if err != nil {
return nil, err
}
if ident.RetentionTime < 0 {
return nil, errors.New("no valid retention time for identification " + ident.PepID)
}
// log.Printf("indent %+v\n", ident)
scoreOK := false
curPrio := math.MaxInt32
for _, cv := range ident.Cv {
// Check if the CV accession number or CV name matches scorefilter
filt, ok := scoreFilt[cv.Accession]
if !ok {
filt, ok = scoreFilt[cv.Name]
}
if ok {
if filt.priority < curPrio {
var score float64
score, err = strconv.ParseFloat(cv.Value, 64)
if err != nil {
return nil, errors.New("Invalid score value " + cv.Value)
}
scoreOK = score >= filt.minScore && score <= filt.maxScore
}
}
}
if scoreOK {
var cal identifiedCalibrant
m, err := pepMass(ident.PepSeq)
if err == nil { // Skip if mass cannot be computed
cal.name = ident.PepID
cal.retentionTime = ident.RetentionTime
cal.idCharge = ident.Charge
cal.singleCharged = false
cal.mass = m + ident.ModMass
cals = append(cals, cal)
}
// } else {
// log.Print(ident.PepID + " does not match score filter.")
}
}
// log.Print(len(cals), " of ", mzIdentML.NumIdents(), " identifications usable for calibration.")
if len(cals) == 0 {
log.Print("No identified spectra will be used as calibrant. Is the specified scorefilter applicable for this file?")
}
cals = append(cals, fixedCalibrants...)
sort.Slice(cals,
func(i, j int) bool { return cals[i].retentionTime < cals[j].retentionTime })
return cals, nil
}
func calibsInRtWindows(rtMin, rtMax float64, allCals []identifiedCalibrant) ([]identifiedCalibrant, error) {
// Find the indices of the calibrants within the retention time window
i1 := sort.Search(len(allCals), func(i int) bool { return allCals[i].retentionTime >= rtMin })
i2 := sort.Search(len(allCals), func(i int) bool { return allCals[i].retentionTime > rtMax })
// Find calibrants that elute at all retention times
// These have elution time -math.MaxFloat64 and are located at the
// start of the list of calibrants. Thus, to search them, we simply
// search from the start for calibrants with elution time -math.MaxFloat64
var i3 int
for i3 = 0; i3 < len(allCals) && allCals[i3].retentionTime == -math.MaxFloat64; i3++ {
}
var cals = make([]identifiedCalibrant, 0, (i2-i1)+i3)
cals = append(cals, allCals[i1:i2]...)
cals = append(cals, allCals[0:i3]...)
return cals, nil
}
// makeChargedCalibrants computes the m/z value for the calibrants
// defines in parameter specCals for all selected charges states.
// Equal m/z values (within numerical precision) are merged
func makeChargedCalibrants(specCals []identifiedCalibrant, par params) ([]calibrant, error) {
// Make slice with mz values for all calibrants
// For efficiency, pre-allocate (more than) enough elements
chargedCalibrants := make([]chargedCalibrant, 0,
len(specCals)*(par.maxCharge-par.minCharge+1))
for j, cal := range specCals {
// log.Printf("Calibrating spec %d, rt %f, calibrants: %+v\n", i, retentionTime, cal)
if cal.singleCharged {
chargedCalibrants = append(chargedCalibrants, newChargedCalibrant(1, &specCals[j]))
} else {
if par.useIdentCharge {
chargedCalibrants = append(chargedCalibrants, newChargedCalibrant(cal.idCharge, &specCals[j]))
} else {
for charge := par.minCharge; charge <= par.maxCharge; charge++ {
chargedCalibrants = append(chargedCalibrants, newChargedCalibrant(charge, &specCals[j]))
}
}
}
}
calibrants := mergeSameMzCals(chargedCalibrants)
return calibrants, nil
}
// mergeSameMzCals merges all calibrants that have the same m/z or
// nearly the same m/z. The m/z of the first calibrant that was encountered
// is retained. The list of calibrants with their charge state is appended
// to the final list of calibrants.
func mergeSameMzCals(chargedCalibrants []chargedCalibrant) []calibrant {
mcals := make([]calibrant, 0, len(chargedCalibrants))
// sort calibrants by mass
sort.Slice(chargedCalibrants,
func(i, j int) bool { return chargedCalibrants[i].mz < chargedCalibrants[j].mz })
prevMz := float64(-1)
for _, cal := range chargedCalibrants {
if math.Abs(cal.mz-prevMz) < mergeMzTol {
mcals[len(mcals)-1].chargedCals = append(mcals[len(mcals)-1].chargedCals, cal)
} else {
var newCal calibrant
newCal.chargedCals = make([]chargedCalibrant, 1)
newCal.chargedCals[0] = cal
newCal.mz = cal.mz
mcals = append(mcals, newCal)
prevMz = cal.mz
}
}
return mcals
}
func newChargedCalibrant(charge int, idCal *identifiedCalibrant) chargedCalibrant {
var chargedCal chargedCalibrant
fCharge := float64(charge)
chargedCal.mz = (idCal.mass + fCharge*massProton) / fCharge
chargedCal.idCal = idCal
chargedCal.charge = charge
return chargedCal
}
func instrument2RecalMethod(mzML *mzml.MzML) (calibType, string, error) {
instruments, err := mzML.MSInstruments()
if err != nil {
if err == mzml.ErrNoInstrumentConfiguration {
log.Println("WARNING: Can't determine instrument type because mzML file doesn't contain obligatory 'instrumentConfigurationList', using POLY2 recalibration")
return calibPoly2, `POLY2`, nil
}
return 0, ``, err
}
for _, instr := range instruments {
switch instr {
case cvFTICRSpectrometer:
return calibFTICR, `FTICR`, nil
case cvTOFSpectrometer:
return calibTOF, `TOF`, nil
case cvOrbiTrapSpectrometer:
return calibOrbitrap, `Orbitrap`, nil
}
}
// FIXME: Implement other instruments
log.Println("WARNING: No recalibration method for instrument, using POLY2 recalibration")
return calibPoly2, `POLY2`, nil
}
func recalMethodStr2Int(recalMethodStr string) (calibType, error) {
var recalMethod calibType
switch strings.ToUpper(recalMethodStr) {
case `FTICR`:
recalMethod = calibFTICR
case `TOF`:
recalMethod = calibTOF
case `ORBITRAP`:
recalMethod = calibOrbitrap
case `OFFSET`:
recalMethod = calibOffset
case `POLY1`:
recalMethod = calibPoly1
case `POLY2`:
recalMethod = calibPoly2
case `POLY3`:
recalMethod = calibPoly3
case `POLY4`:
recalMethod = calibPoly4
case `POLY5`:
recalMethod = calibPoly5
default:
return 0, errors.New("Unknown recalibration method: " + recalMethodStr)
}
return recalMethod, nil
}
// Get the minimum and maximum mz in a slice of peaks
// Potentially, these values could be obtained from the corresponding
// tags in the mzML file, be we don't want te depend on that.
func mzRangePeaks(peaks []mzml.Peak) mzRange {
var r mzRange
if len(peaks) > 0 {
r.min = peaks[0].Mz
r.max = peaks[0].Mz
for _, p := range peaks {
m := p.Mz
if m < r.min {
r.min = m
}
if m > r.max {
r.max = m
}
}
}
return r
}
// Remove calibrants that are outside a given mzrange
// We modify the slice of calibrants in place, hence it is
// passed as a pointer
func filterMzCalibs(calibrants *[]calibrant, r mzRange) {
if calibrants != nil {
k := int(0) // Index of calibrants that we want to keep
for i, c := range *calibrants {
if c.mz >= r.min && c.mz <= r.max {
// Calibrant is mz range
// If calibrant is not in range, k is not incremented,
// so it will be removed/overwritten
// Optimization: only copy is source and destination are the different
if k < i {
(*calibrants)[k] = (*calibrants)[i]
}
k++
}
}
*calibrants = (*calibrants)[:k] // Change slice length
}
}
// genDebugInfo returns info that can be added to the JSON output
// for debugging/clarifying the recalibration
func genDebugInfo(calibrants []calibrant, matchingCals []calibrant,
calsUsed []calibrant, specIdx int, mzML *mzml.MzML) []specDebugInfo {
debugInfo := make([]specDebugInfo, 1)
debugInfo[0].CalsInRTWindow = len(calibrants)
debugInfo[0].CalsInMassWindow = len(matchingCals)
debugInfo[0].CalsUsed = len(calsUsed)
iit, _ := mzML.IonInjectionTime(specIdx)
if !math.IsNaN(iit) {
debugInfo[0].IonInjectionTime = iit
}
tic, _ := mzML.TotalIonCurrent(specIdx)
if !math.IsNaN(tic) {
debugInfo[0].TotalIonCurrent = tic
}
return debugInfo
}
func recalErrRel(mzCalibrant calibrant, recalMethod calibType, p []float64) float64 {
return (mzCalibrant.mz - mzRecal(mzCalibrant.mzMeasured, recalMethod, p)) / mzCalibrant.mz
}
// Remove calibrants with relative error outside range
func removeOutliersPPM(mzCalibrants []calibrant, recalMethod calibType, p []float64,
olLowLim float64, olHighLim float64) ([]calibrant, bool) {
acceptedIdx := 0
satisfied := false
for _, mzCalibrant := range mzCalibrants {
relErr := recalErrRel(mzCalibrant, recalMethod, p)
if (relErr >= olLowLim) && (relErr <= olHighLim) {
mzCalibrants[acceptedIdx] = mzCalibrant
acceptedIdx++
}
}
// If all (remaining) calibrants are accepted, we are done
if acceptedIdx == len(mzCalibrants) {
satisfied = true // all calibrants < internal_calibration_target
}
mzCalibrants = mzCalibrants[:acceptedIdx] // Shorten list of calibrants if needed
return mzCalibrants, satisfied
}
// Remove calibrants that are outliers according to mzQC specification mzQC
// (The HUPO-PSI Quality Control Working Group, 2020)
func removeOutliersMzQC(mzCalibrants []calibrant, recalMethod calibType, p []float64, debug bool) ([]calibrant, bool) {
satisfied := false
// Sort calibrants by error
// FIXME: speed up by computing errors for each calibrant outside sort
sort.Slice(mzCalibrants, func(i, j int) bool {
mzCali := mzRecal(mzCalibrants[i].mzMeasured, recalMethod, p)
mzCalj := mzRecal(mzCalibrants[j].mzMeasured, recalMethod, p)
erri := mzCalibrants[i].mz - mzCali
errj := mzCalibrants[j].mz - mzCalj
return erri < errj
})
// mzQC definition of outliers uses Q1, Q3 and IQR of the distribution,
// compute them here
var q1i1, q1i2 int
// Special case: for < 6 calibrants, adapt method for mzQC to work well
if len(mzCalibrants) < 6 {
// For less than 4 calibrants, we omit outlier detection
if len(mzCalibrants) < 4 {
return mzCalibrants, true
} else {
// For 4 to 5 calibrants, we use for Q1 and Q3 the values values 1 position from extreme
q1i1 = 1
q1i2 = 1
}
} else {
nq1 := len(mzCalibrants) / 2 // count of samples that Q1 is based on (odd numbers are rounded down)
q1i1 = (nq1 - 1) / 2 // index 1 of the median of upper half
q1i2 = nq1 / 2 // index 2 of the median of upper half (for odd number of samples in upper half)
}
q1 := (recalErrRel(mzCalibrants[q1i1], recalMethod, p) + recalErrRel(mzCalibrants[q1i2], recalMethod, p)) / 2
q3i1 := len(mzCalibrants) - q1i1 - 1
q3i2 := len(mzCalibrants) - q1i2 - 1
q3 := (recalErrRel(mzCalibrants[q3i1], recalMethod, p) + recalErrRel(mzCalibrants[q3i2], recalMethod, p)) / 2
iqr := q3 - q1
// Compute outlier limits according to mzQC definition
olLowLim := q1 - 1.5*iqr
olHighLim := q3 + 1.5*iqr
if debug {
for j, mzCalibrant := range mzCalibrants {
relErr := recalErrRel(mzCalibrant, recalMethod, p)
s1 := ' '
if (j == q1i1) || (j == q3i1) {
s1 = '*'
}
s2 := ' '
if (j == q1i2) || (j == q3i2) {
s2 = '*'
}
fmt.Printf("%d rel_err=%e %c%c\n", j, relErr, s1, s2)
}
}
// Remove outliers
mzCalibrants, satisfied = removeOutliersPPM(mzCalibrants, recalMethod, p, olLowLim, olHighLim)
if debug {
fmt.Printf("q1_i1=%d q1_i2=%d q3_i1=%d q3_i2=%d q1=%e q3=%e iqr=%e ol_low_lim=%e ol_high_lim=%e\n",
q1i1, q1i2, q3i1, q3i2, q1, q3, iqr, olLowLim, olHighLim)
}
return mzCalibrants, satisfied
}
// Compute recalibration parameters that best fit the calibrants
func recalibrateSpec(specIndex int, recalMethod calibType,
mzCalibrants []calibrant, par params) (
specRecalParams, []calibrant, error) {
var specRecalPar specRecalParams
specRecalPar.SpecIndex = specIndex
var p []float64
// We use the gonum.optimize package to find the best parameters:
// https://pkg.go.dev/gonum.org/v1/gonum/optimize#Minimize
problem := optimize.Problem{
Func: func(x []float64) float64 {
sumOfResiduals := float64(0.0)
for _, cal := range mzCalibrants {
mzCalib := mzRecal(cal.mzMeasured, recalMethod, x)
diff := mzCalib - cal.mz
sumOfResiduals += diff * diff
}
return math.Sqrt(sumOfResiduals)
},
}
satisfied := false
for !satisfied && (len(mzCalibrants) >= *par.minCal) {
// Set initial calibration constants
// For all calibration methods, the initial value of the parameter
// with index one is 1.0, the other parameters are 0.0
nrCalPars := getNrCalPars(recalMethod)
pIn := make([]float64, nrCalPars)
if nrCalPars > 1 {
pIn[1] = 1.0
}
// Compute parameters for optimal fit
calParams, err := optimize.Minimize(problem, pIn, nil, nil)
if err != nil {
return specRecalPar, nil, err
}
p = calParams.X
if *par.mzTargetPPM > 0.0 {
// If fixed PPM error is defined,
// remove outliers that are out of range
mzCalibrants, satisfied =
removeOutliersPPM(mzCalibrants, recalMethod, p,
-(*par.mzTargetPPM), *par.mzTargetPPM)
} else {
mzCalibrants, satisfied =
removeOutliersMzQC(mzCalibrants, recalMethod, p, par.debug)
}
}
if !satisfied {
return specRecalPar, nil, nil
}
specRecalPar.P = p
return specRecalPar, mzCalibrants, nil
}
func mzRecalPolyN(mzMeas float64, p []float64, degree int) float64 {
mp := float64(1.0)
mzCalib := float64(0.0)
for i := 0; i <= degree; i++ {
mzCalib += p[i] * mp
mp *= mzMeas
}
return mzCalib
}
// Compute the recalibrated mz according to calibration parameters
func mzRecal(mzMeas float64, recalMethod calibType, p []float64) float64 {
var mzCalib float64
switch recalMethod {
case calibFTICR:
// mzCalib = Ca/((1/mzMeas)-Cb)
mzCalib = (p[1]) / ((1 / mzMeas) - (p[0]))
case calibTOF:
mzCalib = p[2]*math.Sqrt(mzMeas) + p[1]*mzMeas + p[0]
case calibOrbitrap:
{
// mzCalib = A/((f-B)^2) =
// A / ((1/sqrt(mzMeas))-B)^2
a := p[1]
b := p[0]
freq := float64(1.0) / math.Sqrt(mzMeas)
fb := freq - b
mzCalib = a / (fb * fb)
}
case calibOffset:
mzCalib = mzMeas + p[0]
case calibPoly1:
mzCalib = mzRecalPolyN(mzMeas, p, 1)
case calibPoly2:
mzCalib = mzRecalPolyN(mzMeas, p, 2)
case calibPoly3:
mzCalib = mzRecalPolyN(mzMeas, p, 3)
case calibPoly4:
mzCalib = mzRecalPolyN(mzMeas, p, 4)
case calibPoly5:
mzCalib = mzRecalPolyN(mzMeas, p, 5)
default:
mzCalib = mzMeas
}
return mzCalib
}
// getNrCalPars returns the number of calibration parameters
// for the given calibration method
func getNrCalPars(recalMethod calibType) int {
switch recalMethod {
case calibFTICR:
return 2
case calibTOF:
return 3
case calibOrbitrap:
return 2
case calibOffset:
return 1
case calibPoly1:
return 2
case calibPoly2:
return 3
case calibPoly3:
return 4
case calibPoly4:
return 5
case calibPoly5:
return 6
}
return 0
}
// calibQC contains data to keep track of the calibration quality
// To measure the quality of the recalibration, we use the Root Mean Square
// (RMS) of the PPM mass shifts of the calibrants that were used for recalibration
// Therefore, we must maintain the total number of calibrants and the
// square of the PPM mass error
type calibQC struct {
nrRecalibrated int
sumRMSErr float64
}
func updateCalibQC(calsUsed []calibrant, recalMethod calibType, specRecalPar specRecalParams, calQC *calibQC) {
sumSqErr := float64(0.0)
nrCalibrants := 0
for _, cal := range calsUsed {
mzCalib := mzRecal(cal.mzMeasured, recalMethod, specRecalPar.P)
massShift := mzCalib - cal.mz
massShiftPPM := massShift / cal.mz * 1e6
nrCalibrants++
sumSqErr += massShiftPPM * massShiftPPM
}
if nrCalibrants > 0 {
rmsErr := math.Sqrt(sumSqErr / float64(nrCalibrants))
calQC.sumRMSErr += rmsErr
calQC.nrRecalibrated++
}
}
// computeRecalSpec executes recalibration steps for a single spectrum
func computeRecalSpec(mzML *mzml.MzML, idCals []identifiedCalibrant,
specIdx int, recalMethod calibType, calQC *calibQC, par params) (specRecalParams, error) {
var specRecalPar specRecalParams
var err error
// Get the retention time of the current MS1 spectrum
retentionTime, err := mzML.RetentionTime(specIdx)
if err != nil {
return specRecalPar, err
}
// Get the uncharged masses of potential calibrants in the retention
// time window
specCals, err := calibsInRtWindows(retentionTime+par.lowRT,
retentionTime+par.upRT, idCals)
if err != nil {
return specRecalPar, err
}
// Get the m/z values of potential calibrants, merging equal values
calibrants, err := makeChargedCalibrants(specCals, par)
if err != nil {
return specRecalPar, err
}
// Get the MS1 peaks
peaks, err := mzML.ReadScan(specIdx)
if err != nil {
log.Fatalf("computeRecalSpec ReadScan failed for spectrum %d: %v",
specIdx, err)
}
// Remove potential calibrants outside of measured range
r := mzRangePeaks(peaks)
filterMzCalibs(&calibrants, r)
// Get the calibrants that match significant MS1 peaks
matchingCals := calibrantsMatchPeaks(peaks, calibrants, par)
// Compute recalibration constants
specRecalPar, calsUsed, err := recalibrateSpec(specIdx, recalMethod,
matchingCals, par)
if err != nil {
log.Printf("computeRecalSpec calibration failed for spectrum %d: %v",
specIdx, err)
}
// Compute the RMS mass shift of the calibrants that where used for recalibration
updateCalibQC(calsUsed, recalMethod, specRecalPar, calQC)
if par.debug {
specRecalPar.DebugInfo = genDebugInfo(calibrants, matchingCals,
calsUsed, specIdx, mzML)
}
debugLogSpecs(specIdx, mzML.NumSpecs(), retentionTime, peaks, matchingCals, par,
calsUsed, recalMethod, specRecalPar)
debugRegisterCalUsed(specIdx, calsUsed)
return specRecalPar, nil
}
var warnProfile = true // FIXME: remove after peak picking is implemented
// computeRecal computes the recalibration parameters for the whole mzML file
func computeRecal(mzML *mzml.MzML, idCals []identifiedCalibrant, par params) (recalParams, error) {
var recal recalParams
var err error
var recalMethod calibType
recal.MzRecalVersion = outputFormatVersion
if *par.recalMethod == `` {
recalMethod, recal.RecalMethod, err = instrument2RecalMethod(mzML)
} else {
recalMethod, err = recalMethodStr2Int(*par.recalMethod)
recal.RecalMethod = *par.recalMethod
}
if err != nil {
return recal, err
}
// Update the minimum number of calibrants
// according to the calibration method
nrCalPars := getNrCalPars(recalMethod)
if *par.minCal == 0 {
*par.minCal = nrCalPars + 1
} else {
if *par.minCal < nrCalPars {
*par.minCal = nrCalPars
}
}
var calQC calibQC
numSpecs := mzML.NumSpecs()
for i := 0; i < numSpecs; i++ {
// Only MS1 spectra are used for recalibration
msLevel, err := mzML.MSLevel(i)
if err != nil {
return recal, err
}
if msLevel == 1 {
// Ensure that the spectra are centroided
centroid, err := mzML.Centroid(i)
if err != nil {
return recal, err
}
if !centroid {
// (unless overruled by option acceptprofile)
if !*par.acceptProfile {
return recal, errors.New(`input mzML file must contain centroid data, not profile data`)
} else if par.verbosity != infoSilent && warnProfile {
log.Println(`Warning: input contains non-peak picked (profile) spectra. This is currently not handled well by mzRecal.`)
warnProfile = false
}
}
specRecalPar, err := computeRecalSpec(mzML, idCals, i, recalMethod, &calQC, par)
if err != nil {
return recal, err
}
recal.SpecRecalPar = append(recal.SpecRecalPar, specRecalPar)
}
}
recal.CalibShiftPPM = calQC.sumRMSErr / float64(calQC.nrRecalibrated)
debugListUnusedCalibrants(idCals)
return recal, nil
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
// Return a slice with only the peaks that we want to base the calibration on
// Only the most intense peaks are used, filtered by number of potential calibrants