-
Notifications
You must be signed in to change notification settings - Fork 1
/
basic_analysis.py
1842 lines (1727 loc) · 81.8 KB
/
basic_analysis.py
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
from __future__ import print_function
import os
import sys
import time
import warnings
import argparse
import collections
import datetime
import struct
import math
import numpy
import scipy
from matplotlib import pyplot
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
try:
import lmfit
SVM = lmfit.models.SkewedVoigtModel()
except (ImportError, ModuleNotFoundError) as e:
lmfit = None
print("Warning: Will produce less precise results as lmfit is not installed.", file=sys.stderr)
# MassLynx API
if sys.version_info.major >= 3 and sys.version_info.minor >= 8:
# on these versions, the path to the dll needs to be added explicitly
os.add_dll_directory(os.path.dirname(__file__))
try:
import MassLynxRawInfoReader as mlrir
import MassLynxRawScanReader as mlrsr
except (ImportError, ModuleNotFoundError) as e:
cwd = os.getcwd()
os.chdir(os.path.dirname(__file__))
sys.path.append(os.path.dirname(__file__))
import MassLynxRawInfoReader as mlrir
import MassLynxRawScanReader as mlrsr
os.chdir(cwd)
# mine
import peak_picking
#################
# GENERAL STUFF #
#################
TIME_FMT = '%d-%b-%Y %H:%M:%S'
class ProgressBar(object):
def __init__(self, total, width=80, name='Progress Bar'):
self._name = name
self.total = float(total)
self.cur_real = 0.
self.cur = 0
self.width = width
self.__fin = False
self.__started = time.time()
print(name)
print('v'*width)
def progress(self, value):
if self.__fin or value <= self.cur_real:
return
self.cur_real = value
relative = value / self.total
num_hashtags = int(relative * self.width)
if num_hashtags > self.cur:
to_draw = num_hashtags - self.cur
self.cur = num_hashtags
sys.stdout.write('#'*to_draw)
sys.stdout.flush()
if relative >= 1.:
self.finish()
def progress_one(self):
self.progress(self.cur_real + 1)
def progress_some(self, value):
self.progress(self.cur_real + value)
def finish(self):
if not self.__fin:
print()
print('^'*self.width)
print("%s ran for %.1f Seconds" % (self._name, time.time() - self.__started))
self.__fin = True
##################
# LC-MS ANALYSIS #
##################
def magic_protein_peak_number_estimation(mass):
"""
This "magic" function estimates with pretty high precision the number
of isotope peaks arising from a given protein or peptide.
It is based on:
(1) the empirical observation that carbon atoms account for roughly 53%
of a protein mass, and thefore #C = ~0.53 / 12 * mass
(2) the abundance of 13C atoms being ~1.11%
(3) the assumption that peaks of less than 0.1% of the total ions are
not really observable or interesting
(4) a weird function that I fit to data without much explanation :)
@param mass: The mass of the peptide/protein in Da
@type mass: number
@return: Estimated number of detectable isotope peaks
@rtype: int
"""
return int(round(15.2 + 5.55e-4 * (mass - 18400 * numpy.exp(-mass / 33300))))
def predict_peak_widths(mass, z, num_mzs, base_peak_width):
"""
Based on the mass, we can predict how many isotopic peaks would be
detectable; based on this number and the charge, as well as the base
peak width of the instrument, we can also predict the width of the
observable peak/peak-set.
This is very useful when one wants to integrate all the ion intensities
corresponding to a single orignal mass.
@param mass: The mass of the peptide/protein in Da
@type mass: number
@param z: The charge of the (first, i.e. highest z = lowest m/z) peak
@type z: int
@param num_mzs: Total number of peaks
@type num_mzs: int
@param base_peak_width: The base peak width expected, to decide the
margins around each m/z value to look at
@type base_peak_width: float
@return: expected width of each of the num_mzs peaks
@rtype: list of float
"""
exp_num_peaks = magic_protein_peak_number_estimation(mass)
if z >= 0.3 / base_peak_width:
# peak overlap is expected
return [(exp_num_peaks + 1) / (z - i)
+ base_peak_width
for i in range(num_mzs)]
else:
# peak overlap is NOT expected, just use base peak width
return [base_peak_width] * num_mzs
def naive_predict_peaks(mass, z_max, nz, base_peak_width = 0.15):
"""
A naive prediction of the locations and widths of M/z peaks for a given
macromolecule (or at least protein) mass in an ESI experiment.
Simply calculates (M + z*H) / z for a given range of z values,
and uses other functions to predict the widths.
On Xevo LC-MS, the default base peak width of 0.15 Da gives pretty
incredible predictions of observed peaks.
@param mass: The mass of the macromolecule (M) in daltons
@type mass: number
@param z_max: Maximal z value to predict for
@type z_max: int
@param nz: Number of z values to predict for
@type nz: int
@param base_peak_width: The expected width of a single pure ion with
charge state +1 on spectrum (default: 0.15)
@type base_peak_width: float
@return: predicted peaks as (left limit, right limit)
@rtype: numpy.ndarray
"""
# calculate (m + z*H) / z = m / z + 1.01
ions = mass / numpy.arange(z_max, z_max - nz, -1) + 1.01
# use predict_peak_widths to predict peak widths
halfwidths = [x / 2 for x in predict_peak_widths(mass, z_max, nz, base_peak_width)]
# return predicted peaks as (left limit, right limit) tuples
return numpy.stack((ions - halfwidths, ions + halfwidths)).T
def integrate_chromatograms(rt_arr, ic_arr):
"""
To integrate data from a chromatogram, it is insufficient to simply
sum ion count (TIC/XIC) values, as that assumes uniformity in the
time-sampling, which many mass spec instruments do not guarantee.
This has a significant impact when looking at XICs with very narrow
peaks, as a skipped recording within the peak would have a large
impact on the integral if calculated naively.
This function takes the time element into account and returns a more
precise approximation of the underlying integral.
@param rt_arr: An array of retention times, size N
@type rt_arr: numpy.ndarray
@param ic_arr: (An) array(s) of ion counts (TIC/XIC), size N or M x N
@type ic_arr: numpy.ndarray
"""
# calculate the sampling rate (derivative of retention time)
sampling = rt_arr[1:] - rt_arr[:-1]
# use the mean for the last value, as we can't calculate it directly
sampling = numpy.concatenate((sampling, (sampling.mean(),)))
# calculate the mean between each two consecutive points,
# using the last point's own value twice to get back its original
# value because as above, we don't have the next one to use
means = (ic_arr.T + numpy.concatenate((ic_arr.T[1:], ic_arr.T[-1:]))) / 2
# now we have all the values to calculate a more precise integral
return (means * sampling).sum(0)
class MassSpec(object):
def __init__(self, acq_date, label, msfunc_params, progress_bar=True, debug=False):
"""
@param acq_date: Date spectrum was acquired
@type acq_date: datetime.datetime
@param label: Label for this spectrum
@type label: str
@param msfunc_params: the LC-MS functions (e.g. MS, DAD) for which we have data, and any other associated information (e.g. [{'func': 'MS', 'ion_mode': 'ES+', total_scans: 239}, {'func': 'DAD', 'ion_mode': 'EI+', 'total_scans': 24001}]); minimally has to contain the 'func' and 'total_scans' keys for each function
@type msfunc_params: iter of dict
@param progress_bar: Whether or not to show a progress bars for
time-consuming processes (default: True)
@type progress_bar: bool
@param debug: Turn on debug printing (default: False)
@type debug: float
"""
self.acq_date = acq_date
self.label = label
self._msfunc_params = tuple(msfunc_params)
num_funcs = len(self._msfunc_params)
self._pb = progress_bar
self._debug = debug
# some things to avoid re-analysis of the same data
self.__rts = [None] * num_funcs
self.__tics = [None] * num_funcs
self.__allsum = [None] * num_funcs
self.__abs = {}
def _get_rt(self, msfunc, i):
"""
Get the retention time (RT) for the i's scan of the MS function msfunc.
*** Implementation is dependent on the file type and engine used and
should be overridden by each daughter class. ***
@param msfunc: MS function to use (default: 0)
@type msfunc: int
@param i: Scan number
@type i: int
@return: Retention time
@rtype: number
"""
raise NotImplementedError("This function should be overridden in classes inheriting from MassSpec!")
def _get_scan(self, msfunc, i):
"""
Get scan data - m/z values and their corresponding inensities - for the
i's scan of the MS function msfunc.
*** Implementation is dependent on the file type and engine used and
should be overridden by each daughter class. ***
@param msfunc: MS function to use (default: 0)
@type msfunc: int
@param i: Scan number
@type i: int
@return: m/z list and corresponding intensity list
@rtype: tuple (tuple, tuple)
"""
raise NotImplementedError("This function should be overridden in classes inheriting from MassSpec!")
def _get_x_range(self, msfunc):
"""
Get the range of values on the x axis (usually m/z or wavelength) for
the MS function msfunc.
*** Implementation is dependent on the file type and engine used and
should be overridden by each daughter class. ***
@param msfunc: MS function to use (default: 0)
@type msfunc: int
@return: x value range (minimum, maximum)
@rtype: tuple (float, float)
"""
raise NotImplementedError("This function should be overridden in classes inheriting from MassSpec!")
def _get_chromatogram(self, msfunc=0, mzranges=None, fltr=None):
"""
Retrieve the data from the file and marginalise over m/z to receive
a chromatogram; filters can be used to extract ions (XIC) or no
filters for a TIC.
@param msfunc: MS function to use (default: 0)
@type msfunc: int
@param mzranges: ranges of m/z values ((min1,max1),(min2,max2),...) to accept, all other m/z values will be rejected and not summed over
@type mzranges: numpy.ndarray
@param fltr: Filter function to apply to (m/z, intensity) pairs
@type fltr: function
@return: total or extracted ion chromatogram as (RTs, T/XICs)
@rtype: numpy.ndarray, list
"""
get_tic = mzranges is None and fltr is None
if not get_tic or self.__rts[msfunc] is None or self.__tics[msfunc] is None:
# get from file
rts = []
tics = []
times = []
n = self._msfunc_params[msfunc]['total_scans']
if self._pb:
pb = ProgressBar(n, name='Gathering chromatogram data')
for i in range(n):
rts.append(self._get_rt(msfunc, i))
mzs, intens = self._get_scan(msfunc, i)
intens = numpy.array(intens)
mzs = numpy.array(mzs)
where = None
if get_tic:
tics.append(intens.sum())
else:
if mzranges is not None:
# this looks scary, but it just calculates a boolean array that represents all the places where the m/z is within one of the ranges
# thanks to Thomas Lohr for this line of code
where = ((mzs.reshape(-1, 1) >= mzranges[:,0]) &
(mzs.reshape(-1, 1) <= mzranges[:,1])).any(axis=1)
if fltr is not None:
vfltr = numpy.frompyfunc(fltr, 2, 1)
if where is not None:
where &= vfltr(mzs, rts)
else:
where = vfltr(mzs, rts)
# sum over the respective intensities
tics.append(intens.dot(where))
if self._pb:
pb.progress_one()
self.__rts[msfunc] = numpy.array(rts)
tics = numpy.array(tics)
if get_tic:
self.__tics[msfunc] = tics
# either return just-calculated values or load from memory
if get_tic:
tics = self.__tics[msfunc]
return self.__rts[msfunc], tics.copy()
def plot_chromatogram(self, msfunc=0, normalise=False, mzranges=None, fltr=None, fltr_label=None, plot_params={}, ax=None, show=True):
rts, tics = self._get_chromatogram(msfunc, mzranges=mzranges, fltr=fltr)
if normalise:
tics /= tics.max()
func_type = self._msfunc_params[msfunc]['func']
if func_type == 'DAD':
data_label = 'Absorbance'
else:
if fltr is None and mzranges is None:
data_label = 'TIC'
else:
data_label = 'XIC' + (' (%s)' % fltr_label if fltr_label is not None else '')
if ax is None:
fig, ax = pyplot.subplots()
plt = ax.plot(rts, tics, label=data_label, **plot_params)
ax.set_xlabel('RT (min)')
ax.set_ylabel(('Normalised ' if normalise else '') + data_label)
if show:
pyplot.legend()
pyplot.show()
pyplot.close()
else:
return ax, plt, (rts, tics)
def plot_absorbance(self, wavelength=280, normalise=False, show=True):
# identify correct function
msfunc = None
for i, func_params in enumerate(self._msfunc_params):
if func_params['func'] == 'DAD':
msfunc = i
if msfunc is None:
raise ValueError("No UV/Vis spectral data channel found!")
# find closest measured wavelength (assumes all scans have same X axis)
xvals = numpy.array(self._get_scan(msfunc, 0)[0])
dvector = abs(xvals - wavelength)
idx = dvector.argmin()
if dvector[idx] > 2.:
warnings.warn("Showing absorbance at closest wavelength to %d nm, which is %d nm" % (wavelength, xvals[idx]))
wavelength = xvals[idx]
# get absorbance values
if self.__rts[msfunc] is None:
# get from file
rts = []
total_scans = self._msfunc_params[msfunc]['total_scans']
for i in range(total_scans):
rts.append(self._get_rt(msfunc, i))
self.__rts[msfunc] = numpy.array(rts)
# or load from memory
rts = self.__rts[msfunc]
if idx not in self.__abs:
abss = []
total_scans = self._msfunc_params[msfunc]['total_scans']
for i in range(total_scans):
abss.append(self._get_scan(msfunc, i)[1][idx])
self.__abs[idx] = abss
else:
# load from memory
abss = self.__abs[idx]
if normalise:
abss = numpy.array(abss)
abss -= abss.min()
abss /= abss.max()
pyplot.plot(rts, abss, label='%d nm' % wavelength)
pyplot.xlabel('RT (min)')
pyplot.ylabel(('Normalised ' if normalise else '') + 'A%d' % wavelength)
if show:
pyplot.legend()
pyplot.show()
pyplot.close()
return wavelength
def fetch_raw_data(self, msfunc=0, rtrange=None, mzrange=None, num_bins=0):
"""
Fetch raw, or minimally processed, 3-dimensional data from the
raw file for further processing by other procedures.
@param msfunc: MS function to use (default: 0)
@type msfunc: int
@param rtrange: Range of retention times to limit to (optional)
@type rtrange: tuple (float, float) or None
@param mzrange: Range of m/z values to accept, all other m/z values will be rejected and not summed over (optional)
@type mzrange: tuple (float, float) or None
@param num_bins: Optional argument allowing reduction in the
memory required to store the data by binning
close-by m/z values together; this specifies
the number of bins to collect the data into
@type num_bins: int
@return: RTs (size N), m/zs (size M), and TICs or XICs (N x M),
each corresponding to one time point and comprising M
values for the M m/z values/ranges
@rtype: tuple (list, list, numpy.ndarray)
"""
rts = []
tics = []
total_scans = self._msfunc_params[msfunc]['total_scans']
# get mass range and create bins
if mzrange is None:
rl, rh = self._get_x_range(msfunc)
else:
rl, rh = mzrange
# calculate bin identities
if num_bins:
bin_width = (rh - rl) / float(num_bins)
mzbins = numpy.arange(rl, rh, bin_width)
else:
mzbins = {}
mz_counter = 0
if self._pb:
pb = ProgressBar(total_scans, name='Gathering raw data')
for i in range(total_scans):
rt = self._get_rt(msfunc, i)
if rtrange is None or rtrange[0] <= rt <= rtrange[1]:
# we are in the correct RT range
rts.append(rt)
mz, intens = self._get_scan(msfunc, i)
bins = numpy.zeros(num_bins or (len(mzbins) + len(mz)))
for mzi, intensi in zip(mz, intens):
# filter by mzrange
if rl <= mzi <= rh:
if num_bins:
# arrange data into bins
idx = int((mzi - rl) / bin_width)
else:
# use m/z values directly rather than binning
idx = mzbins.get(mzi, None)
if idx is None:
# new m/z value
mzbins[mzi] = idx = mz_counter
mz_counter += 1
bins[idx] += intensi
# remove tail data
if not num_bins:
bins = bins[:mz_counter]
# done with this set
tics.append(bins)
if self._pb:
pb.progress_one()
# some annoying consolidation we have to do when no bins are used
if not num_bins:
mzbins = numpy.array(tuple(mzbins.keys()))
# only now we have the final number of m/z values, so we
# have to pad the earlier value lists with zeros
for i in range(len(tics)):
tics[i] = numpy.pad(tics[i], (0, mz_counter - len(tics[i])))
# TODO: consider ordering by m/z
return rts, mzbins, numpy.array(tics)
def plot_3d(self, msfunc=0, num_bins=1000, rtrange=None, mzrange=None, flatten=True, cmap=None, ax=None, show=True):
# get RTs and TICs from file
rts, mzs, tics = self.fetch_raw_data(msfunc, rtrange, mzrange, num_bins)
# create ranges
xx = numpy.array(rts)
zz = numpy.array(tics).T
if mzrange is not None:
i0 = mzs.searchsorted(mzrange[0])
ie = mzs.searchsorted(mzrange[1])
mzs = mzs[i0:ie]
zz = zz[i0:ie]
# make ranges 2d
xx, yy = numpy.meshgrid(xx, mzs)
# plot
if flatten:
if ax is None:
fig, ax = pyplot.subplots()
##pyplot.pcolor(xx, yy, zz, cmap=cmap, linewidth=0, antialiased=False)
retval = ax.contour(xx, yy, zz, cmap=cmap, antialiased=False)
else:
fig = pyplot.figure()
ax = fig.add_subplot(111, projection='3d')
retval = ax.plot_surface(xx, yy, zz, cmap=cmap, rstride=1, cstride=1, linewidth=0, antialiased=False)
if show:
pyplot.show()
pyplot.close()
else:
return retval
def _sum_scans(self, msfunc, scan_b, scan_e, baseline=0.):
# gather scans to sum up
if scan_e <= scan_b:
return
to_sum = (self._get_scan(msfunc, i) for i in range(scan_b, scan_e+1))
# calculate sum with minimal set of x values (code: Thomas Lohr)
## TODO: make more memory-efficient, currently has to load the
## entire 3d spectrum to memory for this..!
data = [numpy.array((x,y)).T for x,y in to_sum]
allx = numpy.unique(numpy.concatenate([d[:,0] for d in data]))
ally = numpy.zeros_like(allx)
# XXX THIS DOES NOT TAKE INTO ACCOUNT THE RT AXIS, SO IF XXX
# XXX THERE IS NON-UNIFORM SAMPLING (AND THERE IS!), IT XXX
# XXX WILL UNDERESTIMATE ALL SUMS! XXX
for dat in data:
_, ix, jx = numpy.intersect1d(allx, dat[:,0], return_indices=True)
ally[ix] += (dat[jx,1] - baseline)
return allx, ally
def sum_scans(self, beg=None, end=None, msfunc=0, baseline=0., export_path=None):
# load sum from memory if available
sumall = beg is None and end is None
if sumall and self.__allsum[msfunc] is not None:
return self.__allsum[msfunc]
# else, look for RTs
if self.__rts[msfunc] is None:
# get from file
rts = []
total_scans = self._msfunc_params[msfunc]['total_scans']
for i in range(total_scans):
rts.append(self._get_rt(msfunc, i))
rts = numpy.array(rts)
self.__rts[msfunc] = numpy.array(rts)
# or load from memory
rts = self.__rts[msfunc]
# find closest point to beginning RT
if beg is None:
begi = 0
else:
d_beg_vec = abs(rts - beg)
begi = d_beg_vec.argmin()
# find closest point to end RT
if end is None:
endi = len(rts) - 1
else:
d_end_vec = abs(rts - end)
endi = d_end_vec.argmin()
# and we have indexes!
retval = self._sum_scans(msfunc, begi, endi, baseline)
if retval is None:
raise ValueError("No scans found in RT range %.2f-%.2f for function %s" % (beg, end, self._msfunc_params[msfunc]['func']))
if export_path is not None:
w = open(export_path, 'w')
for i in range(len(retval[0])):
w.write('%f %f\n' % (retval[0][i], retval[1][i]))
w.close()
if sumall:
self.__allsum[msfunc] = retval
return retval
def pick_peaks(self, msfunc=0):
rts, tics = self._get_chromatogram(msfunc)
last_scan_idx = self._msfunc_params[msfunc]['total_scans'] - 1
partition_pts = peak_picking.pick_peaks(tics) + [last_scan_idx]
partitions = [(partition_pts[i-1] if i > 0 else 0, partition_pts[i]) for i in range(len(partition_pts))]
peaks = [(rts[partition[0]], rts[partition[1]]) +
self._sum_scans(msfunc, *partition) for partition in partitions]
return peaks
def export_peaks(self, outpath, plot_peaks=False, msfunc=0, show=True):
peaks = self.pick_peaks(msfunc)
self.plot_chromatogram(msfunc, normalise=True, show=False)
fig = pyplot.gcf()
w = open(outpath + '-peaks.csv', 'w')
w.write("Start,End,TIC\n")
for i in range(len(peaks)):
peak = peaks[i]
pyplot.plot((peak[0],peak[1]), (-0.08+0.01*(i%2), -0.08+0.01*(i%2)))
pyplot.text((peak[1]+peak[0])/2, -0.06+0.01*(i%2), str(i+1), ha='center')
with open(outpath + '-peak%02d-%.02f_%.02f.txt' % (i+1, peak[0], peak[1]), 'w') as f:
for j in range(len(peak[2])):
f.write('%f %f\n' % (peak[2][j], peak[3][j]))
w.write("%f,%f,%f\n" % (peak[0], peak[1], peak[3].sum()))
w.close()
pyplot.savefig(outpath + '.png')
if plot_peaks:
fig = pyplot.figure(figsize=(16,12))
width = int(math.ceil(len(peaks) ** 0.5))
height = int(math.ceil(float(len(peaks)) / width))
axarr = fig.subplots(height, width)
if height == 1:
axarr = [axarr]
for i in range(height):
for j in range(width):
n = i * width + j
if n < len(peaks):
peak = peaks[n]
axarr[i][j].plot(peak[2], peak[3])
axarr[i][j].set_title('Peak %d (%.1f-%.1f)' % (n+1, peak[0], peak[1]))
fig.savefig(outpath + '.peaks.png')
if show:
fig.canvas.set_window_title(self.label)
pyplot.show()
pyplot.close()
def get_xic(self, mzranges, mzmargins=0.05, msfunc=0, normalise=False, plot=False, label=None, ax=None, show=True):
# cover many different input types for mzranges
if not hasattr(mzranges, '__iter__'):
mzranges = numpy.array((mzranges-mzmargins, mzranges+mzmargins)).reshape(1,2)
elif len(mzranges) == 2 and not hasattr(mzranges[0], '__iter__'):
mzranges = numpy.array(mzranges).reshape(1,2)
else:
mzranges = numpy.array(mzranges)
# make a filter label
if label is None:
label = '; '.join("%.2f - %.2f" % tuple(rng) for rng in mzranges)
# fetch the XIC
if plot:
ax, line, data = self.plot_chromatogram(msfunc=msfunc, normalise=normalise, mzranges=mzranges, fltr_label=label, ax=ax, show=False)
if show:
pyplot.legend()
pyplot.show()
pyplot.close()
return ax, line[0], data
else:
rts, tics = self._get_chromatogram(msfunc=msfunc, mzranges=mzranges)
if normalise:
tics /= tics.max()
return None, None, (rts, tics)
def plot_xic(self, mzranges, mzmargins=0.05, msfunc=0, normalise=False, label=None, ax=None, show=True):
# ugly hack
ax, line, data = self.get_xic(mzranges, mzmargins, msfunc, normalise, True, label, ax, show)
if not show:
return ax, line, data
def plot_multi_mxics(self, mzs, mzmargins=0.05, normalise=False, show=True):
pb = ProgressBar(len(mzs) + 1, name='Plotting XICs')
ax = self.plot_chromatogram(normalise=normalise, show=False)[0]
pb.progress_one()
for mass in mzs:
self.plot_xic((mass-mzmargins, mass+mzmargins), ax=ax, normalise=normalise, show=False)
pb.progress_one()
pyplot.legend()
if show:
pyplot.show()
def predict_ions(self, masses, msfunc=0, refine=True, max_dist=3., sumall=None):
"""
@param refine: refine m/z choice using the marginalised spectrum,
which takes longer but returns much more precise
m/z choices (default: True)
@param refine: bool
@param max_dist: maximum allowable distance, in Da, from the
expected mass implied by the highest peak
(default: 3 Da)
@type max_dist: number
@param sumall: a spectrum to use for verifying peaks in refinement
(optional, will sum entire spectrum if omitted)
@type sumall: tuple (numpy.ndarray, numpy.ndarray)
"""
# get mass range for this function
rl, rh = self._get_x_range(msfunc)
if isinstance(masses, int) or isinstance(masses, float):
masses = (masses,)
mzss = []
for mass in map(float, masses):
# coarse-grained approximation
if mass > rl:
# calculate charge corresponding to ion at middle of range
mid = int(mass // ((rl + rh) / 2))
# take up to 2 higher masses and up to 18 le masses
rng = range(mid+18, mid-2, -1)
mzs = [(z, mass/z + 1.01) for z in rng
if z > 0 and z*rl <= mass and z*rh >= mass]
# add full mass (not M+H but M) for masses within the range
if mass < rh:
mzs.append((1, mass))
else:
raise ValueError("Mass range %.1f-%.1f cannot detect mass %.1f" % (rl, rh, mass))
if self._debug:
print("Unrefined m/z values:", mzs, file=sys.stderr)
# refine m/z choice using marginalised data
refined = False
if refine:
if sumall is None:
sumall = self.sum_scans(msfunc=msfunc)
# try to fit a peak around each m/z
fit = numpy.array([peak_picking.mz_peak_likeness(*sumall, mz[1]) for mz in mzs])
if self._debug:
print("Peak fitting matrix:", " m/z diff obs/exp rat peak hght ", *('%12.3f %12.4f %12.2e' % tuple(row) for row in fit), sep='\n', file=sys.stderr)
# ignore peaks that have a bad fit
fit[fit[:,1] < 0.4] = 0
fit[fit[:,0] > 0.3] = 0
# start with highest peak
highest = fit[:,2].argmax()
h_x_diff, h_y_ratio, h_peak_h = fit[highest]
h_z = mzs[highest][0]
if self._debug:
print("Highest peak:", fit[highest], h_z, file=sys.stderr)
# continue only if fit is good enough
if h_z != 0 and h_peak_h > 0 and abs(h_x_diff * h_z) <= max_dist:
# scan z values until reaching things that don't look
# like peaks in the data or intensity is lower than 1%
z = h_z
x_diff = h_x_diff
peak_h = h_peak_h
i = highest
while z > 1 and abs(x_diff * z) <= max_dist and peak_h >= 0.01 * h_peak_h:
i += 1
z -= 1
# get data for this m/z value
if i < len(mzs):
x_diff, y_ratio, peak_h = fit[i]
else:
x_diff, y_ratio, peak_h = peak_picking.mz_peak_likeness(*sumall, mass / z + 1.01)
minz = z + 1
# same to the other side
z = h_z
x_diff = h_x_diff
peak_h = h_peak_h
i = highest
while abs(x_diff * z) <= max_dist and peak_h >= 0.01 * h_peak_h:
i -= 1
z += 1
# get data for this m/z value
if i > 0:
x_diff, y_ratio, peak_h = fit[i]
else:
x_diff, y_ratio, peak_h = peak_picking.mz_peak_likeness(*sumall, mass / z + 1.01)
maxz = z - 1
if minz < maxz:
mzs = [(z, mass/z + 1.01) for z in range(maxz, minz-1, -1)]
else:
mzs = ((h_z, mass/h_z + 1.01),)
refined = True
else:
print("Warning: m/z values for mass %.1f do not seem to represent peaks in data" % mass, file=sys.stderr)
# make filter function
mzss.append(([mz[1] for mz in mzs], refined))
if self._debug:
for mass, mzs in zip(masses,mzss):
print("Ions for mass %.1f:" % mass, file=sys.stderr)
print(", ".join(["%.2f" % mz for mz in mzs[0]]), file=sys.stderr)
return mzss
def search_mass(self, masses, msfunc=0, normalise=False, base_peak_width=0.15, refine=True, override_z_values=None, export_path=None, return_data=False, show=True):
"""
@param masses: Mass(es) to look for
@type masses: number of iterable of numbers
@param msfunc: MS function to use (default: 0)
@type msfunc: int
@param normalise: Normalise final XIC data to a 0-1 scale (default: False)
@type normalise: bool
@param base_peak_width: The base peak width expected, to decide the
margins around each m/z value to look at
(default: 0.15 Da)
@type base_peak_width: float
@param refine: Refine m/z choice using the marginalised spectrum,
which takes longer but returns much more precise
integrals as well as goodness of fit estimates
(default: True)
@type refine: bool
@param override_z_values: A set of z-values to use, instead of any
automatically detected ones (optional)
@type override_z_values: None or tuple of int
or tuple of tuple of int
@param export_path: Filename to export figure to (optional)
@type export_path: str or None
@param return_data: Return XIC data for further analysis (default: False)
@type return_data: bool
@param show: Whether or not to draw the pyplot plot on the screen (default: True)
@type show: bool
"""
# prepare
retval = []
if isinstance(masses, int) or isinstance(masses, float):
masses = (masses,)
# predict m/z values
if override_z_values is not None:
# no need to predict z values - saves us a lot of work..!
try:
override_z_values = tuple(override_z_values)
except TypeError:
raise TypeError("parameter 'override_z_values' must be an iterable of integers (or of iterables of integers)")
if isinstance(override_z_values[0], int) or isinstance(override_z_values[0], float):
# a single list of z values
get_z_vals = lambda idx: sorted(override_z_values, reverse=True)
else:
# individual z value lists for each mass
get_z_vals = lambda idx: sorted(override_z_values[idx], reverse=True)
# use z values to calculate m/z values
mzss = []
for i, mass in enumerate(masses):
mzss.append(([mass / z + 1.01 for z in get_z_vals(i)], False))
else:
# prepare for refinement of z values, if requested
if refine:
# sum over all RTs to get flat spectrum for parameter optimisations
if self._pb:
pb = ProgressBar(1, name="Marginalising over RT")
allsum = self.sum_scans(msfunc=msfunc)
if self._pb:
pb.progress_one()
# run (first round of) z value prediction
mzss = self.predict_ions(masses, msfunc, refine=refine)
# plot total ion chromatogram (TIC)
print("Plotting TIC...")
ax, line, data = self.plot_chromatogram(msfunc=msfunc, normalise=normalise, show=False)
# start going over the masses and isolating corresponding peaks
for mass, mzs in zip(masses, mzss):
print("Plotting XIC for mass %.1f..." % mass)
mzs, refined = mzs
# predict the width of each peak
z0 = int(round(mass / (mzs[0] - 1.01)))
exp_widths = predict_peak_widths(mass, z0, min(len(mzs), z0), base_peak_width)
# refine mass search further for maximum precision!
if refine and refined and lmfit is not None:
# we will run two rounds of ion extraction, first to
# determine location of peak, then re-identify the ions
# we need to consider, and then re-extract for precision
data = self.get_xic([(mz-exp_w/2, mz+exp_w/2) for mz, exp_w in zip(mzs, exp_widths)], msfunc=msfunc, plot=False)[2]
# fit single peak
print("Refining for mass %.1f..." % mass)
fit = SVM.fit(data[1],
params = SVM.guess(data[1], x = data[0]),
x = data[0])
# identify central region of peak
normfit = fit.best_fit / fit.best_fit.max()
left = (normfit > 0.1).argmax()
right = normfit.shape[0] - 1 - (normfit[::-1] > 0.1).argmax()
# sum scans in peak
partsum = self.sum_scans(data[0][left], data[0][right], msfunc=msfunc)
if self._debug:
print("Potential peak identified between %.2f and %.2f, with fit amplitude %.2e and centre %.2f" % (data[0][left], data[0][right], fit.params['amplitude'], fit.params['center']), file=sys.stderr)
# reidentify m/z values
mzs = self.predict_ions(mass, msfunc, refine=refine, sumall=partsum)[0]
# repeat the exercise...
mzs = mzs[0]
z0 = int(round(mass / (mzs[0] - 1.01)))
exp_widths = predict_peak_widths(mass, z0, min(len(mzs), z0), base_peak_width)
mzranges = [(mz-exp_w/2, mz+exp_w/2) for mz, exp_w in zip(mzs, exp_widths)]
print("Ions for mass %.1f: %s" % (mass, '; '.join("%.2f - %.2f" % tuple(rng) for rng in mzranges)))
ax, line, data = self.plot_xic(mzranges, msfunc=msfunc, normalise=normalise, label="M=%.1f, %d ions" % (mass, len(mzs)), ax=ax, show=False)
else:
# just plot filtered chromatogram (XIC)
mzranges = [(mz-exp_w/2, mz+exp_w/2) for mz, exp_w in zip(mzs, exp_widths)]
print("Ions for mass %.1f: %s" % (mass, '; '.join("%.2f - %.2f" % tuple(rng) for rng in mzranges)))
ax, line, data = self.plot_xic(mzranges, msfunc=msfunc, normalise=normalise, label="M=%.1f, %d ions" % (mass, len(mzs)), ax=ax, show=False)
if return_data:
retval.append(data)
if export_path is not None:
pyplot.legend()
pyplot.savefig(export_path)
if show:
pyplot.legend()
pyplot.show()
pyplot.close()
elif export_path is not None:
pyplot.clf()
return retval or None
def extract_multiple_masses(self, masses, z_max, nz, confounding_peaks = None, between_conflicting_peaks = lambda i0, m0, i1, m1: int(i0 > i1), rtrange = None, return_aggregate = True, return_chrom = False, plot = False, ax = None, show = True):
"""
Very quick and precise way to isolate multiple species that
roughly co-elute, and quantify the relative contributions of
each of them to the spectrum, given that they share the z-value
distribution and the user has prior knowledge of that distribution.
@param masses: Macromolecule masses to search for
@type masses: iterable of number
@param z_max: Maximal z value to predict for
@type z_max: int
@param nz: Number of z values to predict for
@type nz: int
@param confounding_peaks: List of peaks that may be present and
confound the results; peaks that overlap
with these peaks will be completely
ignored and not used (optional)
@type confounding_peaks: iterable of 2-tuple of float
@param between_conflicting_peaks: If two of the masses have
an overlapping peak, this will
be used to decide which species
it counts towards; if this
returns -1 neither will use
it, if 0 the first one, if 1
the second one, and if 2 both
(default: first mass by order
gets the peak)
@type between_conflicting_peaks: function (i0: int, m0: float,
i1: int, m1: float) -> int
@param rtrange: Retention time range to focus on (optional)
@rtype rtrange: 2-tuple of float
@param return_aggregate: Return one total per mass (otherwise, a
total will be returned for each predicted
peak (default: True)
@type return_aggregate: bool
@param return_chrom: Return chromatograms rather than integrals
(default: False)
@type return_chrom: bool
@param plot: Plot the individual/aggregate XICs (default: False)
@type plot: bool
@param ax: Axes to plot the XICs on (optional)
@type ax: matplotlib.axes._subplots.AxesSubplot
@param show: Whether or not to draw the pyplot plot on the screen (default: True)
@type show: bool
@return: retention time vector and a vector of integrals OR
XICs OR
individual peak XICs
@rtype: tuple (numpy.ndarray, numpy.ndarray)
"""
if plot and ax is None:
fig, ax = pyplot.subplots()
# predict peaks
peaks = [naive_predict_peaks(M, z_max, nz) for M in masses]
# identify conflicts
keep = numpy.ones((len(peaks), max(map(len, peaks))), dtype = bool)
for i in range(len(peaks)):
for j in range(i + 1, len(peaks)):
# identify overlapping ranges, by finding ranges in 'peaks'
# that overlap with any range in 'confounding_peaks', i.e.
# those ranges (r0, r1) that have a range in
# 'confounding_peaks' (c0, c1) s.t. r0 < c1 and r1 > c0
overlaps = (numpy.less.outer(peaks[i][:, 0],
peaks[j][:, 1]) &
numpy.greater.outer(peaks[i][:, 1],
peaks[j][:, 0]))
# this gives the indices in the i peak axis and the j peak
# axis of conflicting ion ranges
masses_i, masses_j = numpy.nonzero(overlaps)
# so we just have to decide what to do with each
for k in range(len(masses_i)):
indi = masses_i[k]
indj = masses_j[k]
decision = between_conflicting_peaks(i, peaks[i][indi],
j, peaks[j][indj])
if decision < 1:
# -1 means neither and 0 means first, so second
# is out of the picture
keep[j, indj] = False
print("removing %.3f-%.3f for mass %.1f in %s, as it overlaps with a peak for another mass" % (*peaks[j][indj], masses[j], self.label))
if decision in (-1, 1):
keep[i, indi] = False
print("removing %.3f-%.3f for mass %.1f in %s, as it overlaps with a peak for another mass" % (*peaks[i][indi], masses[i], self.label))
peaks = [peaks[i][keep[i]] for i in range(len(peaks))]
# remove confounding factors
if confounding_peaks is not None:
final_peaks = []
for i, mass_peaks in enumerate(peaks):
# same method as above for identifying overlaps
overlaps = (numpy.less.outer(mass_peaks[:, 0],
confounding_peaks[:, 1]) &
numpy.greater.outer(mass_peaks[:, 1],
confounding_peaks[:, 0]))
bad_peaks = overlaps.sum(1) > 0
for pmn, pmx in mass_peaks[bad_peaks]:
print("removing %.3f-%.3f for mass %.1f in %s, as it overlaps with confounding range" % (pmn, pmx, masses[i], self.label))
final_peaks.append(mass_peaks[~bad_peaks])
peaks = final_peaks
# to avoid fetching too much data, get the minimal range required
minmz = min([(mpeaks[0][0] if (len(mpeaks) and len(mpeaks[0])) else numpy.inf) for mpeaks in peaks])
maxmz = max([(mpeaks[-1][-1] if (len(mpeaks) and len(mpeaks[-1])) else 0.) for mpeaks in peaks])
# gather data
x, y, z = self.fetch_raw_data(rtrange = rtrange,
mzrange = (minmz, maxmz))
rt = numpy.array(x)
# for each species
dim = [len(peaks)]
if not return_aggregate:
# if not aggregate data, we return each individual peak
dim.append(max(map(len, peaks)))
if return_chrom:
# if full chromatograms are requested, we need the time dim
dim.append(len(rt))
species = numpy.zeros(dim)
for j, mpeaks in enumerate(peaks):
# slice peak by peak
xics = numpy.zeros((len(mpeaks), len(rt)))
for k in range(len(mpeaks)):
peak = mpeaks[k]
# isolate slice
ind = (y >= peak[0]) & (y <= peak[1])
dat = z[:, ind]
# use lowest point on slice to remove potential
# baseline shifts
# TODO: verify this is always valid
dat -= dat.min(0)