-
Notifications
You must be signed in to change notification settings - Fork 319
Expand file tree
/
Copy pathedf.py
More file actions
1223 lines (1098 loc) · 45 KB
/
edf.py
File metadata and controls
1223 lines (1098 loc) · 45 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
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
import datetime
import functools
import math
import os
import posixpath
import struct
import numpy as np
import pandas as pd
from wfdb.io.annotation import Annotation, format_ann_from_df, wrann
from wfdb.io.record import Record, rdrecord, SIG_UNITS
from wfdb.io import _url
from wfdb.io import download
def read_edf(
record_name,
pn_dir=None,
header_only=False,
verbose=False,
rdedfann_flag=False,
encoding="iso8859-1",
):
"""
Read a EDF format file into a WFDB Record.
Many EDF files contain signals at widely varying sampling frequencies.
`read_edf` handles these properly, but the default behavior of most WFDB
applications is to read such data in low-resolution mode (in which all
signals are resampled at the lowest sampling frequency used for any signal
in the record). This is almost certainly not what you want if, for
example, the record contains EEG signals sampled at 200 Hz and body
temperature sampled at 1 Hz; by default, applications such as `rdsamp`
will resample the EEGs (and any other signals in the record) at 1 Hz. To
avoid this behavior, you can set `smooth_frames` to False (high resolution)
provided by `rdrecord` and a few other WFDB applications.
Note that applications built using version 3.1.0 and later versions of
the WFDB-Python library can read EDF files directly, so that the conversion
performed by `read_edf` is no longer necessary. However, one can still use
this function to produce WFDB-compatible files from EDF files if desired.
Parameters
----------
record_name : str
The name of the input EDF record to be read.
pn_dir : str, optional
Option used to stream data from Physionet. The Physionet
database directory from which to find the required record files.
eg. For record '100' in 'http://physionet.org/content/mitdb'
pn_dir='mitdb'.
header_only : bool, optional
Whether to only return the header information (True) or not (False).
If true, this function will only return `['fs', 'sig_len', 'n_sig',
'base_date', 'base_time', 'units', 'sig_name', 'comments']`.
verbose : bool, optional
Whether to print all the information read about the file (True) or
not (False).
rdedfann_flag : bool, optional
Whether the function is being called by `rdedfann` or the user. If it
is being called by the user and the file has annotations, then warn
them that the EDF file has annotations and that they should use
`rdedfann` instead.
encoding : str, optional
The encoding to use for strings in the header. Although the edf
specification requires ascii strings, some files do not adhere to it.
Returns
-------
record : dict, optional
All of the record information needed to generate MIT formatted files.
Only returns if 'record_only' is set to True, else generates the
corresponding .dat and .hea files. This record file will not match the
`rdrecord` output since it will only give us the digital signal for now.
Notes
-----
The entire file is composed of (seen here: https://www.edfplus.info/specs/edf.html):
HEADER RECORD (we suggest to also adopt the 12 simple additional EDF+ specs)
8 ascii : version of this data format (0)
80 ascii : local patient identification (mind item 3 of the additional EDF+ specs)
80 ascii : local recording identification (mind item 4 of the additional EDF+ specs)
8 ascii : startdate of recording (dd.mm.yy) (mind item 2 of the additional EDF+ specs)
8 ascii : starttime of recording (hh.mm.ss)
8 ascii : number of bytes in header record
44 ascii : reserved
8 ascii : number of data records (-1 if unknown, obey item 10 of the additional EDF+ specs)
8 ascii : duration of a data record, in seconds
4 ascii : number of signals (ns) in data record
ns * 16 ascii : ns * label (e.g. EEG Fpz-Cz or Body temp) (mind item 9 of the additional EDF+ specs)
ns * 80 ascii : ns * transducer type (e.g. AgAgCl electrode)
ns * 8 ascii : ns * physical dimension (e.g. uV or degreeC)
ns * 8 ascii : ns * physical minimum (e.g. -500 or 34)
ns * 8 ascii : ns * physical maximum (e.g. 500 or 40)
ns * 8 ascii : ns * digital minimum (e.g. -2048)
ns * 8 ascii : ns * digital maximum (e.g. 2047)
ns * 80 ascii : ns * prefiltering (e.g. HP:0.1Hz LP:75Hz)
ns * 8 ascii : ns * nr of samples in each data record
ns * 32 ascii : ns * reserved
DATA RECORD
nr of samples[1] * integer : first signal in the data record
nr of samples[2] * integer : second signal
..
..
nr of samples[ns] * integer : last signal
Bytes 0 - 127: descriptive text
Bytes 128 - 131: master tag (data type = matrix)
Bytes 132 - 135: master tag (data size)
Bytes 136 - 151: array flags (4 byte tag with data type, 4 byte
tag with subelement size, 8 bytes of content)
Bytes 152 - 167: array dimension (4 byte tag with data type, 4
byte tag with subelement size, 8 bytes of content)
Bytes 168 - 183: array name (4 byte tag with data type, 4 byte
tag with subelement size, 8 bytes of content)
Bytes 184 - ...: array content (4 byte tag with data type, 4 byte
tag with subelement size, ... bytes of content)
Examples
--------
>>> record = read_edf('x001_FAROS.edf',
pn_dir='simultaneous-measurements/raw_data')
"""
if pn_dir is not None:
if "." not in pn_dir:
dir_list = pn_dir.split("/")
pn_dir = posixpath.join(
dir_list[0], download.get_version(dir_list[0]), *dir_list[1:]
)
file_url = posixpath.join(download.PN_INDEX_URL, pn_dir, record_name)
# Currently must download file for MNE to read it though can give the
# user the option to delete it immediately afterwards
with _url.openurl(file_url, "rb") as f:
open(record_name, "wb").write(f.read())
# Open the desired file
edf_file = open(record_name, mode="rb")
# Version of this data format (8 bytes)
version = struct.unpack("<8s", edf_file.read(8))[0].decode(encoding)
# Check to see that the input is an EDF file. (This check will detect
# most but not all other types of files.)
if version != "0 ":
raise Exception(
"Input does not appear to be EDF -- no conversion attempted"
)
else:
if verbose:
print("EDF version number: {}".format(version.strip()))
# Local patient identification (80 bytes)
patient_id = struct.unpack("<80s", edf_file.read(80))[0].decode(encoding)
if verbose:
print("Patient ID: {}".format(patient_id))
# Local recording identification (80 bytes)
# Bob Kemp recommends using this field to encode the start date
# including an abbreviated month name in English and a full (4-digit)
# year, as is done here if this information is available in the input
# record. EDF+ requires this.
record_id = struct.unpack("<80s", edf_file.read(80))[0].decode(encoding)
if verbose:
print("Recording ID: {}".format(record_id))
# Start date of recording (dd.mm.yy) (8 bytes)
start_date = struct.unpack("<8s", edf_file.read(8))[0].decode(encoding)
if verbose:
print("Recording Date: {}".format(start_date))
start_day, start_month, start_year = [int(i) for i in start_date.split(".")]
# This should work for a while
if start_year < 1970:
start_year += 1900
if start_year < 1970:
start_year += 100
# Start time of recording (hh.mm.ss) (8 bytes)
start_time = struct.unpack("<8s", edf_file.read(8))[0].decode(encoding)
if verbose:
print("Recording Time: {}".format(start_time))
start_hour, start_minute, start_second = [
int(i) for i in start_time.split(".")
]
# Number of bytes in header (8 bytes)
header_bytes = int(
struct.unpack("<8s", edf_file.read(8))[0].decode(encoding)
)
if verbose:
print("Number of bytes in header record: {}".format(header_bytes))
# Reserved (44 bytes)
reserved_notes = (
struct.unpack("<44s", edf_file.read(44))[0].decode(encoding).strip()
)
if reserved_notes[:5] == "EDF+C":
# The file is EDF compatible and will work without issue
# See: Bob Kemp, Jesus Olivan, European data format ‘plus’ (EDF+), an
# EDF alike standard format for the exchange of physiological
# data, Clinical Neurophysiology, Volume 114, Issue 9, 2003,
# Pages 1755-1761, ISSN 1388-2457
pass
elif reserved_notes[:5] == "EDF+D":
raise Exception(
"EDF+ File: interrupted data records (not currently supported)"
)
else:
if verbose:
print("Free Space: {}".format(reserved_notes))
# Number of blocks (-1 if unknown) (8 bytes)
num_blocks = int(struct.unpack("<8s", edf_file.read(8))[0].decode(encoding))
if verbose:
print("Number of data records: {}".format(num_blocks))
if num_blocks == -1:
raise Exception(
"Number of data records in unknown (not currently supported)"
)
# Duration of a block, in seconds (8 bytes)
block_duration = float(
struct.unpack("<8s", edf_file.read(8))[0].decode(encoding)
)
if verbose:
print(
"Duration of each data record in seconds: {}".format(block_duration)
)
if block_duration <= 0.0:
block_duration = 1.0
# Number of signals (4 bytes)
n_sig = int(struct.unpack("<4s", edf_file.read(4))[0].decode(encoding))
if verbose:
print("Number of signals: {}".format(n_sig))
if n_sig < 1:
raise Exception("Done: not any signals left to read")
# Label (e.g., EEG FpzCz or Body temp) (16 bytes each)
sig_name = []
for _ in range(n_sig):
temp_sig = (
struct.unpack("<16s", edf_file.read(16))[0].decode(encoding).strip()
)
if temp_sig == "EDF Annotations" and not rdedfann_flag:
print(
"*** This may be an EDF+ Annotation file instead, please see "
"the `rdedfann` function. ***"
)
sig_name.append(temp_sig)
if verbose:
print("Signal Labels: {}".format(sig_name))
# Transducer type (e.g., AgAgCl electrode) (80 bytes each)
transducer_types = []
for _ in range(n_sig):
transducer_types.append(
struct.unpack("<80s", edf_file.read(80))[0].decode(encoding).strip()
)
if verbose:
print("Transducer Types: {}".format(transducer_types))
# Physical dimension (e.g., uV or degreeC) (8 bytes each)
physical_dims = []
for _ in range(n_sig):
physical_dims.append(
struct.unpack("<8s", edf_file.read(8))[0].decode(encoding).strip()
)
if verbose:
print("Physical Dimensions: {}".format(physical_dims))
# Physical minimum (e.g., -500 or 34) (8 bytes each)
physical_min = np.array([])
for _ in range(n_sig):
physical_min = np.append(
physical_min,
float(struct.unpack("<8s", edf_file.read(8))[0].decode(encoding)),
)
if verbose:
print("Physical Minimums: {}".format(physical_min))
# Physical maximum (e.g., 500 or 40) (8 bytes each)
physical_max = np.array([])
for _ in range(n_sig):
physical_max = np.append(
physical_max,
float(struct.unpack("<8s", edf_file.read(8))[0].decode(encoding)),
)
if verbose:
print("Physical Maximums: {}".format(physical_max))
# Digital minimum (e.g., -2048) (8 bytes each)
digital_min = np.array([])
for _ in range(n_sig):
digital_min = np.append(
digital_min,
float(struct.unpack("<8s", edf_file.read(8))[0].decode(encoding)),
)
if verbose:
print("Digital Minimums: {}".format(digital_min))
# Digital maximum (e.g., 2047) (8 bytes each)
digital_max = np.array([])
for _ in range(n_sig):
digital_max = np.append(
digital_max,
float(struct.unpack("<8s", edf_file.read(8))[0].decode(encoding)),
)
if verbose:
print("Digital Maximums: {}".format(digital_max))
# Prefiltering (e.g., HP:0.1Hz LP:75Hz) (80 bytes each)
prefilter_info = []
for _ in range(n_sig):
prefilter_info.append(
struct.unpack("<80s", edf_file.read(80))[0].decode(encoding).strip()
)
if verbose:
print("Prefiltering Information: {}".format(prefilter_info))
# Number of samples per block (8 bytes each)
samps_per_block = []
for _ in range(n_sig):
samps_per_block.append(
int(struct.unpack("<8s", edf_file.read(8))[0].decode(encoding))
)
if verbose:
print("Number of Samples per Record: {}".format(samps_per_block))
# The last 32*nsig bytes in the header are unused
for _ in range(n_sig):
struct.unpack("<32s", edf_file.read(32))[0].decode(encoding)
# Pre-process the acquired data before creating the record
record_name_out = (
record_name.split(os.sep)[-1].replace("-", "_").replace(".edf", "")
)
sample_rate = [int(i / block_duration) for i in samps_per_block]
fs = functools.reduce(math.gcd, sample_rate)
samps_per_frame = [int(s / min(samps_per_block)) for s in samps_per_block]
sig_len = int(fs * num_blocks * block_duration)
base_time = datetime.time(start_hour, start_minute, start_second)
base_date = datetime.date(start_year, start_month, start_day)
file_name = n_sig * [record_name_out + ".dat"]
fmt = n_sig * ["16"]
skew = n_sig * [None]
byte_offset = n_sig * [None]
adc_gain_all = (digital_max - digital_min) / (physical_max - physical_min)
adc_gain = [float(format(a, ".12g")) for a in adc_gain_all]
baseline = (digital_max - (physical_max * adc_gain_all) + 1).astype("int64")
units = n_sig * [""]
for i, f in enumerate(physical_dims):
if f == "n/a":
label = sig_name[i].lower().split()[0]
if label in list(SIG_UNITS.keys()):
units[i] = SIG_UNITS[label]
else:
units[i] = "n/a"
else:
f = f.replace("µ", "u") # Maybe more weird symbols to check for?
if f == "":
units[i] = "mV"
else:
units[i] = f
adc_res = [int(math.log2(f)) for f in (digital_max - digital_min)]
adc_zero = [int(f) for f in ((digital_max + 1 + digital_min) / 2)]
block_size = n_sig * [0]
base_datetime = datetime.datetime(
start_year,
start_month,
start_day,
start_hour,
start_minute,
start_second,
)
base_time = datetime.time(
base_datetime.hour, base_datetime.minute, base_datetime.second
)
base_date = datetime.date(
base_datetime.year, base_datetime.month, base_datetime.day
)
if header_only:
return {
"fs": fs,
"sig_len": sig_len,
"n_sig": n_sig,
"base_date": base_date,
"base_time": base_time,
"units": units,
"sig_name": sig_name,
"comments": [],
}
sig_data = np.empty((sig_len, n_sig))
temp_sig_data = np.fromfile(edf_file, dtype=np.int16)
temp_sig_data = temp_sig_data.reshape((-1, sum(samps_per_block)))
temp_all_sigs = np.hsplit(temp_sig_data, np.cumsum(samps_per_block)[:-1])
for i in range(n_sig):
# Check if `samps_per_frame` has all equal values
if samps_per_frame.count(samps_per_frame[0]) == len(samps_per_frame):
sig_data[:, i] = (
(temp_all_sigs[i].flatten() - baseline[i]).astype(np.int64)
) / adc_gain_all[i]
else:
temp_sig_data = temp_all_sigs[i].flatten()
if samps_per_frame[i] == 1:
sig_data[:, i] = (temp_sig_data - baseline[i]).astype(
np.int64
) / adc_gain_all[i]
else:
for j in range(sig_len):
start_ind = j * samps_per_frame[i]
stop_ind = start_ind + samps_per_frame[i]
sig_data[j, i] = np.mean(
(
temp_sig_data[start_ind:stop_ind] - baseline[i]
).astype(np.int64)
/ adc_gain_all[i]
)
# This is the closest I can get to the original implementation
# NOTE: This is done using `np.testing.assert_array_equal()`
# Mismatched elements: 15085545 / 15400000 (98%)
# Max absolute difference: 3.75166564e-12
# Max relative difference: 5.41846079e-15
# x: array([[ -3.580728, 42.835293, -102.818048, 54.978632, -52.354247],
# [ -8.340205, 43.079939, -102.106351, 56.402027, -44.992626],
# [ -5.004123, 43.546991, -99.481966, 51.64255 , -43.079939],...
# y: array([[ -3.580728, 42.835293, -102.818048, 54.978632, -52.354247],
# [ -8.340205, 43.079939, -102.106351, 56.402027, -44.992626],
# [ -5.004123, 43.546991, -99.481966, 51.64255 , -43.079939],...
init_value = [int(s[0, 0]) for s in temp_all_sigs]
checksum = [
int(np.sum(v) % 65536) for v in np.transpose(sig_data)
] # not all values correct?
edf_file.close()
record = Record(
record_name=record_name_out,
n_sig=n_sig,
fs=fs,
samps_per_frame=samps_per_frame,
counter_freq=None,
base_counter=None,
sig_len=sig_len,
base_time=base_time,
base_date=base_date,
comments=[],
sig_name=sig_name, # Remove whitespace to make compatible later?
p_signal=sig_data,
d_signal=None,
e_p_signal=None,
e_d_signal=None,
file_name=n_sig * [record_name_out + ".dat"],
fmt=n_sig * ["16"],
skew=n_sig * [None],
byte_offset=n_sig * [None],
adc_gain=adc_gain,
baseline=baseline,
units=units,
adc_res=[int(math.log2(f)) for f in (digital_max - digital_min)],
adc_zero=[int(f) for f in ((digital_max + 1 + digital_min) / 2)],
init_value=init_value,
checksum=checksum,
block_size=n_sig * [0],
)
record.base_datetime = base_datetime
return record
def wfdb_to_edf(
record_name,
pn_dir=None,
sampfrom=0,
sampto=None,
channels=None,
output_filename="",
edf_plus=False,
):
"""
These programs convert EDF (European Data Format) files into
WFDB-compatible files (as used in PhysioNet) and vice versa. European
Data Format (EDF) was originally designed for storage of polysomnograms.
Note that WFDB format does not include a standard way to specify the
transducer type or the prefiltering specification; these parameters are
not preserved by these conversion programs. Also note that use of the
standard signal and unit names specified for EDF is permitted but not
enforced by `wfdb_to_edf`.
Parameters
----------
record_name : str
The name of the input WFDB record to be read. Can also work with both
EDF and WAV files.
pn_dir : str, optional
Option used to stream data from Physionet. The Physionet
database directory from which to find the required record files.
eg. For record '100' in 'http://physionet.org/content/mitdb'
pn_dir='mitdb'.
sampfrom : int, optional
The starting sample number to read for all channels.
sampto : int, 'end', optional
The sample number at which to stop reading for all channels.
Reads the entire duration by default.
channels : list, optional
List of integer indices specifying the channels to be read.
Reads all channels by default.
output_filename : str, optional
The desired name of the output file. If this value set to the
default value of '', then the output filename will be 'REC.edf'.
edf_plus : bool, optional
Whether to write the output file in EDF (False) or EDF+ (True) format.
Returns
-------
N/A
Notes
-----
The entire file is composed of (seen here: https://www.edfplus.info/specs/edf.html):
HEADER RECORD (we suggest to also adopt the 12 simple additional EDF+ specs)
8 ascii : version of this data format (0)
80 ascii : local patient identification (mind item 3 of the additional EDF+ specs)
80 ascii : local recording identification (mind item 4 of the additional EDF+ specs)
8 ascii : startdate of recording (dd.mm.yy) (mind item 2 of the additional EDF+ specs)
8 ascii : starttime of recording (hh.mm.ss)
8 ascii : number of bytes in header record
44 ascii : reserved
8 ascii : number of data records (-1 if unknown, obey item 10 of the additional EDF+ specs)
8 ascii : duration of a data record, in seconds
4 ascii : number of signals (ns) in data record
ns * 16 ascii : ns * label (e.g. EEG Fpz-Cz or Body temp) (mind item 9 of the additional EDF+ specs)
ns * 80 ascii : ns * transducer type (e.g. AgAgCl electrode)
ns * 8 ascii : ns * physical dimension (e.g. uV or degreeC)
ns * 8 ascii : ns * physical minimum (e.g. -500 or 34)
ns * 8 ascii : ns * physical maximum (e.g. 500 or 40)
ns * 8 ascii : ns * digital minimum (e.g. -2048)
ns * 8 ascii : ns * digital maximum (e.g. 2047)
ns * 80 ascii : ns * prefiltering (e.g. HP:0.1Hz LP:75Hz)
ns * 8 ascii : ns * nr of samples in each data record
ns * 32 ascii : ns * reserved
DATA RECORD
nr of samples[1] * integer : first signal in the data record
nr of samples[2] * integer : second signal
..
..
nr of samples[ns] * integer : last signal
Bytes 0 - 127: descriptive text
Bytes 128 - 131: master tag (data type = matrix)
Bytes 132 - 135: master tag (data size)
Bytes 136 - 151: array flags (4 byte tag with data type, 4 byte
tag with subelement size, 8 bytes of content)
Bytes 152 - 167: array dimension (4 byte tag with data type, 4
byte tag with subelement size, 8 bytes of content)
Bytes 168 - 183: array name (4 byte tag with data type, 4 byte
tag with subelement size, 8 bytes of content)
Bytes 184 - ...: array content (4 byte tag with data type, 4 byte
tag with subelement size, ... bytes of content)
Examples
--------
>>> wfdb.wfdb_to_edf('100', pn_dir='pwave')
The output file name is '100.edf'
"""
record = rdrecord(
record_name,
pn_dir=pn_dir,
sampfrom=sampfrom,
sampto=sampto,
smooth_frames=False,
)
record_name_out = record_name.split(os.sep)[-1].replace("-", "_")
# Maximum data block length, in bytes
edf_max_block = 61440
# Convert to the expected month name formatting
month_names = [
"JAN",
"FEB",
"MAR",
"APR",
"MAY",
"JUN",
"JUL",
"AUG",
"SEP",
"OCT",
"NOV",
"DEC",
]
# Calculate block duration. (In the EDF spec, blocks are called "records"
# or "data records", but this would be confusing here since "record"
# refers to the entire recording -- so here we say "blocks".)
samples_per_frame = sum(record.samps_per_frame)
# i.e., The number of frames per minute, divided by 60
frames_per_minute = record.fs * 60 + 0.5
frames_per_second = frames_per_minute / 60
# Ten seconds
frames_per_block = 10 * frames_per_second + 0.5
# EDF specifies 2 bytes per sample
bytes_per_block = int(2 * samples_per_frame * frames_per_block)
# Blocks would be too long -- reduce their length by a factor of 10
while bytes_per_block > edf_max_block:
frames_per_block /= 10
bytes_per_block = samples_per_frame * 2 * frames_per_block
seconds_per_block = int(frames_per_block / frames_per_second)
if (frames_per_block < 1) and (bytes_per_block < edf_max_block / 60):
# The number of frames/minute
frames_per_block = frames_per_minute
bytes_per_block = 2 * samples_per_frame * frames_per_block
seconds_per_block = 60
if bytes_per_block > edf_max_block:
print(
(
"Can't convert record %s to EDF: EDF blocks can't be larger "
"than {} bytes, but each input frame requires {} bytes. Use "
"'channels' to select a subset of the input signals or trim "
"using 'sampfrom' and 'sampto'."
).format(edf_max_block, samples_per_frame * 2)
)
# Calculate the number of blocks to be written. The calculation rounds
# up so that we don't lose any frames, even if the number of frames is not
# an exact multiple of frames_per_block
total_frames = record.sig_len
num_blocks = int(total_frames / int(frames_per_block)) + 1
digital_min = []
digital_max = []
physical_min = []
physical_max = []
# Calculate the physical and digital extrema
for i in range(record.n_sig):
# Invalid ADC resolution in input .hea file
if record.adc_res[i] < 1:
# Guess the ADC resolution based on format
if record.fmt[i] == "24":
temp_adc_res = 24
elif record.fmt[i] == "32":
temp_adc_res = 32
elif record.fmt[i] == "80":
temp_adc_res = 8
elif record.fmt[i] == "212":
temp_adc_res = 12
elif (record.fmt[i] == "310") or (record.fmt[i] == "311"):
temp_adc_res = 10
else:
temp_adc_res = 16
else:
temp_adc_res = record.adc_res[i]
# Determine the physical and digital extrema
digital_max.append(
int(record.adc_zero[i] + (1 << (temp_adc_res - 1)) - 1)
)
digital_min.append(int(record.adc_zero[i] - (1 << (temp_adc_res - 1))))
physical_max.append(
(digital_max[i] - record.baseline[i]) / record.adc_gain[i]
)
physical_min.append(
(digital_min[i] - record.baseline[i]) / record.adc_gain[i]
)
# The maximum record name length to write is 80 bytes
if len(record_name_out) > 80:
record_name_write = record_name_out[:79] + "\0"
else:
record_name_write = record_name_out
# The maximum seconds per block length to write is 8 bytes
if len(str(seconds_per_block)) > 8:
seconds_per_block_write = seconds_per_block[:7] + "\0"
else:
seconds_per_block_write = seconds_per_block
# The maximum signal name length to write is 16 bytes
sig_name_write = len(record.sig_name) * []
for s in record.sig_name:
if len(s) > 16:
sig_name_write.append(s[:15] + "\0")
else:
sig_name_write.append(s)
# The maximum units length to write is 8 bytes
units_write = len(record.units) * []
for s in record.units:
if len(s) > 8:
units_write.append(s[:7] + "\0")
else:
units_write.append(s)
# Configure the output datetime
if hasattr("record", "base_datetime"):
start_second = int(record.base_datetime.second)
start_minute = int(record.base_datetime.minute)
start_hour = int(record.base_datetime.hour)
start_day = int(record.base_datetime.day)
start_month = int(record.base_datetime.month)
start_year = int(record.base_datetime.year)
else:
# Set date to start of EDF epoch
start_second = 0
start_minute = 0
start_hour = 0
start_day = 1
start_month = 1
start_year = 1985
# Determine the number of bytes in the header
header_bytes = 256 * (record.n_sig + 1)
# Determine the number of samples per data record
samps_per_record = []
for spf in record.samps_per_frame:
samps_per_record.append(int(frames_per_block) * spf)
# Determine the output data
# NOTE: The output data will be close (+-1) but not equal due to the
# inappropriate rounding done by record.adc()
# For example...
# Mismatched elements: 862881 / 24168000 (3.57%)
# Max absolute difference: 1
# Max relative difference: 0.0212766
# x: array([ 53, -28, 14, ..., 884, 898, 898], dtype=int16)
# y: array([ 53, -28, 14, ..., 884, 898, 898], dtype=int16)
if record.e_p_signal is not None:
temp_data = record.adc(expanded=True)
else:
temp_data = record.adc()
temp_data = [v for v in np.transpose(temp_data)]
out_data = []
for i in range(record.sig_len):
for j, sig in enumerate(temp_data):
ind_start = i * samps_per_record[j]
ind_stop = (i + 1) * samps_per_record[j]
out_data.extend(sig[ind_start:ind_stop].tolist())
out_data = np.array(out_data, dtype=np.int16)
# Start writing the file
if output_filename == "":
output_filename = record_name_out + ".edf"
with open(output_filename, "wb") as f:
print(
"Converting record {} to {} ({} mode)".format(
record_name, output_filename, "EDF+" if edf_plus else "EDF"
)
)
# Version of this data format (8 bytes)
f.write(struct.pack("<8s", b"0").replace(b"\x00", b"\x20"))
# Local patient identification (80 bytes)
f.write(
struct.pack(
"<80s", "{}".format(record_name_write).encode("ascii")
).replace(b"\x00", b"\x20")
)
# Local recording identification (80 bytes)
# Bob Kemp recommends using this field to encode the start date
# including an abbreviated month name in English and a full (4-digit)
# year, as is done here if this information is available in the input
# record. EDF+ requires this.
if hasattr("record", "base_datetime"):
f.write(
struct.pack(
"<80s",
"Startdate {}-{}-{}".format(
start_day, month_names[start_month - 1], start_year
).encode("ascii"),
).replace(b"\x00", b"\x20")
)
else:
f.write(
struct.pack("<80s", b"Startdate not recorded").replace(
b"\x00", b"\x20"
)
)
if edf_plus:
print("WARNING: EDF+ requires start date (not specified)")
# Start date of recording (dd.mm.yy) (8 bytes)
f.write(
struct.pack(
"<8s",
"{:02d}.{:02d}.{:02d}".format(
start_day, start_month, start_year % 100
).encode("ascii"),
).replace(b"\x00", b"\x20")
)
# Start time of recording (hh.mm.ss) (8 bytes)
f.write(
struct.pack(
"<8s",
"{:02d}.{:02d}.{:02d}".format(
start_hour, start_minute, start_second
).encode("ascii"),
).replace(b"\x00", b"\x20")
)
# Number of bytes in header (8 bytes)
f.write(
struct.pack(
"<8s", "{:d}".format(header_bytes).encode("ascii")
).replace(b"\x00", b"\x20")
)
# Reserved (44 bytes)
if edf_plus:
f.write(struct.pack("<44s", b"EDF+C").replace(b"\x00", b"\x20"))
else:
f.write(struct.pack("<44s", b"").replace(b"\x00", b"\x20"))
# Number of blocks (-1 if unknown) (8 bytes)
f.write(
struct.pack(
"<8s", "{:d}".format(num_blocks).encode("ascii")
).replace(b"\x00", b"\x20")
)
# Duration of a block, in seconds (8 bytes)
f.write(
struct.pack(
"<8s", "{:g}".format(seconds_per_block_write).encode("ascii")
).replace(b"\x00", b"\x20")
)
# Number of signals (4 bytes)
f.write(
struct.pack(
"<4s", "{:d}".format(record.n_sig).encode("ascii")
).replace(b"\x00", b"\x20")
)
# Label (e.g., EEG FpzCz or Body temp) (16 bytes each)
for i in sig_name_write:
f.write(
struct.pack("<16s", "{}".format(i).encode("ascii")).replace(
b"\x00", b"\x20"
)
)
# Transducer type (e.g., AgAgCl electrode) (80 bytes each)
for _ in range(record.n_sig):
f.write(
struct.pack("<80s", b"transducer type not recorded").replace(
b"\x00", b"\x20"
)
)
# Physical dimension (e.g., uV or degreeC) (8 bytes each)
for i in units_write:
f.write(
struct.pack("<8s", "{}".format(i).encode("ascii")).replace(
b"\x00", b"\x20"
)
)
# Physical minimum (e.g., -500 or 34) (8 bytes each)
for pmin in physical_min:
f.write(
struct.pack("<8s", "{:g}".format(pmin).encode("ascii")).replace(
b"\x00", b"\x20"
)
)
# Physical maximum (e.g., 500 or 40) (8 bytes each)
for pmax in physical_max:
f.write(
struct.pack("<8s", "{:g}".format(pmax).encode("ascii")).replace(
b"\x00", b"\x20"
)
)
# Digital minimum (e.g., -2048) (8 bytes each)
for dmin in digital_min:
f.write(
struct.pack("<8s", "{:d}".format(dmin).encode("ascii")).replace(
b"\x00", b"\x20"
)
)
# Digital maximum (e.g., 2047) (8 bytes each)
for dmax in digital_max:
f.write(
struct.pack("<8s", "{:d}".format(dmax).encode("ascii")).replace(
b"\x00", b"\x20"
)
)
# Prefiltering (e.g., HP:0.1Hz LP:75Hz) (80 bytes each)
for _ in range(record.n_sig):
f.write(
struct.pack("<80s", b"prefiltering not recorded").replace(
b"\x00", b"\x20"
)
)
# Number of samples per block (8 bytes each)
for spr in samps_per_record:
f.write(
struct.pack("<8s", "{:d}".format(spr).encode("ascii")).replace(
b"\x00", b"\x20"
)
)
# The last 32*nsig bytes in the header are unused
for _ in range(record.n_sig):
f.write(struct.pack("<32s", b"").replace(b"\x00", b"\x20"))
# Write the data blocks
out_data.tofile(f, format="%d")
# Add the buffer
correct_bytes = num_blocks * sum(samps_per_record)
current_bytes = len(out_data)
num_to_write = correct_bytes - current_bytes
for i in range(num_to_write):
f.write(b"\x00\x80")
print("Header block size: {:d} bytes".format((record.n_sig + 1) * 256))
print(
"Data block size: {:g} seconds ({:d} frames or {:d} bytes)".format(
seconds_per_block, int(frames_per_block), int(bytes_per_block)
)
)
print(
"Recording length: {:d} ({:d} data blocks, {:d} frames, {:d} bytes)".format(
sum(
[
num_blocks,
num_blocks * int(frames_per_block),
num_blocks * bytes_per_block,
]
),
num_blocks,
num_blocks * int(frames_per_block),
num_blocks * bytes_per_block,
)
)
print(
"Total length of file to be written: {:d} bytes".format(
int((record.n_sig + 1) * 256 + num_blocks * bytes_per_block)
)
)
if edf_plus:
print(
(
"WARNING: EDF+ requires the subject's gender, birthdate, and name, as "
"well as additional information about the recording that is not usually "
"available. This information is not saved in the output file even if "
"available. EDF+ also requires the use of standard names for signals and "
"for physical units; these requirements are not enforced by this program. "
"To make the output file fully EDF+ compliant, its header must be edited "
"manually."
)
)
if "EDF-Annotations" not in record.sig_name:
print(
"WARNING: The output file does not include EDF annotations, which are required for EDF+."
)
# Check that all characters in the header are valid (printable ASCII
# between 32 and 126 inclusive). Note that this test does not prevent
# generation of files containing invalid characters; it merely warns
# the user if this has happened.
header_test = open(output_filename, "rb").read((record.n_sig + 1) * 256)
for i, val in enumerate(header_test):