-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathparser_mzml.py
More file actions
905 lines (717 loc) · 30.7 KB
/
parser_mzml.py
File metadata and controls
905 lines (717 loc) · 30.7 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
# -------------------------------------------------------------------------
# Copyright (C) 2008-2011 Martin Strohalm <www.mmass.org>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# Complete text of GNU GPL can be found in the file LICENSE.TXT in the
# main directory of the program.
# -------------------------------------------------------------------------
# load libs
import xml.sax
import xml.dom.minidom
import base64
import zlib
import struct
import re
import os.path
import numpy
from copy import deepcopy
# load stopper
from mod_stopper import CHECK_FORCE_QUIT
# load objects
import obj_peak
import obj_peaklist
import obj_scan
# compile basic patterns
SCAN_NUMBER_PATTERN = re.compile('scan=([0-9]+)')
# PARSE mzML DATA
# ---------------
class parseMZML():
"""Parse data from mzML."""
def __init__(self, path):
self.path = path
self._scans = None
self._scanlist = None
self._info = None
# check path
if not os.path.exists(path):
raise IOError, 'File not found! --> ' + self.path
# ----
def load(self):
"""Load all scans into memory."""
# init parser
handler = runHandler()
parser = xml.sax.make_parser()
parser.setContentHandler(handler)
# parse document
try:
document = file(self.path)
parser.parse(document)
document.close()
self._scans = handler.data
except xml.sax.SAXException:
self._scans = False
# make scanlist
if self._scans:
self._scanlist = deepcopy(self._scans)
for scanNumber in self._scanlist:
del self._scanlist[scanNumber]['mzData']
del self._scanlist[scanNumber]['mzPrecision']
del self._scanlist[scanNumber]['mzCompression']
del self._scanlist[scanNumber]['intData']
del self._scanlist[scanNumber]['intPrecision']
del self._scanlist[scanNumber]['intCompression']
# ----
def info(self):
"""Get document info."""
# get preloaded data if available
if self._info:
return self._info
# init parser
handler = infoHandler()
parser = xml.sax.make_parser()
parser.setContentHandler(handler)
# parse document
try:
document = file(self.path)
parser.parse(document)
document.close()
except stopParsing:
self._info = handler.data
except xml.sax.SAXException:
self._info = False
return self._info
# ----
def scanlist(self):
"""Get list of all scans in the document."""
# use preloaded data if available
if self._scanlist:
return self._scanlist
# init parser
handler = scanlistHandler()
parser = xml.sax.make_parser()
parser.setContentHandler(handler)
# parse document
try:
document = file(self.path)
parser.parse(document)
document.close()
self._scanlist = handler.data
except xml.sax.SAXException:
self._scanlist = False
return self._scanlist
# ----
def scan(self, scanID=None):
"""Get spectrum from document."""
# use preloaded data if available
if self._scans and scanID in self._scans:
data = self._scans[scanID]
# parse file
else:
handler = scanHandler(scanID)
parser = xml.sax.make_parser()
parser.setContentHandler(handler)
try:
document = file(self.path)
parser.parse(document)
document.close()
data = handler.data
except stopParsing:
data = handler.data
except xml.sax.SAXException:
return False
# check data
if not data:
return False
# return scan
return self._makeScan(data)
# ----
def _makeScan(self, scanData):
"""Make scan object from raw data."""
# parse peaks
points = self._parsePoints(scanData)
if scanData['spectrumType'] == 'discrete':
for x, p in enumerate(points):
points[x] = obj_peak.peak(p[0], p[1])
scan = obj_scan.scan(peaklist=obj_peaklist.peaklist(points))
else:
scan = obj_scan.scan(profile=points)
# set metadata
scan.title = scanData['title']
scan.scanNumber = scanData['scanNumber']
scan.parentScanNumber = scanData['parentScanNumber']
scan.msLevel = scanData['msLevel']
scan.polarity = scanData['polarity']
scan.retentionTime = scanData['retentionTime']
scan.totIonCurrent = scanData['totIonCurrent']
scan.basePeakMZ = scanData['basePeakMZ']
scan.basePeakIntensity = scanData['basePeakIntensity']
scan.precursorMZ = scanData['precursorMZ']
scan.precursorIntensity = scanData['precursorIntensity']
scan.precursorCharge = scanData['precursorCharge']
return scan
# ----
def _parsePoints(self, scanData):
"""Parse spectrum data."""
# check data
if not scanData['mzData'] or not scanData['intData']:
return []
# decode data
mzData = base64.b64decode(scanData['mzData'])
intData = base64.b64decode(scanData['intData'])
# decompress data
if scanData['mzCompression'] == 'zlib':
mzData = zlib.decompress(mzData)
if scanData['intCompression'] == 'zlib':
intData = zlib.decompress(intData)
# get precision
mzPrecision = 'f'
intPrecision = 'f'
if scanData['mzPrecision'] == 64:
mzPrecision = 'd'
if scanData['intPrecision'] == 64:
intPrecision = 'd'
# convert from binary
count = len(mzData) / struct.calcsize('<' + mzPrecision)
mzData = struct.unpack('<' + mzPrecision * count, mzData[0:len(mzData)])
count = len(intData) / struct.calcsize('<' + intPrecision)
intData = struct.unpack('<' + intPrecision * count, intData[0:len(intData)])
# format
if scanData['spectrumType'] == 'discrete':
data = map(list, zip(mzData, intData))
else:
mzData = numpy.array(mzData)
mzData.shape = (-1,1)
intData = numpy.array(intData)
intData.shape = (-1,1)
data = numpy.concatenate((mzData,intData), axis=1)
data = data.copy()
return data
# ----
class infoHandler(xml.sax.handler.ContentHandler):
"""Get info data."""
def __init__(self):
self.data = {
'title': '',
'operator': '',
'contact': '',
'institution': '',
'date': '',
'instrument': '',
'notes': '',
}
self._isDescription = False
self._isConfig = False
# ----
def startElement(self, name, attrs):
"""Element started."""
# get file description
if name == 'fileDescription':
self._isDescription = True
elif self._isDescription and name == 'cvParam':
if attrs.get('accession', '') == 'MS:1000580':
self.data['title'] = attrs.get('name', '')
elif attrs.get('accession', '') == 'MS:1000586':
self.data['operator'] = attrs.get('value', '')
elif attrs.get('accession', '') == 'MS:1000590':
self.data['institution'] = attrs.get('value', '')
elif attrs.get('accession', '') == 'MS:1000589':
self.data['contact'] = attrs.get('value', '')
# get instrument
elif name == 'instrumentConfiguration':
self._isConfig = True
elif self._isConfig and name == 'cvParam' and attrs.get('accession', '') == 'MS:1000169':
self.data['instrument'] = attrs.get('name', '')
# ----
def endElement(self, name):
"""Element ended."""
# stop parsing
if name == 'instrumentConfiguration':
raise stopParsing()
# ----
class scanlistHandler(xml.sax.handler.ContentHandler):
"""Get list of all scans in the document."""
def __init__(self):
self.data = {}
self._isSpectrum = False
self._isPrecursor = False
self._scanHierarchy = [None]
# ----
def startElement(self, name, attrs):
"""Element started."""
# get scan data
if name == 'spectrum':
self._isSpectrum = True
# get scan ID
self.currentID = None
attribute = attrs.get('id', False)
if attribute:
self.currentID = _parseScanNumber(attribute)
scan = {
'title': '',
'scanNumber': self.currentID,
'parentScanNumber': None,
'msLevel': None,
'pointsCount': None,
'polarity': None,
'retentionTime': None,
'lowMZ': None,
'highMZ': None,
'basePeakMZ': None,
'basePeakIntensity': None,
'totIonCurrent': None,
'precursorMZ': None,
'precursorIntensity': None,
'precursorCharge': None,
'spectrumType': 'unknown',
}
# get points count
attribute = attrs.get('defaultArrayLength', False)
if attribute:
scan['pointsCount'] = int(attribute)
# append scan
self.data[self.currentID] = scan
# precursor tag
elif name == 'precursor' and self._isSpectrum:
self._isPrecursor = True
# get parent scan number
attribute = attrs.get('spectrumRef', False)
if attribute:
self.data[self.currentID]['parentScanNumber'] = _parseScanNumber(attribute)
# get precursor
elif name == 'cvParam' and self._isPrecursor:
paramName = attrs.get('name','')
paramValue = attrs.get('value','')
if paramName == 'selected ion m/z' and paramValue != None:
self.data[self.currentID]['precursorMZ'] = float(paramValue)
elif paramName == 'intensity' and paramValue != None:
self.data[self.currentID]['precursorIntensity'] = float(paramValue)
elif paramName == 'possible charge state' and paramValue != None:
self.data[self.currentID]['precursorCharge'] = int(paramValue)
elif paramName == 'charge state' and paramValue != None:
self.data[self.currentID]['precursorCharge'] = int(paramValue)
# get scan metadata
elif name == 'cvParam' and self._isSpectrum:
paramName = attrs.get('name','')
paramValue = attrs.get('value','')
# data type
if paramName == 'centroid spectrum':
self.data[self.currentID]['spectrumType'] = 'discrete'
elif paramName == 'profile spectrum':
self.data[self.currentID]['spectrumType'] = 'continuous'
# MS level
elif paramName == 'ms level' and paramValue != None:
self.data[self.currentID]['msLevel'] = int(paramValue)
# polarity
elif paramName == 'positive scan':
self.data[self.currentID]['polarity'] = 1
elif paramName == 'negative scan':
self.data[self.currentID]['polarity'] = -1
# total ion current
elif paramName == 'total ion current' and paramValue != None:
self.data[self.currentID]['totIonCurrent'] = max(0.0, float(paramValue))
# base peak
elif paramName == 'base peak m/z' and paramValue != None:
self.data[self.currentID]['basePeakMZ'] = float(paramValue)
elif paramName == 'base peak intensity' and paramValue != None:
self.data[self.currentID]['basePeakIntensity'] = max(0.0, float(paramValue))
# mass range
elif paramName == 'lowest observed m/z' and paramValue != None:
self.data[self.currentID]['lowMZ'] = float(paramValue)
elif paramName == 'highest observed m/z' and paramValue != None:
self.data[self.currentID]['highMZ'] = float(paramValue)
# retention time
elif paramName == 'scan start time' and paramValue != None:
if attrs.get('unitName','') == 'minute':
self.data[self.currentID]['retentionTime'] = float(paramValue)*60
elif attrs.get('unitName','') == 'second':
self.data[self.currentID]['retentionTime'] = float(paramValue)
else:
self.data[self.currentID]['retentionTime'] = float(paramValue)*60
# ----
def endElement(self, name):
"""Element ended."""
# end spectrum element
if name == 'spectrum':
self._isSpectrum = False
# end precursor element
elif name == 'precursor':
self._isPrecursor = False
# ----
def characters(self, ch):
"""Grab characters."""
pass
# ----
class scanHandler(xml.sax.handler.ContentHandler):
"""Get scan data."""
def __init__(self, scanID):
self.data = False
self.scanID = scanID
self._isMatch = False
self._isPrecursor = False
self._isBinaryDataArray = False
self._isData = False
self._scanHierarchy = [None]
self.tmpBinaryData = None
self.tmpPrecision = None
self.tmpCompression = None
self.tmpArrayType = None
# ----
def startElement(self, name, attrs):
"""Element started."""
# get scan metadata
if name == 'spectrum':
self._isMatch = False
# get scan ID
scanID = None
attribute = attrs.get('id', False)
if attribute:
scanID = _parseScanNumber(attribute)
# selected scan
if self.scanID == None or self.scanID == scanID:
self._isMatch = True
self.data = {
'title': '',
'scanNumber': scanID,
'parentScanNumber': None,
'msLevel': None,
'pointsCount': None,
'polarity': None,
'retentionTime': None,
'lowMZ': None,
'highMZ': None,
'basePeakMZ': None,
'basePeakIntensity': None,
'totIonCurrent': None,
'precursorMZ': None,
'precursorIntensity': None,
'precursorCharge': None,
'spectrumType': 'unknown',
'mzData': None,
'mzPrecision': None,
'mzCompression': None,
'intData': None,
'intPrecision': None,
'intCompression': None,
}
# get points count
attribute = attrs.get('defaultArrayLength', False)
if attribute:
self.data['pointsCount'] = int(attribute)
# precursor tag
elif name == 'precursor' and self._isMatch:
self._isPrecursor = True
# get parent scan number
attribute = attrs.get('spectrumRef', False)
if attribute:
self.data['parentScanNumber'] = _parseScanNumber(attribute)
# binary aray tag
elif name == 'binaryDataArray' and self._isMatch:
self._isBinaryDataArray = True
self.tmpBinaryData = []
self.tmpPrecision = None
self.tmpCompression = None
self.tmpArrayType = None
# data array tag
elif name == 'binary' and self._isBinaryDataArray:
self._isData = True
# get precursor
elif name == 'cvParam' and self._isPrecursor:
paramName = attrs.get('name','')
paramValue = attrs.get('value','')
if paramName == 'selected ion m/z' and paramValue != None:
self.data['precursorMZ'] = float(paramValue)
elif paramName == 'intensity' and paramValue != None:
self.data['precursorIntensity'] = float(paramValue)
elif paramName == 'possible charge state' and paramValue != None:
self.data['precursorCharge'] = int(paramValue)
elif paramName == 'charge state' and paramValue != None:
self.data['precursorCharge'] = int(paramValue)
# get binary data metadata
elif name == 'cvParam' and self._isBinaryDataArray:
paramName = attrs.get('name','')
paramValue = attrs.get('value','')
# precision
if paramName == '64-bit float':
self.tmpPrecision = 64
elif paramName == '32-bit float':
self.tmpPrecision = 32
# compression
elif paramName == 'zlib compression':
self.tmpCompression = 'zlib'
elif paramName == 'no compression':
self.tmpCompression = None
# array type
elif paramName == 'm/z array':
self.tmpArrayType = 'mzArray'
elif paramName == 'intensity array':
self.tmpArrayType = 'intArray'
# get scan metadata
elif name == 'cvParam' and self._isMatch:
paramName = attrs.get('name','')
paramValue = attrs.get('value','')
# data type
if paramName == 'centroid spectrum':
self.data['spectrumType'] = 'discrete'
elif paramName == 'profile spectrum':
self.data['spectrumType'] = 'continuous'
# MS level
elif paramName == 'ms level' and paramValue != None:
self.data['msLevel'] = int(paramValue)
# polarity
elif paramName == 'positive scan':
self.data['polarity'] = 1
elif paramName == 'negative scan':
self.data['polarity'] = -1
# total ion current
elif paramName == 'total ion current' and paramValue != None:
self.data['totIonCurrent'] = max(0.0, float(paramValue))
# base peak
elif paramName == 'base peak m/z' and paramValue != None:
self.data['basePeakMZ'] = float(paramValue)
elif paramName == 'base peak intensity' and paramValue != None:
self.data['basePeakIntensity'] = max(0.0, float(paramValue))
# mass range
elif paramName == 'lowest observed m/z' and paramValue != None:
self.data['lowMZ'] = float(paramValue)
elif paramName == 'highest observed m/z' and paramValue != None:
self.data['highMZ'] = float(paramValue)
# retention time
elif paramName == 'scan start time' and paramValue != None:
if attrs.get('unitName','') == 'minute':
self.data['retentionTime'] = float(paramValue)*60
elif attrs.get('unitName','') == 'second':
self.data['retentionTime'] = float(paramValue)
else:
self.data['retentionTime'] = float(paramValue)*60
# ----
def endElement(self, name):
"""Element ended."""
# stop parsing
if name == 'spectrum' and self._isMatch:
raise stopParsing()
# end spectrum element
elif name == 'spectrum':
self._isMatch = False
# end precursor element
elif name == 'precursor' and self._isMatch:
self._isPrecursor = False
# stop reading peaks data
elif name == 'binaryDataArray' and self._isMatch:
self._isBinaryDataArray = False
# mz array
if self.tmpArrayType == 'mzArray':
self.data['mzData'] = ''.join(self.tmpBinaryData)
self.data['mzPrecision'] = self.tmpPrecision
self.data['mzCompression'] = self.tmpCompression
# intensity array
elif self.tmpArrayType == 'intArray':
self.data['intData'] = ''.join(self.tmpBinaryData)
self.data['intPrecision'] = self.tmpPrecision
self.data['intCompression'] = self.tmpCompression
self.tmpBinaryData = None
self.tmpPrecision = None
self.tmpCompression = None
# stop reading binary array
elif name == 'binary' and self._isMatch:
self._isData = False
# ----
def characters(self, ch):
"""Grab characters."""
# get peaks
if self._isData:
self.tmpBinaryData.append(ch)
# ----
class runHandler(xml.sax.handler.ContentHandler):
"""Get whole run."""
def __init__(self):
self.data = {}
self.currentID = None
self._isSpectrum = False
self._isPrecursor = False
self._isBinaryDataArray = False
self._isData = False
self.tmpBinaryData = None
self.tmpPrecision = None
self.tmpCompression = None
self.tmpArrayType = None
# ----
def startElement(self, name, attrs):
"""Element started."""
# get scan metadata
if name == 'spectrum':
self._isSpectrum = True
# get scan ID
self.currentID = None
attribute = attrs.get('id', False)
if attribute:
self.currentID = _parseScanNumber(attribute)
scan = {
'title': '',
'scanNumber': self.currentID,
'parentScanNumber': None,
'msLevel': None,
'pointsCount': None,
'polarity': None,
'retentionTime': None,
'lowMZ': None,
'highMZ': None,
'basePeakMZ': None,
'basePeakIntensity': None,
'totIonCurrent': None,
'precursorMZ': None,
'precursorIntensity': None,
'precursorCharge': None,
'spectrumType': 'unknown',
'mzData': None,
'mzPrecision': None,
'mzCompression': None,
'intData': None,
'intPrecision': None,
'intCompression': None,
}
# get points count
attribute = attrs.get('defaultArrayLength', False)
if attribute:
scan['pointsCount'] = int(attribute)
# add scan
self.data[self.currentID] = scan
# precursor tag
elif name == 'precursor' and self._isSpectrum:
self._isPrecursor = True
# get parent scan number
attribute = attrs.get('spectrumRef', False)
if attribute:
self.data[self.currentID]['parentScanNumber'] = _parseScanNumber(attribute)
# binary aray tag
elif name == 'binaryDataArray' and self._isSpectrum:
self._isBinaryDataArray = True
self.tmpBinaryData = []
self.tmpPrecision = None
self.tmpCompression = None
self.tmpArrayType = None
# data array tag
elif name == 'binary' and self._isBinaryDataArray:
self._isData = True
# get precursor
elif name == 'cvParam' and self._isPrecursor:
paramName = attrs.get('name','')
paramValue = attrs.get('value','')
if paramName == 'selected ion m/z' and paramValue != None:
self.data[self.currentID]['precursorMZ'] = float(paramValue)
elif paramName == 'intensity' and paramValue != None:
self.data[self.currentID]['precursorIntensity'] = float(paramValue)
elif paramName == 'possible charge state' and paramValue != None:
self.data[self.currentID]['precursorCharge'] = int(paramValue)
elif paramName == 'charge state' and paramValue != None:
self.data[self.currentID]['precursorCharge'] = int(paramValue)
# get binary data metadata
elif name == 'cvParam' and self._isBinaryDataArray:
paramName = attrs.get('name','')
paramValue = attrs.get('value','')
# precision
if paramName == '64-bit float':
self.tmpPrecision = 64
elif paramName == '32-bit float':
self.tmpPrecision = 32
# compression
elif paramName == 'zlib compression':
self.tmpCompression = 'zlib'
elif paramName == 'no compression':
self.tmpCompression = None
# array type
elif paramName == 'm/z array':
self.tmpArrayType = 'mzArray'
elif paramName == 'intensity array':
self.tmpArrayType = 'intArray'
# get scan metadata
elif name == 'cvParam' and self._isSpectrum:
paramName = attrs.get('name','')
paramValue = attrs.get('value','')
# data type
if paramName == 'centroid spectrum':
self.data[self.currentID]['spectrumType'] = 'discrete'
elif paramName == 'profile spectrum':
self.data[self.currentID]['spectrumType'] = 'continuous'
# MS level
elif paramName == 'ms level' and paramValue != None:
self.data[self.currentID]['msLevel'] = int(paramValue)
# polarity
elif paramName == 'positive scan':
self.data[self.currentID]['polarity'] = 1
elif paramName == 'negative scan':
self.data[self.currentID]['polarity'] = -1
# total ion current
elif paramName == 'total ion current' and paramValue != None:
self.data[self.currentID]['totIonCurrent'] = max(0.0, float(paramValue))
# base peak
elif paramName == 'base peak m/z' and paramValue != None:
self.data[self.currentID]['basePeakMZ'] = float(paramValue)
elif paramName == 'base peak intensity' and paramValue != None:
self.data[self.currentID]['basePeakIntensity'] = max(0.0, float(paramValue))
# mass range
elif paramName == 'lowest observed m/z' and paramValue != None:
self.data[self.currentID]['lowMZ'] = float(paramValue)
elif paramName == 'highest observed m/z' and paramValue != None:
self.data[self.currentID]['highMZ'] = float(paramValue)
# retention time
elif paramName == 'scan start time' and paramValue != None:
if attrs.get('unitName','') == 'minute':
self.data[self.currentID]['retentionTime'] = float(paramValue)*60
elif attrs.get('unitName','') == 'second':
self.data[self.currentID]['retentionTime'] = float(paramValue)
else:
self.data[self.currentID]['retentionTime'] = float(paramValue)*60
# ----
def endElement(self, name):
"""Element ended."""
# end spectrum element
if name == 'spectrum':
self._isSpectrum = False
# end precursor element
elif name == 'precursor':
self._isPrecursor = False
# stop reading peaks data
elif name == 'binaryDataArray' and self._isSpectrum:
self._isBinaryDataArray = False
# mz array
if self.tmpArrayType == 'mzArray':
self.data[self.currentID]['mzData'] = ''.join(self.tmpBinaryData)
self.data[self.currentID]['mzPrecision'] = self.tmpPrecision
self.data[self.currentID]['mzCompression'] = self.tmpCompression
# intensity array
elif self.tmpArrayType == 'intArray':
self.data[self.currentID]['intData'] = ''.join(self.tmpBinaryData)
self.data[self.currentID]['intPrecision'] = self.tmpPrecision
self.data[self.currentID]['intCompression'] = self.tmpCompression
self.tmpBinaryData = None
self.tmpPrecision = None
self.tmpCompression = None
# stop reading binary array
elif name == 'binary':
self._isData = False
# ----
def characters(self, ch):
"""Grab characters."""
# get peaks
if self._isData:
self.tmpBinaryData.append(ch)
# ----
class stopParsing(Exception):
"""Exeption to stop parsing XML data."""
pass
def _parseScanNumber(string):
"""Parse real scan number from id tag."""
# match scan number pattern
match = SCAN_NUMBER_PATTERN.search(string)
if not match:
return None
# convert to int
try: return int(match.group(1))
except: return None
# ----