-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathEDF.py
381 lines (329 loc) · 16.5 KB
/
EDF.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
from copy import deepcopy
from math import ceil, floor
from struct import pack, unpack
import calendar
import datetime
import numpy as np
import os
import re
import warnings
def padtrim(buf, num):
num -= len(buf)
if num>=0:
# pad the input to the specified length
return str(buf) + ' ' * num
else:
# trim the input to the specified length
return buf[0:num]
####################################################################################################
# the EDF header is represented as a tuple of (meas_info, chan_info)
# meas_info should have ['record_length', 'magic', 'hour', 'subject_id', 'recording_id', 'n_records', 'month', 'subtype', 'second', 'nchan', 'data_size', 'data_offset', 'lowpass', 'year', 'highpass', 'day', 'minute']
# chan_info should have ['physical_min', 'transducers', 'physical_max', 'digital_max', 'ch_names', 'n_samps', 'units', 'digital_min']
####################################################################################################
class EDFWriter():
def __init__(self, fname=None):
self.fname = None
self.meas_info = None
self.chan_info = None
self.calibrate = None
self.offset = None
self.n_records = 0
if fname:
self.open(fname)
def open(self, fname):
with open(fname, 'wb') as fid:
assert(fid.tell() == 0)
self.fname = fname
def close(self):
# it is still needed to update the number of records in the header
# this requires copying the whole file content
meas_info = self.meas_info
chan_info = self.chan_info
# update the n_records value in the file
tempname = self.fname + '.bak'
os.rename(self.fname, tempname)
with open(tempname, 'rb') as fid1:
assert(fid1.tell() == 0)
with open(self.fname, 'wb') as fid2:
assert(fid2.tell() == 0)
fid2.write(fid1.read(236))
fid1.read(8) # skip this part
fid2.write(padtrim(str(self.n_records), 8)) # but write this instead
fid2.write(fid1.read(meas_info['data_offset'] - 236 - 8))
blocksize = np.sum(chan_info['n_samps']) * meas_info['data_size']
for block in range(self.n_records):
fid2.write(fid1.read(blocksize))
os.remove(tempname)
self.fname = None
self.meas_info = None
self.chan_info = None
self.calibrate = None
self.offset = None
self.n_records = 0
return
def writeHeader(self, header):
meas_info = header[0]
chan_info = header[1]
meas_size = 256
chan_size = 256 * meas_info['nchan']
with open(self.fname, 'wb') as fid:
assert(fid.tell() == 0)
# fill in the missing or incomplete information
if not 'subject_id' in meas_info:
meas_info['subject_id'] = ''
if not 'recording_id' in meas_info:
meas_info['recording_id'] = ''
if not 'subtype' in meas_info:
meas_info['subtype'] = 'edf'
nchan = meas_info['nchan']
if not 'ch_names' in chan_info or len(chan_info['ch_names'])<nchan:
chan_info['ch_names'] = [str(i) for i in range(nchan)]
if not 'transducers' in chan_info or len(chan_info['transducers'])<nchan:
chan_info['transducers'] = ['' for i in range(nchan)]
if not 'units' in chan_info or len(chan_info['units'])<nchan:
chan_info['units'] = ['' for i in range(nchan)]
if meas_info['subtype'] in ('24BIT', 'bdf'):
meas_info['data_size'] = 3 # 24-bit (3 byte) integers
else:
meas_info['data_size'] = 2 # 16-bit (2 byte) integers
fid.write(padtrim('0', 8))
fid.write(padtrim(meas_info['subject_id'], 80))
fid.write(padtrim(meas_info['recording_id'], 80))
fid.write(padtrim('{:0>2d}.{:0>2d}.{:0>2d}'.format(meas_info['day'], meas_info['month'], meas_info['year']), 8))
fid.write(padtrim('{:0>2d}.{:0>2d}.{:0>2d}'.format(meas_info['hour'], meas_info['minute'], meas_info['second']), 8))
fid.write(padtrim(str(meas_size + chan_size), 8))
fid.write(' ' * 44)
fid.write(padtrim(str(-1), 8)) # the final n_records should be inserted on byte 236
fid.write(padtrim(str(meas_info['record_length']), 8))
fid.write(padtrim(str(meas_info['nchan']), 4))
# ensure that these are all np arrays rather than lists
for key in ['physical_min', 'transducers', 'physical_max', 'digital_max', 'ch_names', 'n_samps', 'units', 'digital_min']:
chan_info[key] = np.asarray(chan_info[key])
for i in range(meas_info['nchan']):
fid.write(padtrim( chan_info['ch_names'][i], 16))
for i in range(meas_info['nchan']):
fid.write(padtrim( chan_info['transducers'][i], 80))
for i in range(meas_info['nchan']):
fid.write(padtrim( chan_info['units'][i], 8))
for i in range(meas_info['nchan']):
fid.write(padtrim(str(chan_info['physical_min'][i]), 8))
for i in range(meas_info['nchan']):
fid.write(padtrim(str(chan_info['physical_max'][i]), 8))
for i in range(meas_info['nchan']):
fid.write(padtrim(str(chan_info['digital_min'][i]), 8))
for i in range(meas_info['nchan']):
fid.write(padtrim(str(chan_info['digital_max'][i]), 8))
for i in range(meas_info['nchan']):
fid.write(' ' * 80) # prefiltering
for i in range(meas_info['nchan']):
fid.write(padtrim(str(chan_info['n_samps'][i]), 8))
for i in range(meas_info['nchan']):
fid.write(' ' * 32) # reserved
meas_info['data_offset'] = fid.tell()
self.meas_info = meas_info
self.chan_info = chan_info
self.calibrate = (chan_info['physical_max'] - chan_info['physical_min'])/(chan_info['digital_max'] - chan_info['digital_min']);
self.offset = chan_info['physical_min'] - self.calibrate * chan_info['digital_min'];
channels = list(range(meas_info['nchan']))
for ch in channels:
if self.calibrate[ch]<0:
self.calibrate[ch] = 1;
self.offset[ch] = 0;
def writeBlock(self, data):
meas_info = self.meas_info
chan_info = self.chan_info
with open(self.fname, 'ab') as fid:
assert(fid.tell() > 0)
for i in range(meas_info['nchan']):
raw = deepcopy(data[i])
assert(len(raw)==chan_info['n_samps'][i])
if min(raw)<chan_info['physical_min'][i]:
warnings.warn('Value exceeds physical_min: ' + str(min(raw)) );
if max(raw)>chan_info['physical_max'][i]:
warnings.warn('Value exceeds physical_max: '+ str(max(raw)));
raw -= self.offset[i] # FIXME I am not sure about the order of calibrate and offset
raw /= self.calibrate[i]
raw = np.asarray(raw, dtype=np.int16)
buf = [pack('h', x) for x in raw]
for val in buf:
fid.write(val)
self.n_records += 1
####################################################################################################
class EDFReader():
def __init__(self, fname=None):
self.fname = None
self.meas_info = None
self.chan_info = None
self.calibrate = None
self.offset = None
if fname:
self.open(fname)
def open(self, fname):
with open(fname, 'rb') as fid:
assert(fid.tell() == 0)
self.fname = fname
self.readHeader()
return self.meas_info, self.chan_info
def close(self):
self.fname = None
self.meas_info = None
self.chan_info = None
self.calibrate = None
self.offset = None
def readHeader(self):
# the following is copied over from MNE-Python and subsequently modified
# to more closely reflect the native EDF standard
meas_info = {}
chan_info = {}
with open(self.fname, 'rb') as fid:
assert(fid.tell() == 0)
meas_info['magic'] = fid.read(8).strip().decode()
meas_info['subject_id'] = fid.read(80).strip().decode() # subject id
meas_info['recording_id'] = fid.read(80).strip().decode() # recording id
day, month, year = [int(x) for x in re.findall('(\d+)', fid.read(8).decode())]
hour, minute, second = [int(x) for x in re.findall('(\d+)', fid.read(8).decode())]
meas_info['day'] = day
meas_info['month'] = month
meas_info['year'] = year
meas_info['hour'] = hour
meas_info['minute'] = minute
meas_info['second'] = second
# date = datetime.datetime(year + 2000, month, day, hour, minute, sec)
# meas_info['meas_date'] = calendar.timegm(date.utctimetuple())
meas_info['data_offset'] = header_nbytes = int(fid.read(8).decode())
subtype = fid.read(44).strip().decode()[:5]
if len(subtype) > 0:
meas_info['subtype'] = subtype
else:
meas_info['subtype'] = os.path.splitext(self.fname)[1][1:].lower()
if meas_info['subtype'] in ('24BIT', 'bdf'):
meas_info['data_size'] = 3 # 24-bit (3 byte) integers
else:
meas_info['data_size'] = 2 # 16-bit (2 byte) integers
meas_info['n_records'] = n_records = int(fid.read(8).decode())
# record length in seconds
record_length = float(fid.read(8).decode())
if record_length == 0:
meas_info['record_length'] = record_length = 1.
warnings.warn('Headermeas_information is incorrect for record length. '
'Default record length set to 1.')
else:
meas_info['record_length'] = record_length
meas_info['nchan'] = nchan = int(fid.read(4).decode())
channels = list(range(nchan))
chan_info['ch_names'] = [fid.read(16).strip().decode() for ch in channels]
chan_info['transducers'] = [fid.read(80).strip().decode() for ch in channels]
chan_info['units'] = [fid.read(8).strip().decode() for ch in channels]
chan_info['physical_min'] = physical_min = np.array([float(fid.read(8).decode()) for ch in channels])
chan_info['physical_max'] = physical_max = np.array([float(fid.read(8).decode()) for ch in channels])
chan_info['digital_min'] = digital_min = np.array([float(fid.read(8).decode()) for ch in channels])
chan_info['digital_max'] = digital_max = np.array([float(fid.read(8).decode()) for ch in channels])
prefiltering = [fid.read(80).strip().decode() for ch in channels][:-1]
highpass = np.ravel([re.findall('HP:\s+(\w+)', filt) for filt in prefiltering])
lowpass = np.ravel([re.findall('LP:\s+(\w+)', filt) for filt in prefiltering])
high_pass_default = 0.
if highpass.size == 0:
meas_info['highpass'] = high_pass_default
elif all(highpass):
if highpass[0] == 'NaN':
meas_info['highpass'] = high_pass_default
elif highpass[0] == 'DC':
meas_info['highpass'] = 0.
else:
meas_info['highpass'] = float(highpass[0])
else:
meas_info['highpass'] = float(np.max(highpass))
warnings.warn('Channels contain different highpass filters. '
'Highest filter setting will be stored.')
if lowpass.size == 0:
meas_info['lowpass'] = None
elif all(lowpass):
if lowpass[0] == 'NaN':
meas_info['lowpass'] = None
else:
meas_info['lowpass'] = float(lowpass[0])
else:
meas_info['lowpass'] = float(np.min(lowpass))
warnings.warn('%s' % ('Channels contain different lowpass filters.'
' Lowest filter setting will be stored.'))
# number of samples per record
chan_info['n_samps'] = n_samps = np.array([int(fid.read(8).decode()) for ch in channels])
fid.read(32 *meas_info['nchan']).decode() # reserved
assert fid.tell() == header_nbytes
if meas_info['n_records']==-1:
# this happens if the n_records is not updated at the end of recording
tot_samps = (os.path.getsize(self.fname)-meas_info['data_offset'])/meas_info['data_size']
meas_info['n_records'] = tot_samps/sum(n_samps)
self.calibrate = (chan_info['physical_max'] - chan_info['physical_min'])/(chan_info['digital_max'] - chan_info['digital_min']);
self.offset = chan_info['physical_min'] - self.calibrate * chan_info['digital_min'];
for ch in channels:
if self.calibrate[ch]<0:
self.calibrate[ch] = 1;
self.offset[ch] = 0;
self.meas_info = meas_info
self.chan_info = chan_info
return (meas_info, chan_info)
def readBlock(self, block):
assert(block>=0)
meas_info = self.meas_info
chan_info = self.chan_info
data = []
with open(self.fname, 'rb') as fid:
assert(fid.tell() == 0)
blocksize = np.sum(chan_info['n_samps']) * meas_info['data_size']
fid.seek(meas_info['data_offset'] + block * blocksize)
for i in range(meas_info['nchan']):
buf = fid.read(chan_info['n_samps'][i]*meas_info['data_size'])
raw = np.asarray(unpack('<{}h'.format(chan_info['n_samps'][i]), buf), dtype=np.float32)
raw *= self.calibrate[i]
raw += self.offset[i] # FIXME I am not sure about the order of calibrate and offset
data.append(raw)
return data
def readSamples(self, channel, begsample, endsample):
meas_info = self.meas_info
chan_info = self.chan_info
n_samps = chan_info['n_samps'][channel]
begblock = int(floor((begsample) / n_samps))
endblock = int(floor((endsample) / n_samps))
data = self.readBlock(begblock)[channel]
for block in range(begblock+1, endblock+1):
data = np.append(data, self.readBlock(block)[channel])
begsample -= begblock*n_samps
endsample -= begblock*n_samps
return data[begsample:(endsample+1)]
####################################################################################################
# the following are a number of helper functions to make the behaviour of this EDFReader
# class more similar to https://bitbucket.org/cleemesser/python-edf/
####################################################################################################
def getSignalTextLabels(self):
# convert from unicode to string
return [str(x) for x in self.chan_info['ch_names']]
def getNSignals(self):
return self.meas_info['nchan']
def getSignalFreqs(self):
return self.chan_info['n_samps'] / self.meas_info['record_length']
def getNSamples(self):
return self.chan_info['n_samps'] * self.meas_info['n_records']
def readSignal(self, chanindx):
begsample = 0;
endsample = self.chan_info['n_samps'][chanindx] * self.meas_info['n_records'] - 1;
return self.readSamples(chanindx, begsample, endsample)
####################################################################################################
if False:
file_in = EDFReader()
file_in.open('/Users/roboos/day 01[10.03].edf')
print file_in.readSamples(0, 0, 0)
print file_in.readSamples(0, 0, 128)
if False:
file_in = EDFReader()
file_in.open('/Users/roboos/test_generator.edf')
file_out = EDFWriter()
file_out.open('/Users/roboos/test_generator copy.edf')
header = file_in.readHeader()
file_out.writeHeader(header)
meas_info = header[0]
for i in range(meas_info['n_records']):
data = file_in.readBlock(i)
file_out.writeBlock(data)
file_in.close()
file_out.close()