File: parser_mzdata.py

package info (click to toggle)
mmass 5.1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 8,396 kB
  • sloc: python: 33,183; xml: 7,925; ansic: 1,722; makefile: 83; sh: 2
file content (1009 lines) | stat: -rw-r--r-- 33,232 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
# -------------------------------------------------------------------------
#     Copyright (C) 2005-2012 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 struct
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


# PARSE mzData DATA
# -----------------

class parseMZDATA():
    """Parse data from mzData."""
    
    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]['mzEndian']
                del self._scanlist[scanNumber]['mzPrecision']
                del self._scanlist[scanNumber]['intData']
                del self._scanlist[scanNumber]['intEndian']
                del self._scanlist[scanNumber]['intPrecision']
    # ----
    
    
    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]
        
        # faster loading of single-scan documents
        elif scanID == None:
            parser = singleScanParser(self.path)
            parser.parse()
            data = parser.data
        
        # 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'])
        
        # get endian
        mzEndian = '!'
        intEndian = '!'
        if scanData['mzEndian'] == 'little':
            mzEndian = '<'
        elif scanData['mzEndian'] == 'big':
            mzEndian = '>'
        if scanData['intEndian'] == 'little':
            intEndian = '<'
        elif scanData['intEndian'] == 'big':
            intEndian = '>'
        
        # 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(mzEndian + mzPrecision)
        mzData = struct.unpack(mzEndian + mzPrecision * count, mzData[0:len(mzData)])
        count = len(intData) / struct.calcsize(intEndian + intPrecision)
        intData = struct.unpack(intEndian + 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._isSampleName = False
        self._isContact = False
        self._isName = False
        self._isInstitution = False
        self._isContactInfo = False
        self._isInstrumentName = False
    # ----
    
    
    def startElement(self, name, attrs):
        """Element started."""
        
        # get instrument
        if name == 'sampleName':
             self._isSampleName = True
        if name == 'contact':
             self._isContact = True
        elif name == 'name' and self._isContact:
             self._isName = True
        elif name == 'institution':
             self._isInstitution = True
        elif name == 'contactInfo':
             self._isContactInfo = True
        elif name == 'instrumentName':
             self._isInstrumentName = True
    # ----
    
    
    def endElement(self, name):
        """Element ended."""
        
        # stop parsing
        if name == 'description':
            raise stopParsing()
        
        # stop elements
        if name == 'sampleName':
             self._isSampleName = False
        if name == 'contact':
             self._isContact = False
             self._isName = False
        elif name == 'name':
             self._isName = False
        elif name == 'institution':
             self._isInstitution = False
        elif name == 'contactInfo':
             self._isContactInfo = False
        elif name == 'instrumentName':
             self._isInstrumentName = False
    # ----
    
    
    def characters(self, ch):
        """Grab characters."""
        
        # get data
        if self._isSampleName:
            self.data['title'] += ch
        elif self._isName:
            self.data['operator'] += ch
        elif self._isInstitution:
            self.data['institution'] += ch
        elif self._isContactInfo:
            self.data['contact'] += ch
        elif self._isInstrumentName:
            self.data['instrument'] += ch
    # ----
    
    

class scanlistHandler(xml.sax.handler.ContentHandler):
    """Get list of all scans in the document."""
    
    def __init__(self):
        self.data = {}
        self.currentID = None
    # ----
    
    
    def startElement(self, name, attrs):
        """Element started."""
        
        # get scan metadata
        if name == 'spectrum':
            
            # get scan ID
            self.currentID = attrs.get('id', None)
            if self.currentID != None:
                self.currentID = int(self.currentID)
            
            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',
            }
            
            # add scan
            self.data[self.currentID] = scan
        
        # get spectrum type
        elif name == 'acqSpecification':
            attribute = attrs.get('spectrumType', False)
            if attribute:
                self.data[self.currentID]['spectrumType'] = attribute
        
        # get other params
        elif name == 'spectrumInstrument':
            
            # get ms level
            attribute = attrs.get('msLevel', 1)
            if attribute:
                self.data[self.currentID]['msLevel'] = int(attribute)
            
            # get low m/z
            attribute = attrs.get('mzRangeStart', None)
            if attribute != None:
                self.data[self.currentID]['lowMZ'] = float(attribute)
            
            # get high m/z
            attribute = attrs.get('mzRangeStop', None)
            if attribute != None:
                self.data[self.currentID]['highMZ'] = float(attribute)
        
        # get other params
        elif name == 'userParam' or name == 'cvParam':
            paramName = attrs.get('name', None)
            paramValue = attrs.get('value', None)
            
            # get retention time
            if paramName == 'TimeInMinutes' and paramValue != None:
                try: self.data[self.currentID]['retentionTime'] = float(paramValue)*60
                except ValueError: pass
            
            # get total ion current
            elif paramName == 'TotalIonCurrent' and paramValue != None:
                try: self.data[self.currentID]['totIonCurrent'] = float(paramValue)
                except ValueError: pass
            
            # get precursor m/z
            elif paramName == 'MassToChargeRatio' and paramValue != None:
                try: self.data[self.currentID]['precursorMZ'] = float(paramValue)
                except ValueError: pass
            
            # get precursor m/z
            elif paramName == 'ChargeState' and paramValue != None:
                try: self.data[self.currentID]['precursorCharge'] = int(paramValue)
                except ValueError: pass
            
            # get polarity
            elif paramName == 'Polarity':
                if paramValue in ('positive', 'Positive', '+'):
                    self.data[self.currentID]['polarity'] = 1
                elif paramValue == ('negative', 'Negative', '-'):
                    self.data[self.currentID]['polarity'] = -1
        
        # get parent scan
        elif name == 'precursor':
            attribute = attrs.get('spectrumRef', None)
            if attribute != None:
                self.data[self.currentID]['parentScanNumber'] = int(attribute)
        
        # get spectrum length
        elif name == 'data':
            attribute = attrs.get('length', None)
            if attribute != None:
                self.data[self.currentID]['pointsCount'] = int(attribute)
    # ----
    
    
    def endElement(self, name):
        """Element ended."""
        pass
    # ----
    
    
    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._isMzArray = False
        self._isIntArray = False
    # ----
    
    
    def startElement(self, name, attrs):
        """Element started."""
        
        # get scan metadata
        if name == 'spectrum':
            self._isMatch = False
            
            # get scan ID
            scanID = attrs.get('id', None)
            if scanID != None:
                scanID = int(scanID)
            
            # selected scan
            if self.scanID == None or scanID == self.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,
                    'mzEndian': None,
                    'mzPrecision': None,
                    'intData': None,
                    'intEndian': None,
                    'intPrecision': None,
                }
        
        # get spectrum type
        elif name == 'acqSpecification' and self._isMatch:
            attribute = attrs.get('spectrumType', False)
            if attribute:
                self.data['spectrumType'] = attribute
        
        # get other params
        elif name == 'spectrumInstrument' and self._isMatch:
            
            # get ms level
            attribute = attrs.get('msLevel', 1)
            if attribute:
                self.data['msLevel'] = int(attribute)
            
            # get low m/z
            attribute = attrs.get('mzRangeStart', None)
            if attribute != None:
                self.data['lowMZ'] = float(attribute)
            
            # get high m/z
            attribute = attrs.get('mzRangeStop', None)
            if attribute != None:
                self.data['highMZ'] = float(attribute)
        
        # get other params
        elif (name == 'userParam' or name == 'cvParam') and self._isMatch:
            paramName = attrs.get('name','')
            paramValue = attrs.get('value', None)
            
            # get retention time
            if paramName == 'TimeInMinutes' and paramValue != None:
                try: self.data['retentionTime'] = float(paramValue)*60
                except ValueError: pass
            
            # get total ion current
            elif paramName == 'TotalIonCurrent' and paramValue != None:
                try: self.data['totIonCurrent'] = float(paramValue)
                except ValueError: pass
            
            # get precursor m/z
            elif paramName == 'MassToChargeRatio' and paramValue != None:
                try: self.data['precursorMZ'] = float(paramValue)
                except ValueError: pass
            
            # get precursor m/z
            elif paramName == 'ChargeState' and paramValue != None:
                try: self.data['precursorCharge'] = int(paramValue)
                except ValueError: pass
            
            # get polarity
            elif paramName == 'Polarity':
                if paramValue in ('positive', 'Positive', '+'):
                    self.data['polarity'] = 1
                elif paramValue == ('negative', 'Negative', '-'):
                    self.data['polarity'] = -1
        
        # get parent scan
        elif name == 'precursor' and self._isMatch:
            attribute = attrs.get('spectrumRef', None)
            if attribute != None:
                self.data['parentScanNumber'] = int(attribute)
        
        # get mz data
        elif name == 'mzArrayBinary' and self._isMatch:
            self._isMzArray = True
            self.data['mzData'] = ''
        
        # get int data
        elif name == 'intenArrayBinary' and self._isMatch:
            self._isIntArray = True
            self.data['intData'] = ''
        
        # get data
        elif name == 'data' and self._isMatch:
            
            # get points count
            attribute = attrs.get('length', None)
            if attribute != None:
                self.data['pointsCount'] = int(attribute)
            
            # get array params
            endian = attrs.get('endian','network')
            precision = attrs.get('precision', 32)
            
            if self._isMzArray:
                self.data['mzEndian'] = endian
                if precision:
                    self.data['mzPrecision'] = int(precision)
            
            elif self._isIntArray:
                self.data['intEndian'] = endian
                if precision:
                    self.data['intPrecision'] = int(precision)
    # ----
    
    
    def endElement(self, name):
        """Element ended."""
        
        # stop parsing
        if name == 'spectrum' and self._isMatch:
            raise stopParsing()
        
        # stop reading mz data
        elif name == 'mzArrayBinary' and self._isMatch:
            self._isMzArray = False
            if not self.data['mzData']:
                self.data['mzData'] = None
        
        # stop reading int data
        elif name == 'intenArrayBinary' and self._isMatch:
            self._isIntArray = False
            if not self.data['intData']:
                self.data['intData'] = None
    # ----
    
    
    def characters(self, ch):
        """Grab characters."""
        
        # get m/z array
        if self._isMzArray:
            self.data['mzData'] += ch
        
        # get intensity array
        elif self._isIntArray:
            self.data['intData'] += ch
    # ----
    
    

class runHandler(xml.sax.handler.ContentHandler):
    """Get whole run."""
    
    def __init__(self):
        self.data = {}
        self.currentID = None
        
        self._isMzArray = False
        self._isIntArray = False
    # ----
    
    
    def startElement(self, name, attrs):
        """Element started."""
        
        # get scan metadata
        if name == 'spectrum':
            
            # get scan ID
            self.currentID = attrs.get('id', None)
            if self.currentID != None:
                self.currentID = int(self.currentID)
            
            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,
                'mzEndian': None,
                'mzPrecision': None,
                'intData': None,
                'intEndian': None,
                'intPrecision': None,
            }
            
            # add scan
            self.data[self.currentID] = scan
        
        # get spectrum type
        elif name == 'acqSpecification':
            attribute = attrs.get('spectrumType', False)
            if attribute:
                self.data[self.currentID]['spectrumType'] = attribute
        
        # get other params
        elif name == 'spectrumInstrument':
            
            # get ms level
            attribute = attrs.get('msLevel', 1)
            if attribute:
                self.data[self.currentID]['msLevel'] = int(attribute)
            
            # get low m/z
            attribute = attrs.get('mzRangeStart', None)
            if attribute != None:
                self.data[self.currentID]['lowMZ'] = float(attribute)
            
            # get high m/z
            attribute = attrs.get('mzRangeStop', None)
            if attribute != None:
                self.data[self.currentID]['highMZ'] = float(attribute)
        
        # get other params
        elif (name == 'userParam' or name == 'cvParam'):
            paramName = attrs.get('name','')
            paramValue = attrs.get('value', None)
            
            # get retention time
            if paramName == 'TimeInMinutes' and paramValue != None:
                try: self.data[self.currentID]['retentionTime'] = float(paramValue)*60
                except ValueError: pass
            
            # get total ion current
            elif paramName == 'TotalIonCurrent' and paramValue != None:
                try: self.data[self.currentID]['totIonCurrent'] = float(paramValue)
                except ValueError: pass
            
            # get precursor m/z
            elif paramName == 'MassToChargeRatio' and paramValue != None:
                try: self.data[self.currentID]['precursorMZ'] = float(paramValue)
                except ValueError: pass
            
            # get precursor m/z
            elif paramName == 'ChargeState' and paramValue != None:
                try: self.data[self.currentID]['precursorCharge'] = int(paramValue)
                except ValueError: pass
            
            # get polarity
            elif paramName == 'Polarity':
                if paramValue in ('positive', 'Positive', '+'):
                    self.data[self.currentID]['polarity'] = 1
                elif paramValue == ('negative', 'Negative', '-'):
                    self.data[self.currentID]['polarity'] = -1
        
        # get parent scan
        elif name == 'precursor':
            attribute = attrs.get('spectrumRef', None)
            if attribute != None:
                self.data[self.currentID]['parentScanNumber'] = int(attribute)
        
        # get mz data
        elif name == 'mzArrayBinary':
            self._isMzArray = True
            self.data[self.currentID]['mzData'] = ''
        
        # get int data
        elif name == 'intenArrayBinary':
            self._isIntArray = True
            self.data[self.currentID]['intData'] = ''
        
        # get data
        elif name == 'data':
            
            # get points count
            attribute = attrs.get('length', None)
            if attribute != None:
                self.data[self.currentID]['pointsCount'] = int(attribute)
            
            # get array params
            endian = attrs.get('endian','network')
            precision = attrs.get('precision', 32)
            
            if self._isMzArray:
                self.data[self.currentID]['mzEndian'] = endian
                if precision:
                    self.data[self.currentID]['mzPrecision'] = int(precision)
            
            elif self._isIntArray:
                self.data[self.currentID]['intEndian'] = endian
                if precision:
                    self.data[self.currentID]['intPrecision'] = int(precision)
    # ----
    
    
    def endElement(self, name):
        """Element ended."""
        
        # stop reading mz data
        if name == 'mzArrayBinary':
            self._isMzArray = False
            if not self.data[self.currentID]['mzData']:
                self.data[self.currentID]['mzData'] = None
        
        # stop reading int data
        elif name == 'intenArrayBinary':
            self._isIntArray = False
            if not self.data[self.currentID]['intData']:
                self.data[self.currentID]['intData'] = None
    # ----
    
    
    def characters(self, ch):
        """Grab characters."""
        
        # get m/z array
        if self._isMzArray:
            self.data[self.currentID]['mzData'] += ch
        
        # get intensity array
        elif self._isIntArray:
            self.data[self.currentID]['intData'] += ch
    # ----
    
    

class singleScanParser():
    """Faster loading of single-scan documents."""
    
    def __init__(self, path):
        
        self.path = path
        self.data = None
        self._parsedData = None
    # ----
    
    
    def parse(self):
        """Parse document."""
        
        # read xml
        try:
            doc = file(self.path)
            rawData = doc.read()
            doc.close()
            self._parsedData = xml.dom.minidom.parseString(rawData)
        except:
            self.data = None
            return
        
        # init data
        self.data = {
                'title': '',
                'scanNumber': None,
                '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,
                'mzEndian': None,
                'mzPrecision': None,
                'intData': None,
                'intEndian': None,
                'intPrecision': None,
        }
        
        # parse xml
        self.handleSpectrum()
        self.handleMetadata()
    # ----
    
    
    def handleSpectrum(self):
        """Get spectrum data."""
        
        # get spectrum type
        acqSpecificationTags = self._parsedData.getElementsByTagName('acqSpecification')
        if acqSpecificationTags:
            self.data['spectrumType'] = acqSpecificationTags[0].getAttribute('spectrumType')
        
        # get mz data
        mzArrayBinaryTags = self._parsedData.getElementsByTagName('mzArrayBinary')
        if mzArrayBinaryTags:
            dataTags = mzArrayBinaryTags[0].getElementsByTagName('data')
            if dataTags:
                
                # get points count
                attribute = dataTags[0].getAttribute('length')
                if attribute:
                    self.data['pointsCount'] = int(attribute)
                
                # get endian
                attribute = dataTags[0].getAttribute('endian')
                if attribute:
                    self.data['mzEndian'] = attribute
                
                # get precision
                attribute = dataTags[0].getAttribute('precision')
                if attribute:
                    try: self.data['mzPrecision'] = int(attribute)
                    except ValueError: pass
                
                # get array data
                self.data['mzData'] = ''
                for node in dataTags[0].childNodes:
                    if node.nodeType == node.TEXT_NODE:
                        self.data['mzData'] += node.data
        
        # get int data
        intenArrayBinaryTags = self._parsedData.getElementsByTagName('intenArrayBinary')
        if intenArrayBinaryTags:
            dataTags = intenArrayBinaryTags[0].getElementsByTagName('data')
            if dataTags:
                
                # get endian
                attribute = dataTags[0].getAttribute('endian')
                if attribute:
                    self.data['intEndian'] = attribute
                
                # get precision
                attribute = dataTags[0].getAttribute('precision')
                if attribute:
                    try: self.data['intPrecision'] = int(attribute)
                    except ValueError: pass
                
                # get array data
                self.data['intData'] = ''
                for node in dataTags[0].childNodes:
                    if node.nodeType == node.TEXT_NODE:
                        self.data['intData'] += node.data
    # ----
    
    
    def handleMetadata(self):
        """Get metadata."""
        
        # get spectrum params
        spectrumInstrumentTags = self._parsedData.getElementsByTagName('spectrumInstrument')
        if spectrumInstrumentTags:
            
            # get ms level
            attribute = spectrumInstrumentTags[0].getAttribute('msLevel')
            if attribute:
                self.data['msLevel'] = int(attribute)
            
            # get low m/z
            attribute = spectrumInstrumentTags[0].getAttribute('mzRangeStart')
            if attribute:
                self.data['lowMZ'] = float(attribute)
            
            # get high m/z
            attribute = spectrumInstrumentTags[0].getAttribute('mzRangeStop')
            if attribute:
                self.data['highMZ'] = float(attribute)
        
        # get cvParams
        cvParamTags = self._parsedData.getElementsByTagName('cvParam')
        for cvParamTag in cvParamTags:
            
            paramName = cvParamTag.getAttribute('name')
            paramValue = cvParamTag.getAttribute('value')
            
            # get retention time
            if paramName == 'TimeInMinutes' and paramValue:
                try: self.data['retentionTime'] = float(paramValue)*60
                except ValueError: pass
            
            # get total ion current
            elif paramName == 'TotalIonCurrent' and paramValue:
                try: self.data['totIonCurrent'] = float(paramValue)
                except ValueError: pass
            
            # get precursor m/z
            elif paramName == 'MassToChargeRatio' and paramValue:
                try: self.data['precursorMZ'] = float(paramValue)
                except ValueError: pass
            
            # get precursor charge
            elif paramName == 'ChargeState' and paramValue:
                try: self.data['precursorCharge'] = int(paramValue)
                except ValueError: pass
            
            # get polarity
            elif paramName == 'Polarity':
                if paramValue in ('positive', 'Positive', '+'):
                    self.data['polarity'] = 1
                elif paramValue == ('negative', 'Negative', '-'):
                    self.data['polarity'] = -1
    # ----
    
    

class stopParsing(Exception):
    """Exeption to stop parsing XML data."""
    pass