-
Notifications
You must be signed in to change notification settings - Fork 8
/
SpectrumFileBase.py
95 lines (78 loc) · 2.68 KB
/
SpectrumFileBase.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
from __future__ import print_function
import numpy
from scipy.interpolate import interp1d
import struct
import datetime
class SpectrumFileBase(object):
"""
Spectrum file parser base class.
Basically, all you need is:
SpectrumFileBase.read()
SpectrumFileBase.calibrate()
Then the data are in
SpectrumFileBase.data [counts]
SpectrumFileBase.channel
SpectrumFileBase.energy
SpectrumFileBase.energy_binwidth
Mark S. Bandstra
Jan. 2014
"""
def __init__(self, filename):
super(SpectrumFileBase, self).__init__()
self.filename = filename
# to read from file
self.spectrum_id = ''
self.sample_description = ''
self.detector_description = ''
self.location_description = ''
self.hardware_status = ''
self.collection_start = None
self.collection_stop = None
self.realtime = 0.
self.livetime = 0.
self.first_channel = 0
self.num_channels = 0
# arrays to be read
self.channel = numpy.array([], dtype=numpy.int32)
self.data = numpy.array([], dtype=numpy.int32)
self.cal_coeff = []
# arrays to be calculated
self.energy = numpy.array([], dtype=numpy.float)
self.energy_binwidth = numpy.array([], dtype=numpy.float)
def __str__(self, show_data=False):
s = ''
return s
def read(self, verbose=False):
"""Read in the file."""
self.cal_coeff = [0., 1.]
return True
def write(self, filename):
"""Write back to a file."""
return True
def calibrate(self):
"""Calculate energies corresponding to channels."""
self.energy = self.channel_to_energy(self.channel)
self.energy_binwidth = self.bin_width(self.channel)
return True
def channel_to_energy(self, channel):
"""Apply energy calibration to the given channel (or numpy array of
channels)."""
chan = numpy.float64(channel)
en = numpy.zeros_like(chan)
for j in range(len(self.cal_coeff)):
en += self.cal_coeff[j] * pow(chan, j)
return en
def energy_to_channel(self, energy):
"""Invert the energy calibration to find the channel equivalent."""
return interp1d(self.energy, self.channel)(energy)
def bin_width(self, channel):
"""Calculate the width in keV of the bin at the given channel."""
en0 = self.channel_to_energy(channel - 0.5)
en1 = self.channel_to_energy(channel + 0.5)
return en1 - en0
if __name__ == '__main__':
spec = SpectrumFileBase('')
spec.read()
spec.calibrate()
print(spec)
spec.write('test.txt')