File: specfilewrapper.py

package info (click to toggle)
pymca 5.8.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 44,392 kB
  • sloc: python: 155,456; ansic: 15,843; makefile: 116; sh: 73; xml: 55
file content (684 lines) | stat: -rw-r--r-- 27,527 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
#/*##########################################################################
#
# The PyMca X-Ray Fluorescence Toolkit
#
# Copyright (c) 2004-2022 European Synchrotron Radiation Facility
#
# This file is part of the PyMca X-ray Fluorescence Toolkit developed at
# the ESRF by the Software group.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
#############################################################################*/
__author__ = "V.A. Sole - ESRF Data Analysis"
__contact__ = "sole@esrf.fr"
__license__ = "MIT"
__copyright__ = "European Synchrotron Radiation Facility, Grenoble, France"
import os
import sys
import numpy
import re
import logging
from PyMca5.PyMcaIO import specfile
from PyMca5.PyMcaIO import Fit2DChiFileParser
from PyMca5.PyMcaIO import APSMEDFileParser
from PyMca5.PyMcaIO import SRSFileParser
from PyMca5.PyMcaIO import BAXSCSVFileParser
from PyMca5.PyMcaIO import OlympusCSVFileParser
from PyMca5.PyMcaIO import ThermoEMSFileParser
from PyMca5.PyMcaIO import JcampFileParser
from PyMca5.PyMcaIO import BlissSpecFile

_logger = logging.getLogger(__name__)

try:
    from PyMca5.PyMcaIO import ArtaxFileParser
    SPX = True
except:
    _logger.info("specfilewrapper cannot import ArtaxFileParser")
    SPX = False


if sys.version >= '2.6':
    def safe_str(bytesObject):
        try:
            return str(bytesObject, 'utf-8')
        except UnicodeDecodeError:
            try:
                return str(bytesObject, 'latin-1')
            except:
                try:
                    return str(bytesObject, 'utf-16')
                except:
                    return str(bytesObject)
else:
    def safe_str(*var, **kw):
        return str(var[0])

    #python 2.5 does not have bytes function
    def bytes(*var, **kw):
        return var[0]

def Specfile(filename):
    if BlissSpecFile.isBlissSpecFile(filename):
        return BlissSpecFile.BlissSpecFile(filename)
    if sys.version_info < (3, 0):
        f = open(filename)
    else:
        f = open(filename, 'r', errors="ignore")
    line0  = f.readline()
    if filename.upper().endswith('DTA'):
        #TwinMic single column file
        line = line0 * 1
        line = line.replace('\r','')
        line = line.replace('\n','')
        line = line.replace('\t',' ')
        s = line.split(' ')
        if len(s) == 2:
            if len(s[-1]) == 0:
                try:
                    float(s[0])
                    f.close()
                    output = specfilewrapper(filename, dta=True)
                    return output
                except:
                    #try to read in other way
                    pass

    # this piece of code checks if we deal with a SPEC file
    # Prior to any data, all lines have to be either empty or starting
    # by the hash character.
    line = line0
    while(len(line)):
        if len(line) > 1:
            if line[0:2] == '#S':
                if ('#SIGNALTYPE' in line) or \
                   ('#SPECTRUM' in line):
                    line = ""
                break
            elif line[0] not in ['#', ' ', '\r']:
                line = ""
                break
        try:
            line = f.readline()
        except:
            line = ""
            break
    f.close()
    # end of specfile identification
    amptek = False
    qxas   = False
    if len(line):
        #it is a Specfile
        _logger.debug("This looks as a specfile")
        output=specfile.Specfile(filename)
    elif SPX and ArtaxFileParser.isArtaxFile(filename):
        _logger.debug("This looks as an Artax file")
        output = ArtaxFileParser.ArtaxFileParser(filename)
    else:
        _logger.debug("this does not look as a specfile")
        if len(line0) > 7:
            if line0.startswith('$SPEC_ID') or\
               line0.startswith('$DATE_MEA') or\
               line0.startswith('$MEAS_TIM') or\
               line0.startswith('$Core_ID') or\
               line0.startswith('$Section_ID'):
                qxas = True
        if (not qxas) and line0.startswith('<<'):
                amptek = True
        if (not qxas) and (not amptek) and Fit2DChiFileParser.isFit2DChiFile(filename):
            return Fit2DChiFileParser.Fit2DChiFileParser(filename)
        if (not qxas) and (not amptek) and APSMEDFileParser.isAPSMEDFile(filename):
            return APSMEDFileParser.APSMEDFileParser(filename)
        if (not qxas) and (not amptek) and SRSFileParser.isSRSFile(filename):
            _logger.debug("SRSFileParser")
            return SRSFileParser.SRSFileParser(filename)
        if (not qxas) and (not amptek) and BAXSCSVFileParser.isBAXSCSVFile(filename):
            _logger.debug("BAXSCSVFileParser")
            return BAXSCSVFileParser.BAXSCSVFileParser(filename)
        if (not qxas) and (not amptek) and \
           OlympusCSVFileParser.isOlympusCSVFile(filename):
            _logger.debug("OlympusCSVFileParser")
            return OlympusCSVFileParser.OlympusCSVFileParser(filename)
        if (not qxas) and (not amptek) and \
           ThermoEMSFileParser.isThermoEMSFile(filename):
            _logger.debug("ThermoEMSFileParser")
            return ThermoEMSFileParser.ThermoEMSFileParser(filename)
        if (not qxas) and (not amptek) and \
           JcampFileParser.isJcampFile(filename):
            _logger.debug("JcampFileParser")
            return JcampFileParser.JcampFileParser(filename)
        output = specfilewrapper(filename, amptek=amptek, qxas=qxas)
    return output

class specfilewrapper(object):
    def __init__(self, filename, amptek=None, qxas=None, dta=None):
        if amptek is None:
            amptek = False
        if qxas is None:
            qxas = False
        if dta is None:
            dta = False
        self.amptek = amptek
        self.qxas = qxas
        self.dta = dta
        self.ketek = None
        self.header = []
        if self.dta:
            #TwinMic .dta files with only one spectrum
            if 0:
                f = open(filename, 'rb')
                raw_content = f.read()
                f.close()
                expr = '([-+]?\d+)\t\r\n'
                self.data = [float(i) for i in re.split(expr,raw_content) if i != '']
                self.data = numpy.array(self.data, numpy.float32)
            else:
                self.data = numpy.fromfile(filename,
                                           dtype=numpy.float32,
                                           sep='\t\r\n')
            self.header = ['#S1 %s' % os.path.basename(filename)]
            self.data.shape = -1, 1
            self.scandata=[myscandata(self.data,'MCA','1.1',
                                      scanheader=self.header)]
            return
        if self.qxas:
            f = open(filename)
        else:
            f = BufferedFile(filename)
        line = f.readline()
        outdata = []
        ncol0 = -1
        nlines= 0
        if amptek:
            if sys.version < '3.0':
                while "<<DATA>>" not in line:
                    self.header.append(line.replace("\n",""))
                    line = f.readline()
            else:
                while bytes("<<DATA>>", 'utf-8') not in line:
                    self.header.append(safe_str(line.replace(bytes("\n", 'utf-8'),
                                                    bytes("", 'utf-8'))))
                    line = f.readline()
        elif qxas:
            line.replace("\n","")
            line.replace("\x00","")
            self._qxasHeader = {}
            self._qxasHeader['S'] = '#S1 '+ " Unlabelled Spectrum"
            while 1:
                self.header.append(line)
                if line.startswith('$SPEC_ID:'):
                    line = f.readline().replace("\n","")
                    line.replace("\x00","")
                    self.header.append(line)
                    self._qxasHeader['S'] = '#S1 '+ line
                if line.startswith('$DATE_MEA'):
                    line = f.readline().replace("\n","")
                    self.header.append(line)
                    self._qxasHeader['D'] = line
                if line.startswith('$MEAS_TIM'):
                    line = f.readline().replace("\n","")
                    self.header.append(line)
                    tmpList = [float(i) for i in line.split()]
                    if len(tmpList) == 1:
                        preset = tmpList[0]
                        elapsed = preset
                    else:
                        preset, elapsed = tmpList[0:2]
                    self._qxasHeader['@CTIME'] = ['#@CTIME %f %f %f' % (preset, preset, elapsed)]
                if line.startswith('$MCA_CAL'):
                    try:
                       line = f.readline().replace("\n","")
                       self.header.append(line)
                       if line.startswith('$'):
                           continue
                       line = f.readline().replace("\n","")
                       self.header.append(line)
                       if line.startswith('$'):
                           continue
                       coefficients = [float(i) for i in line.split()]
                       if len(coefficients) == 2:
                           coefficients.append(0.0)
                       self._qxasHeader['@CALIB']=  ['#@CALIB %f  %f  %f' %\
                                            (coefficients[0], coefficients[1], coefficients[2])]
                    except:
                        pass
                if line.startswith('$DATA:'):
                    line = f.readline().replace("\n","")
                    self.header.append(line)
                    start, stop = [int(i) for i in line.split()]
                    self._qxasHeader['@CHANN'] = ['#@CHANN  %d  %d  %d  1' % (stop-start+1, start, stop)]
                    break
                line = f.readline().replace("\n","")
        if qxas:
            outdata = []
            line = f.readline().replace("\n","")
            while len(line):
                if line[0] == "$":
                    break
                outdata += [float(x) for x in line.split()]
                line = f.readline().replace("\n","")
            nlines = len(outdata)
            f.close()
            self.data = numpy.resize(numpy.array(outdata).astype(numpy.float64),(nlines,1))
        else:
            if sys.version < '3.0':
                line = line.replace(",","  ")
                line = line.replace(";","  ")
                line = line.replace("\t","  ")
                line = line.replace("\r","\n")
                line = line.replace('"',"")
                line = line.replace('\n\n',"\n")
            else:
                tmpBytes = bytes(" ",'utf-8')
                line = line.replace(bytes(",",'utf-8'), tmpBytes)
                line = line.replace(bytes(";",'utf-8'), tmpBytes)
                line = line.replace(bytes("\t",'utf-8'), tmpBytes)
                tmpBytes = bytes("\n",'utf-8')
                line = line.replace(bytes("\r","utf-8"), tmpBytes)
                line = line.replace(bytes('"',"utf-8"), bytes("", "utf-8"))
                line = line.replace(bytes('\n\n',"utf-8"), tmpBytes)
            while(len(line)):
                values = line.split()
                if len(values):
                    try:
                        reals = [float(x) for x in values]
                        ncols = len(reals)
                        if ncol0 < 0:ncol0 = ncols
                        if ncols == ncol0:
                            outdata.append(reals)
                            nlines += 1
                    except:
                        if len(line) > 1:
                            if sys.version < '3.0':
                                self.header.append(line.replace("\n",""))
                            else:
                                self.header.append(safe_str(line.replace(\
                                                    bytes("\n",'utf-8'),\
                                                    bytes("", 'utf-8'))))
                else:
                    if len(line) > 1:
                        if sys.version < '3.0':
                            self.header.append(line.replace("\n",""))
                        else:
                            self.header.append(safe_str(line.replace(bytes("\n",'utf-8'),
                                                            bytes("", 'utf-8'))))
                line = f.readline()
                if sys.version < '3.0':
                    line = line.replace(",","  ")
                    line = line.replace(";","  ")
                    line = line.replace("\t","  ")
                    line = line.replace("\r","\n")
                    line = line.replace('"',"")
                    line = line.replace('\n\n',"\n")
                else:
                    tmpBytes = bytes(" ",'utf-8')
                    line = line.replace(bytes(",",'utf-8'), tmpBytes)
                    line = line.replace(bytes(";",'utf-8'), tmpBytes)
                    line = line.replace(bytes("\t",'utf-8'), tmpBytes)
                    tmpBytes = bytes("\n",'utf-8')
                    line = line.replace(bytes("\r","utf-8"), tmpBytes)
                    line = line.replace(bytes('"',"utf-8"), bytes("", "utf-8"))
                    line = line.replace(bytes('\n\n',"utf-8"), tmpBytes)
            f.close()
            self.data = numpy.resize(numpy.array(outdata).astype(numpy.float64),(nlines,ncol0))
        if self.amptek:
            self.scandata=[myscandata(self.data,'MCA','1.1',
                                      scanheader=self.header)]
        elif self.qxas:
            self.scandata=[myscandata(self.data,'MCA','1.1',
                                      scanheader=self.header,
                                      qxas=self._qxasHeader)]
        else:
            labels = None
            if len(self.header) == 1:
                if len(self.header[0]) > 0:
                    labels = self.header[0].split("  ")
                    if len(labels) != ncol0:
                        labels = None
            # check if it is a KETEK AXAS-D file
            ketek_keys = ["File Version = ",
                          "Livetime = ", "Live Time: = ",
                          "Realtime = ", "Real Time: = ",
                          "Input Count Rate = ", "ICR: = ",
                          "Output Count Rate = ", "OCR: = ",
                          "= KETEK"]
            ketek_counter = 0
            icr = None
            ocr = None
            live_time = None
            live_time = None
            real_time = None
            for line in self.header:
                for key in ketek_keys:
                    if key in line:
                        keylower = line.lower()
                        if keylower.startswith("livetime =") or keylower.startswith("live time: = "):
                            tokens = line.split(" = ")[-1].split()
                            if tokens[-1] == "s":
                                if "." in tokens[0]:
                                    live_time = float(tokens[0])
                                else:
                                    live_time = float(tokens[0] + "." + tokens[1])
                        elif keylower.startswith("realtime =") or keylower.startswith("real time: = "):
                            tokens = line.split(" = ")[-1].split()
                            if tokens[-1] == "s":
                                if "." in tokens[0]:
                                    real_time = float(tokens[0]) 
                                else:
                                    real_time = float(tokens[0] + "." + tokens[1])
                        elif keylower.startswith("input count rate = ") or keylower.startswith("icr: = "):
                            tokens = line.split(" = ")[-1].split()
                            if "." in tokens[0]:
                                icr = float(tokens[0]) 
                            else:
                                icr = float(tokens[0] + "." + tokens[1])
                        elif keylower.startswith("output count rate = ") or keylower.startswith("ocr: = "):
                            tokens = line.split(" = ")[-1].split()
                            if "." in tokens[0]:
                                ocr = float(tokens[0]) 
                            else:
                                ocr = float(tokens[0] + "." + tokens[1])                            
                        ketek_counter += 1
                        break
            if ketek_counter >= 4:
                self.ketek = 1
                if real_time and live_time:
                    self._ketekHeader = {}
                    self._ketekHeader['S'] = '#S1 '+ " Unlabelled Spectrum"
                    if ocr and icr:
                        live_time = real_time * ocr / icr
                        _logger.info("Taking live time =  real_time * ocr / icr")
                    else:
                        _logger.warning("Taking live time from file")
                    self._ketekHeader['@CTIME'] = ['#@CTIME %f %f %f' % (real_time,
                                                                         live_time,
                                                                         real_time)]
                else:
                    self._ketekHeader = None
                self.scandata=[myscandata(self.data,'MCA','1.1',
                                      fileheader=self.header,
                                      qxas=self._ketekHeader)]
            else:
                self.scandata=[myscandata(self.data,'SCAN','1.1',
                                      labels=labels,
                                      fileheader=self.header),
                               myscandata(self.data,'MCA','2.1',
                                      fileheader=self.header)]

    def list(self):
        if self.amptek or self.qxas or self.dta or self.ketek:
            return "1:1"
        else:
            return "1:2"

    def __getitem__(self,item):
        return self.scandata[item]

    def __len__(self):
        return self.scanno()

    def select(self,i):
        n = i.split(".")
        return self.__getitem__(int(n[0]) - 1)

    def scanno(self):
        if self.amptek or self.qxas or self.dta or self.ketek:
            return 1
        else:
            return 2

class myscandata(object):
    def __init__(self, data, scantype=None, identification=None,
                 scanheader=None, qxas=None, labels=None, fileheader=None):
        if identification is None:
            identification='1.1'
        if scantype is None:
            scantype='SCAN'
        self.qxas = qxas
        self.scanheader = scanheader
        if fileheader is None:
            fileheader = []
        self._fileheader = fileheader
        #print shape(data)
        (rows, cols) = numpy.shape(data)
        if scantype == 'SCAN':
            self.__data = numpy.zeros((rows, cols +1 ), numpy.float64)
            self.__data[:,0] = numpy.arange(rows) * 1.0
            self.__data[:,1:] = data * 1
            self.__cols = cols + 1
            self.labels = ['Point']
            if labels is None:
                for i in range(cols):
                    self.labels.append('Column %d'  % i)
            else:
                for label in labels:
                    self.labels.append('%s' % label)
        else:
            self.__data = data
            self.__cols = cols
            self.labels = []
        self.scantype = scantype
        self.rows = rows
        if scanheader is None:
            labels = '#L '
            for label in self.labels:
                labels += '  '+label
            if self.scantype == 'SCAN':
                self.scanheader = ['#S1 Unknown command',
                              '#N %d' % len(self.labels),
                              labels]
            else:
                self.scanheader = ['#S1 Unknown command']

        n = identification.split(".")
        self.__number = int(n[0])
        self.__order  = int(n[1])

    def alllabels(self):
        if self.scantype == 'SCAN':
            return self.labels
        else:
            return []

    def allmotorpos(self):
        return []

    def cols(self):
        return self.__cols

    def command(self):
        _logger.debug("command called")
        if self.qxas is not None:
            if 'S' in self.qxas:
                text = self.qxas['S']
        elif self.scanheader is not None:
            if len(self.scanheader):
                text = self.scanheader[0]
        return text

    def data(self):
        return numpy.transpose(self.__data)

    def datacol(self, col):
        # it is awful that starts at one ...
        if col <= 0:
            raise ValueError("Specfile column numberig starts at 1")
        return self.__data[:, col - 1]

    def dataline(self, line):
        # it is awful that starts at one ...
        if line <= 0:
            raise ValueError("Specfile line numberig starts at 1")
        return self.__data[line - 1,:]


    def date(self):
        text = 'sometime'
        if self.qxas is not None:
            if 'D' in self.qxas:
                return self.qxas['D']
        elif self.scanheader is not None:
            for line in self.scanheader:
                if 'START_TIME' in line:
                    text = "%s" % line
                    break
        return text

    def fileheader(self, key=''):
        # key is there for compatibility
        _logger.debug("file header called")
        return self._fileheader

    def header(self, key):
        if self.qxas is not None:
            if key in self.qxas:
                return self.qxas[key]
            elif key == "" or key == " ":
                return self.scanheader
        if key == 'S':
            return self.scanheader[0]
        elif key == 'N':
            return self.scanheader[-2]
        elif key == 'L':
            return self.scanheader[-1]
        elif key == '@CALIB':
            output = []
            if self.scanheader is None:
                return output
            if self.scanheader[0][0:2] == '<<':
                #amptek
                try:
                    amptekCalibrationLines = []
                    amptekInCalibrationLines = False
                    for line in self.scanheader:
                        if '<<CALIBRATION>>' in line:
                            amptekInCalibrationLines = True
                            continue
                        if line.startswith('<<'):
                            amptekInCalibrationLines = False
                            continue
                        if amptekInCalibrationLines and\
                           ('LABEL' not in line):
                            amptekCalibrationLines.append(line)
                    n = len(amptekCalibrationLines)
                    if n == 0 :
                        return output
                    if n == 1:
                        #one point calibration
                        x0,y0 = 0.0, 0.0
                        values = amptekCalibrationLines[0].split()
                        x1,y1 = map(float,values)
                        gain = (y1-y0)/(x1-x0)
                        zero = y0 - gain * x0
                    elif n == 2:
                        #two point calibration
                        values = amptekCalibrationLines[0].split()
                        x0,y0 = map(float,values)
                        values = amptekCalibrationLines[1].split()
                        x1,y1 = map(float,values)
                        gain = (y1-y0)/(x1-x0)
                        zero = y0 - gain * x0
                    else:
                        x = numpy.zeros((n,), numpy.float64)
                        y = numpy.zeros((n,), numpy.float64)
                        for i in range(n):
                            values = amptekCalibrationLines[i].split()
                            x[i], y[i] = map(float,values)
                        Sxy = numpy.dot(x, y.T)
                        Sxx = numpy.dot(x, x.T)
                        Sx  = x.sum()
                        Sy  = y.sum()
                        d = n * Sxx - Sx * Sx
                        zero = (Sxx * Sy - Sx * Sxy)/d
                        gain = (n * Sxy - Sx * Sy)/d
                    output = ['#@CALIB  %g  %g  0' % (zero, gain)]
                except:
                    pass
            return output
        elif key == "" or key == " ":
            return self.scanheader
        else:
            return []

    def order(self):
        return self.__order

    def number(self):
        return self.__number

    def lines(self):
        if self.scantype == 'SCAN':
            return self.rows
        else:
            return 0

    def nbmca(self):
        if self.scantype == 'SCAN':
            return 0
        else:
            return self.__cols

    def mca(self,number):
        if number <= 0:
            raise ValueError("Specfile mca numberig starts at 1")
        return self.__data[:,number-1]

class BufferedFile(object):
    def __init__(self, filename):
        f = open(filename, 'rb')
        self.__buffer = f.read()
        f.close()
        if sys.version < '3.0':
            self.__buffer=self.__buffer.replace("\r", "\n")
            self.__buffer=self.__buffer.replace("\n\n", "\n")
            self.__buffer = self.__buffer.split("\n")
        else:
            tmp = bytes("\n", 'utf-8')
            self.__buffer=self.__buffer.replace(bytes("\r", 'utf-8'), tmp)
            self.__buffer=self.__buffer.replace(bytes("\n\n", 'utf-8'), tmp)
            self.__buffer = self.__buffer.split(tmp)
        self.__currentLine = 0

    if sys.version < '3.0':
        def readline(self):
            if self.__currentLine >= len(self.__buffer):
                return ""
            line = self.__buffer[self.__currentLine] + "\n"
            self.__currentLine += 1
            return line
    else:
        def readline(self):
            if self.__currentLine >= len(self.__buffer):
                return bytes("", 'utf-8')
            line = self.__buffer[self.__currentLine] + bytes("\n", 'utf-8')
            self.__currentLine += 1
            return line

    def close(self):
        self.__currentLine = 0
        return

if __name__ == "__main__":
    filename = sys.argv[1]
    print(filename)
    sf=Specfile(filename)
    sf.list()
    print(sf[0].alllabels())
    print(dir(sf[0]))