ensemble-eeg 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of ensemble-eeg might be problematic. Click here for more details.

File without changes
@@ -0,0 +1,373 @@
1
+ import glob
2
+ import os
3
+ import shutil
4
+ import zipfile
5
+ from collections import Counter, namedtuple
6
+ from datetime import datetime, timezone
7
+
8
+ import defusedxml.ElementTree as ET
9
+ import numpy as np
10
+
11
+ import src.ensemble_eeg.ensemble_eeg as ensemble_eeg
12
+
13
+
14
+ def convert_brm_to_edf(fd, is_fs_64hz=None):
15
+ """
16
+ Converts a BRM file to EDF format.
17
+
18
+ Parameters:
19
+ fd (str): The path to the BRM file.
20
+ is_fs_64hz (bool, optional): Indicates whether the sampling frequency is 64 Hz. Defaults to None.
21
+
22
+ Raises:
23
+ ValueError: If the file is not found.
24
+
25
+ Returns:
26
+ None
27
+ """
28
+ filename = os.path.basename(fd)
29
+ file_exists = os.path.isfile(fd)
30
+
31
+ if file_exists:
32
+ file_dir = os.path.dirname(fd)
33
+ tmp_dir = os.path.join(file_dir, "tmp")
34
+ if os.path.isdir(tmp_dir):
35
+ shutil.rmtree(tmp_dir)
36
+
37
+ print(f"{filename}")
38
+ print("\tUnzipping to temporary directory")
39
+ with zipfile.ZipFile(fd, "r") as zip_ref:
40
+ zip_ref.extractall(tmp_dir)
41
+
42
+ index_xml = os.path.join(tmp_dir, "BRM_Index.xml")
43
+ index = parse_xml(index_xml)
44
+ device_xml = os.path.join(tmp_dir, "Device.xml")
45
+ device = parse_xml(device_xml)
46
+
47
+ dat_files_left = []
48
+ dat_files_right = []
49
+
50
+ if is_fs_64hz is None:
51
+ is_fs_64hz = (
52
+ input("is the sampling " "frequency 64 Hz? [y/N]: ").lower() == "y"
53
+ )
54
+
55
+ if is_fs_64hz:
56
+ dat_files_left = sorted(
57
+ glob.glob(os.path.join(tmp_dir, "DATA_RAW_EEG_LEFT*.dat"))
58
+ )
59
+ dat_files_right = sorted(
60
+ glob.glob(os.path.join(tmp_dir, "DATA_RAW_EEG_RIGHT*.dat"))
61
+ )
62
+
63
+ else:
64
+ dat_files_left = sorted(
65
+ glob.glob(os.path.join(tmp_dir, "DATA_RAW_EEG_ELECTRODE_LEFT*.dat"))
66
+ )
67
+ dat_files_right = sorted(
68
+ glob.glob(os.path.join(tmp_dir, "DATA_RAW_EEG_ELECTRODE_RIGHT*.dat"))
69
+ )
70
+
71
+ n_data_files_left = len(dat_files_left)
72
+ n_data_files_right = len(dat_files_right)
73
+
74
+ assert n_data_files_left == n_data_files_right
75
+
76
+ for i in range(0, n_data_files_left):
77
+ both_dat_files = [dat_files_left[i], dat_files_right[i]]
78
+ data = extract_brm_file(index, device, both_dat_files)
79
+
80
+ if i == 0:
81
+ output_filename = os.path.splitext(fd)[0] + ".edf"
82
+ else:
83
+ output_filename = os.path.splitext(fd)[0] + "_" + str(i) + ".edf"
84
+
85
+ hdr = prepare_edf_header(data)
86
+ signal_header = prepare_edf_signal_header(data, device)
87
+ header = ensemble_eeg.Header(*hdr, signal_header)
88
+
89
+ # write header to file
90
+ print(f"\tprint header to {output_filename}")
91
+ ensemble_eeg.write_edf_header(output_filename, header)
92
+
93
+ # write data to file
94
+ print(f"\tprint data records to {output_filename}")
95
+ write_brm_data_to_edf(output_filename, data)
96
+
97
+ print("\tremoving temporary directory")
98
+ shutil.rmtree(tmp_dir)
99
+ else:
100
+ raise ValueError("file not found")
101
+
102
+
103
+ def parse_xml(xml):
104
+ """
105
+ Parse an XML file and return a named tuple representing the parsed XML.
106
+
107
+ Parameters:
108
+ xml (str): The path to the XML file to be parsed.
109
+
110
+ Returns:
111
+ Parsed_XML: A named tuple representing the parsed XML. The fields of the
112
+ named tuple correspond to the unique XML tags found in the file. If
113
+ a tag appears only once, the corresponding field of the named tuple
114
+ will contain the text content of the tag. If a tag appears multiple
115
+ times, the corresponding field of the named tuple will contain a
116
+ list of named tuples, each representing one occurrence of the tag.
117
+ The fields of the nested named tuples correspond to the unique tags
118
+ found within the repeated tag, and the values of the fields
119
+ correspond to the text content of the corresponding tags.
120
+
121
+ Raises:
122
+ ValueError: If the specified XML file does not exist.
123
+
124
+ Example:
125
+ >>> parse_xml('data.xml')
126
+ Parsed_XML(tag_names=['tag1', 'tag2'], tag1='text1', tag2=[Tag2(tag3='text3', tag4='text4')])
127
+ """
128
+ file_exists = os.path.isfile(xml)
129
+
130
+ if file_exists:
131
+ tree = ET.parse(xml)
132
+ root = tree.getroot()
133
+
134
+ all_tags = [child.tag for child in root]
135
+ tag_names = list(Counter(all_tags).keys())
136
+ tag_dict = list(Counter(all_tags).items())
137
+
138
+ Parsed_XML = namedtuple("ParsedXML", tag_names)
139
+ parsed_xml = []
140
+ counter = 0
141
+ for name, vals in tag_dict:
142
+ if vals == 1:
143
+ parsed_xml.append(root[counter].text)
144
+ counter = counter + 1
145
+ else:
146
+ parsed_child = []
147
+ child_elems = root.findall(name)
148
+ for child_elem in child_elems:
149
+ child_elem_tags = [el.tag for el in child_elem]
150
+ child_elem_vals = [el.text for el in child_elem]
151
+ tup = namedtuple(child_elem.tag, child_elem_tags)
152
+ parsed_child.append(tup(*child_elem_vals))
153
+ counter = counter + 1
154
+ parsed_xml.append(parsed_child)
155
+
156
+ else:
157
+ raise ValueError("file not found")
158
+
159
+ return Parsed_XML(*parsed_xml)
160
+
161
+
162
+ def extract_brm_file(index, device, dat_files):
163
+ """
164
+ Extracts data from BRM files based on the given index, device, and dat_files.
165
+
166
+ Parameters:
167
+ index (Index): The index object containing file descriptions.
168
+ device (Device): The device to extract data for.
169
+ dat_files (List[str]): The list of dat files to extract data from.
170
+
171
+ Returns:
172
+ List[List[Data]]: A list of data extracted from BRM files.
173
+ """
174
+ filenames = [fd.FileName for fd in index.FileDescription]
175
+
176
+ counter = 0
177
+ data = [[] for _ in dat_files]
178
+
179
+ for dat_file in dat_files:
180
+ df = os.path.basename(dat_file)
181
+ file = index.FileDescription[filenames.index(df)]
182
+ file = file._replace(FileName=dat_file)
183
+ print(f"\textracting {df} datastream")
184
+ data[counter] = get_brm_data(file, device)
185
+ counter = counter + 1
186
+
187
+ return data
188
+
189
+
190
+ def get_brm_data(file, device):
191
+ """
192
+ Generates a named tuple containing the data from the given file and device.
193
+
194
+ Parameters:
195
+ file (namedtuple): The file containing the data.
196
+ device (str): The device associated with the data.
197
+
198
+ Returns:
199
+ Data: A named tuple containing the data from the file, the sample rate, and the numerical data.
200
+ """
201
+ DAUSampleHz = 512
202
+
203
+ Data = namedtuple("data", list(file._fields) + ["sampleHz", "data"])
204
+ data = list(file)
205
+ data.append(int(DAUSampleHz / int(file.SamplePeriod512thSeconds)))
206
+ data.append(get_numerical_data(file, device))
207
+
208
+ return Data(*data)
209
+
210
+
211
+ def get_numerical_data(file, device):
212
+ """
213
+ Reads numerical data from a file and returns it.
214
+
215
+ Parameters:
216
+ file (File): The file object representing the file to read from.
217
+ device (str): The device to use for reading the file.
218
+
219
+ Returns:
220
+ np.ndarray: The numerical data read from the file.
221
+
222
+ Raises:
223
+ Exception: If the file format is unrecognized.
224
+ """
225
+ f = open(file.FileName, "rb")
226
+
227
+ match file.FileType:
228
+ case "FloatMappedToInt16" | "Int16":
229
+ data = np.fromfile(f, dtype=np.int16)
230
+ case "Float32":
231
+ data = np.fromfile(f, dtype=np.float32)
232
+ case _:
233
+ raise Exception(f"Unrecognized file format {file.FileType}")
234
+
235
+ return data
236
+
237
+
238
+ def prepare_edf_header(data):
239
+ """
240
+ Generate the header for an EDF (European Data Format) file.
241
+
242
+ Args:
243
+ data: A list of objects containing the data for each channel.
244
+
245
+ Returns:
246
+ header: A list containing the header information for the EDF file.
247
+
248
+ Raises:
249
+ None.
250
+
251
+ Examples:
252
+ >>> data = [channel1, channel2]
253
+ >>> prepare_edf_header(data)
254
+ ['0', 'X X X X', 'Startdate X X X X', 'dd.mm.yy', 'hh.mm.ss',
255
+ header_size, None, n_records, '1', n_signals]
256
+ """
257
+ n_channels = 2
258
+ version = "0"
259
+ PID = "X X X X"
260
+ RID = "Startdate X X X X"
261
+ # start_date = datetime.strftime(
262
+ # datetime.fromtimestamp(int(data[0].StartTime), timezone.utc), format="%d.%m.%y"
263
+ # )
264
+ # start_time = datetime.strftime(
265
+ # datetime.fromtimestamp(int(data[0].StartTime), timezone.utc), format="%H.%M.%S"
266
+ # )
267
+
268
+ start_date = "01.01.85"
269
+ start_time = "00.00.00"
270
+
271
+ bytes_in_header = (
272
+ ensemble_eeg.HEADER_SIZE + n_channels * ensemble_eeg.SIGNAL_HEADER_SIZE
273
+ )
274
+ reserved = None
275
+ fs = data[0].sampleHz
276
+ n_records = int(np.floor(len(data[0].data) / fs))
277
+ dur_data_record = "1"
278
+ n_signals = len(data)
279
+ header = [
280
+ version,
281
+ PID,
282
+ RID,
283
+ start_date,
284
+ start_time,
285
+ bytes_in_header,
286
+ reserved,
287
+ n_records,
288
+ dur_data_record,
289
+ n_signals,
290
+ ]
291
+
292
+ return header
293
+
294
+
295
+ def prepare_edf_signal_header(data, device):
296
+ """
297
+ Generate the signal headers for an EDF file based on the provided data and device.
298
+
299
+ Parameters:
300
+ data (list): A list of data objects.
301
+ device (Device): The device object.
302
+
303
+ Returns:
304
+ tuple: A tuple of signal headers.
305
+ """
306
+ channel_ids = [channel.ID for channel in device.Channel]
307
+ units = data[0].Units
308
+
309
+ # replace non-ascii characters
310
+ if "µ" in units:
311
+ units = units.replace("µ", "u")
312
+
313
+ signal_headers = [[] for _ in data]
314
+ for i in range(0, len(data)):
315
+ ichan = channel_ids.index(data[i].ChannelTitle)
316
+ if data[i].ChannelTitle == "Left":
317
+ label = "F3"
318
+ elif data[i].ChannelTitle == "Right":
319
+ label = "F4"
320
+
321
+ transducer_type = None
322
+ physical_dimension = units
323
+ physical_min = round(-5e6 / float(device.Channel[ichan].Gain) / 2)
324
+ physical_max = round(5e6 / float(device.Channel[ichan].Gain) / 2)
325
+ digital_min = -(2**15)
326
+ digital_max = 2**15 - 1
327
+ prefiltering = None
328
+ nr_samples = data[i].sampleHz
329
+ reserved = None
330
+ sig_header = [
331
+ label,
332
+ transducer_type,
333
+ physical_dimension,
334
+ physical_min,
335
+ physical_max,
336
+ digital_min,
337
+ digital_max,
338
+ prefiltering,
339
+ nr_samples,
340
+ reserved,
341
+ ]
342
+ signal_headers[i] = ensemble_eeg.SignalHeader(*sig_header)
343
+
344
+ return tuple(signal_headers)
345
+
346
+
347
+ def write_brm_data_to_edf(filename, data):
348
+ """
349
+ Write BRM data to EDF file.
350
+
351
+ Args:
352
+ filename (str): The name of the file to write the data to.
353
+ data (list): A list of data objects.
354
+
355
+ Returns:
356
+ None
357
+ """
358
+ file_exists = os.path.isfile(filename)
359
+ dat1 = data[0].data
360
+ dat2 = data[1].data
361
+
362
+ if file_exists:
363
+ fs = data[0].sampleHz
364
+ n_records = int(np.floor(len(data[0].data) / fs))
365
+ fd = open(filename, "ab")
366
+
367
+ index = 0
368
+ for i_record in range(0, n_records):
369
+ fd.write(dat1[index : (index + fs)])
370
+ fd.write(dat2[index : (index + fs)])
371
+ index = (i_record + 1) * fs
372
+
373
+ fd.close()
@@ -0,0 +1,600 @@
1
+ import os
2
+ import shutil
3
+ import warnings
4
+ from collections import namedtuple
5
+
6
+ import numpy as np
7
+
8
+
9
+ def _str(f, size, _):
10
+ s = f.read(size).decode("ascii", "ignore").strip()
11
+ while s.endswith("\x00"):
12
+ s = s[:-1]
13
+ return s
14
+
15
+
16
+ def _int(f, size, name):
17
+ s = _str(f, size, name)
18
+ try:
19
+ return int(s)
20
+ except ValueError:
21
+ warnings.warn("{name}: Could not parse integer {s}.".format(name=name, s=s))
22
+
23
+
24
+ def _float(f, size, name):
25
+ s = _str(f, size, name)
26
+ try:
27
+ return float(s)
28
+ except ValueError:
29
+ warnings.warn("{name}: Could not parse float {s}.".format(name=name, s=s))
30
+
31
+
32
+ def _discard(f, size, _):
33
+ f.read(size)
34
+
35
+
36
+ HEADER = (
37
+ ("version", 8, _str),
38
+ ("local_patient_identification", 80, _str),
39
+ ("local_recording_identification", 80, _str),
40
+ ("startdate_of_recording", 8, _str),
41
+ ("starttime_of_recording", 8, _str),
42
+ ("number_of_bytes_in_header_record", 8, _int),
43
+ ("reserved", 44, _discard),
44
+ ("number_of_data_records", 8, _int),
45
+ ("duration_of_a_data_record", 8, _float),
46
+ ("number_of_signals", 4, _int),
47
+ )
48
+
49
+
50
+ SIGNAL_HEADER = (
51
+ ("label", 16, _str),
52
+ ("transducer_type", 80, _str),
53
+ ("physical_dimension", 8, _str),
54
+ ("physical_minimum", 8, _float),
55
+ ("physical_maximum", 8, _float),
56
+ ("digital_minimum", 8, _int),
57
+ ("digital_maximum", 8, _int),
58
+ ("prefiltering", 80, _str),
59
+ ("nr_of_samples_in_each_data_record", 8, _int),
60
+ ("reserved", 32, _discard),
61
+ )
62
+
63
+ INT_SIZE = 2
64
+ HEADER_SIZE = sum([size for _, size, _ in HEADER])
65
+ SIGNAL_HEADER_SIZE = sum([size for _, size, _ in SIGNAL_HEADER])
66
+
67
+ Header = namedtuple("Header", [name for name, _, _ in HEADER] + ["signals"])
68
+ SignalHeader = namedtuple("SignalHeader", [name for name, _, _ in SIGNAL_HEADER])
69
+
70
+
71
+ def read_edf_header(fd):
72
+ """
73
+ Reads the header of an EDF file.
74
+
75
+ Parameters:
76
+ fd (str or file-like object): The file descriptor or the path to the EDF file.
77
+
78
+ Returns:
79
+ Header: The header of the EDF file, including information about the signals.
80
+
81
+ Raises:
82
+ FileNotFoundError: If the file specified by `fd` does not exist.
83
+ ValueError: If `fd` is not a valid EDF file.
84
+ """
85
+ opened = False
86
+ if isinstance(fd, str):
87
+ opened = True
88
+ fd = open(fd, "rb")
89
+
90
+ header = [func(fd, size, name) for name, size, func in HEADER]
91
+ number_of_signals = header[-1]
92
+ signal_headers = [[] for _ in range(number_of_signals)]
93
+
94
+ for name, size, func in SIGNAL_HEADER:
95
+ for signal_header in signal_headers:
96
+ signal_header.append(func(fd, size, name))
97
+
98
+ header.append(
99
+ tuple(SignalHeader(*signal_header) for signal_header in signal_headers)
100
+ )
101
+
102
+ if opened:
103
+ fd.close()
104
+
105
+ return Header(*header)
106
+
107
+
108
+ def read_edf_data(fd, header, chans="all"):
109
+ """
110
+ Reads EDF data from a file or file-like object.
111
+
112
+ Parameters:
113
+ fd (str or file-like object): The file path or file-like object to read the EDF data from.
114
+ header (Header): The EDF header object containing information about the data.
115
+
116
+ Returns:
117
+ generator: A generator that yields each data record as a list of signals.
118
+
119
+ Raises:
120
+ IOError: If there was an error opening or reading the EDF file.
121
+ """
122
+ opened = False
123
+ if isinstance(fd, str):
124
+ opened = True
125
+ fd = open(fd, "rb")
126
+
127
+ start = 0
128
+ end = header.number_of_data_records
129
+
130
+ if chans == "all":
131
+ chans = list(range(header.number_of_signals))
132
+
133
+ data_record_length = sum(
134
+ [signal.nr_of_samples_in_each_data_record for signal in header.signals]
135
+ )
136
+
137
+ if opened:
138
+ fd.seek(
139
+ HEADER_SIZE
140
+ + header.number_of_signals * SIGNAL_HEADER_SIZE
141
+ + start * data_record_length * INT_SIZE
142
+ )
143
+
144
+ for _ in range(start, end):
145
+ a = np.fromfile(fd, count=data_record_length, dtype=np.int16)
146
+
147
+ offset = 0
148
+ chan_nr = 0
149
+ data_record = []
150
+ for signal in header.signals:
151
+ if chan_nr in chans:
152
+ data_record.append(
153
+ a[offset : offset + signal.nr_of_samples_in_each_data_record]
154
+ )
155
+
156
+ offset += signal.nr_of_samples_in_each_data_record
157
+ chan_nr += 1
158
+
159
+ yield data_record
160
+
161
+ if opened:
162
+ fd.close()
163
+
164
+
165
+ def write_edf_header(fd, header):
166
+ """
167
+ Writes the EDF header to the specified file-like object or file path.
168
+
169
+ Args:
170
+ fd (str): (Relative) path to file to write.
171
+ header: The header information to write.
172
+
173
+ Raises:
174
+ AssertionError: If the length of the value to write is not equal to the expected size.
175
+
176
+ Returns:
177
+ None
178
+ """
179
+ opened = False
180
+ if isinstance(fd, str):
181
+ fd = open(fd, "wb")
182
+ opened = True
183
+
184
+ for val, (name, size, _) in zip(header, HEADER):
185
+ if val is None:
186
+ val = b"\x20" * size
187
+
188
+ if not isinstance(val, bytes):
189
+ if (
190
+ name == "startdate_of_recording" or name == "starttime_of_recording"
191
+ ) and not isinstance(val, str):
192
+ val = "{:02d}.{:02d}.{:02d}".format(val[0], val[1], val[2] % 100)
193
+ val = str(val).encode(encoding="ascii").ljust(size, b"\x20")
194
+
195
+ assert len(val) == size
196
+ fd.write(val)
197
+
198
+ for vals, (name, size, _) in zip(zip(*header.signals), SIGNAL_HEADER):
199
+ for val in vals:
200
+ if val is None:
201
+ val = b"\x20" * size
202
+
203
+ if not isinstance(val, bytes):
204
+ val = str(val).encode(encoding="ascii").ljust(size, b"\x20")
205
+
206
+ assert len(val) == size
207
+ fd.write(val)
208
+
209
+ if opened:
210
+ fd.close()
211
+
212
+
213
+ def write_edf_data(fd, data_records):
214
+ """Function to check and fix edf files according to EDF plus standards
215
+
216
+ Args:
217
+ fd (str): (Relative) path to file to write.
218
+ data_records (array): Variable with data_records to write to edf file\
219
+ is output from read_edf_data function
220
+
221
+ """
222
+ opened = False
223
+ if isinstance(fd, str):
224
+ opened = True
225
+ fd = open(fd, "ab")
226
+ for data_record in data_records:
227
+ for signal in data_record:
228
+ signal.tofile(fd)
229
+ # try:
230
+
231
+ if opened:
232
+ fd.close()
233
+
234
+
235
+ def fix_edf_header(fd):
236
+ """
237
+ Fix the EDF header.
238
+
239
+ Args:
240
+ fd (file object): The file descriptor for the EDF file.
241
+
242
+ Returns:
243
+ None
244
+ """
245
+
246
+ if not (os.path.isfile(fd)):
247
+ raise FileNotFoundError(fd)
248
+ else:
249
+ print(f"fixing header for {fd} ... ", end="", flush=True)
250
+
251
+ header = read_edf_header(fd)
252
+ data = read_edf_data(fd, header)
253
+
254
+ something_to_fix = False
255
+ if ":" in header.startdate_of_recording:
256
+ warnings.warn(
257
+ f"start date {header.startdate_of_recording} "
258
+ "contains colon (:), changing to dot (.)"
259
+ )
260
+ header = header._replace(
261
+ startdate_of_recording=header.startdate_of_recording.replace(":", ".")
262
+ )
263
+ something_to_fix = True
264
+
265
+ if ":" in header.starttime_of_recording:
266
+ warnings.warn(
267
+ f"start time {header.starttime_of_recording}"
268
+ "contains colon (:), changing to dot (.)"
269
+ )
270
+ header = header._replace(
271
+ starttime_of_recording=header.starttime_of_recording.replace(":", ".")
272
+ )
273
+ something_to_fix = True
274
+
275
+ for signal in header.signals:
276
+ if signal.physical_maximum <= signal.physical_minimum:
277
+ warnings.warn(
278
+ f"channel {signal.label}: physical maximum "
279
+ f"({signal.physical_maximum}) is smaller or equal "
280
+ f"to physical minimum ({signal.physical_minimum})"
281
+ )
282
+
283
+ if signal.digital_maximum <= signal.digital_minimum:
284
+ warnings.warn(
285
+ f"channel {signal.label}: digital maximum "
286
+ f"({signal.digital_maximum}) is smaller or equal "
287
+ f"to digital minimum ({signal.digital_minimum})"
288
+ )
289
+
290
+ if something_to_fix:
291
+ tmp_fd = fd + "tmp"
292
+ write_edf_header(tmp_fd, header)
293
+ write_edf_data(tmp_fd, data)
294
+
295
+ assert os.path.getsize(tmp_fd) == os.path.getsize(fd)
296
+ os.replace(tmp_fd, fd)
297
+
298
+ print("done")
299
+
300
+
301
+ def anonymize_edf_header(fd):
302
+ """Function to anonymize edf files according to ENSEMBLE and BIDS standards.
303
+ The output file will be appended with ANONYMIZED in the filename. Please
304
+ make sure to only upload the anonymized files.
305
+
306
+
307
+ Args:
308
+ fd (str): (Relative) path to file to rename.
309
+
310
+ """
311
+ if not (os.path.isfile(fd)):
312
+ raise FileNotFoundError(fd)
313
+ else:
314
+ print(f"anonymizing {fd} ... ", end="", flush=True)
315
+
316
+ header = read_edf_header(fd)
317
+ data = read_edf_data(fd, header)
318
+
319
+ filename = os.path.splitext(os.path.basename(fd))[0]
320
+ ext = os.path.splitext(os.path.basename(fd))[1]
321
+ folder = os.path.dirname(fd)
322
+ split_filename = filename.split("_")
323
+ is_ensemble_approved = (
324
+ split_filename[0] == "subj"
325
+ and len(split_filename[1]) == 10
326
+ and ("E" in split_filename[1])
327
+ )
328
+
329
+ anonymized_rid = "Startdate X X X X"
330
+ if is_ensemble_approved:
331
+ pseudo_code = split_filename[1]
332
+ anonymized_pid = pseudo_code + " X X X"
333
+ else:
334
+ anonymized_pid = "X X X X"
335
+
336
+ anonymized_startdate = "01.01.85"
337
+ anonymized_starttime = "00.00.00"
338
+
339
+ header = header._replace(
340
+ local_patient_identification=anonymized_pid,
341
+ local_recording_identification=anonymized_rid,
342
+ startdate_of_recording=anonymized_startdate,
343
+ starttime_of_recording=anonymized_starttime,
344
+ )
345
+
346
+ fd_out = os.path.join(folder, filename + "_ANONYMIZED" + ext)
347
+ write_edf_header(fd_out, header)
348
+ write_edf_data(fd_out, data)
349
+
350
+ print("done")
351
+
352
+
353
+ def rename_for_ensemble(fd):
354
+ """Function to rename edf files according to ENSEMBLE and BIDS standards
355
+
356
+ Args:
357
+ fd (str): (Relative) path to file to rename.
358
+
359
+ """
360
+ if not os.path.isfile(fd):
361
+ raise FileNotFoundError(fd)
362
+
363
+ filedir = os.path.expanduser(os.path.dirname(fd))
364
+ if not filedir:
365
+ filedir = os.getcwd()
366
+
367
+ while True:
368
+ print(f"changing name of {fd}")
369
+ filename = os.path.basename(fd)
370
+
371
+ # check whether filename needs to be changed
372
+ do_renaming = check_filename_ensemble(filename)
373
+
374
+ if do_renaming:
375
+ header = read_edf_header(fd)
376
+
377
+ # get the new subject code
378
+ subject_code = get_subject_code()
379
+
380
+ # check type of acquisition
381
+ acq = get_acquisition_type(header)
382
+
383
+ # check type of session
384
+ ses = get_session_type()
385
+
386
+ split_new_filename = [subject_code, ses, acq, "run-1_eeg.edf"]
387
+ new_filename = "_".join(split_new_filename)
388
+
389
+ print(f"new filename is {new_filename}")
390
+ correct_filename = input("Is this correct? [Y/n]: ")
391
+
392
+ if correct_filename.lower() == "y":
393
+ break
394
+
395
+ # Create new directory and copy renamed file
396
+ new_dirname = os.path.join(filedir, subject_code)
397
+ new_filename = os.path.join(new_dirname, new_filename)
398
+
399
+ if not os.path.isdir(new_dirname):
400
+ os.mkdir(new_dirname)
401
+
402
+ if os.path.isfile(new_filename):
403
+ print("File already exists, not overwriting")
404
+ else:
405
+ shutil.copy(fd, new_filename)
406
+
407
+
408
+ def combine_aeeg_channels(fd_left, fd_right, new_filename="two_channel_aeeg"):
409
+ """
410
+ Combine left and right aEEG channels into a single edf file.
411
+
412
+ Args:
413
+ fd_left (str): The file path of the left aEEG channel.
414
+ fd_right (str): The file path of the right aEEG channel.
415
+ new_filename (str, optional): The name of the new combined file. Defaults to "two_channel_aeeg".
416
+
417
+ Raises:
418
+ FileNotFoundError: If fd_left or fd_right is not a valid file path.
419
+ """
420
+ if not os.path.isfile(fd_left):
421
+ raise FileNotFoundError(fd_left)
422
+ elif not os.path.isfile(fd_right):
423
+ raise FileNotFoundError(fd_right)
424
+
425
+ filename_left = os.path.basename(fd_left)
426
+ filename_right = os.path.basename(fd_right)
427
+ print(f"Combining {filename_left} and {filename_right} ... ", end="", flush=True)
428
+
429
+ output_dir = os.path.dirname(fd_left)
430
+ path_to_file = os.path.join(output_dir, new_filename + ".edf")
431
+
432
+ hdr_left = read_edf_header(fd_left)
433
+ hdr_right = read_edf_header(fd_right)
434
+
435
+ opened = False
436
+ if isinstance(fd_left, str):
437
+ opened = True
438
+ fd = open(fd_left, "rb")
439
+
440
+ # create new header by combining left and right channel headers, get the
441
+ # annotation channel from right channel
442
+ header = [func(fd, size, name) for name, size, func in HEADER]
443
+
444
+ # create new signal headers
445
+ signal_headers_left = [hdr_left.signals[0]]
446
+ signal_headers_right = [signal for signal in hdr_right.signals]
447
+ signal_headers = signal_headers_left + signal_headers_right
448
+ header[-1] = len(signal_headers)
449
+ header.append(
450
+ tuple(SignalHeader(*signal_header) for signal_header in signal_headers)
451
+ )
452
+
453
+ # calculate new header length
454
+ header_length = HEADER_SIZE + len(signal_headers) * SIGNAL_HEADER_SIZE
455
+ header[5] = header_length
456
+
457
+ # read in data from both left and right channels, read - if possible -
458
+ # annotation channel from right channel edf file
459
+ labels_left = [signal.label for signal in hdr_left.signals]
460
+ chans = list(range(hdr_left.number_of_signals))
461
+ if "EDF Annotations" in labels_left:
462
+ chans.remove(labels_left.index("EDF Annotations"))
463
+
464
+ data_left = list(read_edf_data(fd_left, hdr_left, chans=chans))
465
+ data_right = list(read_edf_data(fd_right, hdr_right))
466
+
467
+ # append channels
468
+ data_all = append_channels(data_left, data_right)
469
+
470
+ write_edf_header(path_to_file, Header(*header))
471
+ write_edf_data(path_to_file, data_all)
472
+
473
+ if opened:
474
+ fd.close()
475
+
476
+ print("done")
477
+
478
+
479
+ def append_channels(data_left, data_right):
480
+ """
481
+ This function takes two lists of data and appends the corresponding elements from the second list to the elements in the first list. It yields the appended elements.
482
+ """
483
+ counter = 0
484
+ for _ in range(len(data_left)):
485
+ dat_out = data_left[counter]
486
+ dat_out.extend(data_right[counter])
487
+ counter += 1
488
+
489
+ yield dat_out
490
+
491
+
492
+ def check_filename_ensemble(filename):
493
+ """
494
+ Helper function to check filename and compare to the ENSEMBLE standard
495
+
496
+ Args:
497
+ fd (str): (Relative) path to file to rename.
498
+
499
+ """
500
+ split_filename = filename.split("_")
501
+ do_renaming = True
502
+
503
+ if (
504
+ (split_filename[0] == "subj")
505
+ and ("ses" in split_filename[2])
506
+ and ("acq" in split_filename[3])
507
+ and ("run" in split_filename[4])
508
+ and (split_filename[-1] == "eeg.edf")
509
+ ):
510
+ do_renaming = False
511
+ warnings.warn(
512
+ "The filename already seems to adhere to the ensemble " "and BIDS standard "
513
+ )
514
+ continue_renaming = input("Are you sure you want to rename this file? " "[y/N]")
515
+ do_renaming = continue_renaming.lower() == "y"
516
+
517
+ return do_renaming
518
+
519
+
520
+ def get_subject_code():
521
+ """
522
+ Helper code to get subject code with user input
523
+ """
524
+
525
+ # Get centre code
526
+ while True:
527
+ centre_code = input("Please input your centre code [xxx]: ")
528
+ if len(centre_code) != 3 or not centre_code.isdigit():
529
+ print("Centre code must consist of three digits")
530
+ continue
531
+ break
532
+
533
+ # Get subject number
534
+ while True:
535
+ subject_number = input("Please input your subject number [xxxxx]: ")
536
+ if len(subject_number) != 5 or not subject_number.isdigit():
537
+ print("Subject number must consist of five digits")
538
+ continue
539
+ break
540
+
541
+ # Get sibling number
542
+ while True:
543
+ sibling_number = input("Please input the sibling number [x]: ")
544
+ if len(sibling_number) != 1 or not sibling_number.isdigit():
545
+ print("Sibling number must consist of a single digit")
546
+ continue
547
+ break
548
+
549
+ subject_code = "sub-" + centre_code + "E" + subject_number + sibling_number
550
+
551
+ return subject_code
552
+
553
+
554
+ def get_acquisition_type(header):
555
+ """
556
+ Helper code to get acquisition type with user input or header information.
557
+
558
+ Args:
559
+ header: The header information of the file.
560
+
561
+ Returns:
562
+ acq: The determined acquisition type.
563
+ """
564
+ # Check number of signals in file
565
+ if header.number_of_signals <= 4:
566
+ acq = "acq-aeeg"
567
+ print("file automatically determined to be aEEG")
568
+ correct_acq = input("is this correct? [Y/n]: ").lower()
569
+
570
+ if correct_acq == "n":
571
+ acq = "acq-ceeg"
572
+
573
+ else:
574
+ acq = "acq-ceeg"
575
+ print("file automatically determined to be cEEG")
576
+ correct_acq = input("is this correct? [Y/n]: ").lower()
577
+
578
+ if correct_acq == "n":
579
+ acq = "acq-aeeg"
580
+
581
+ return acq
582
+
583
+
584
+ def get_session_type():
585
+ """
586
+ Helper code to get session type with user input
587
+ """
588
+ while 1:
589
+ ses_string = (
590
+ "During which session was this recordig taken? " + "[(d)iag/(t)erm]: "
591
+ )
592
+ ses = input(ses_string).lower()
593
+ if ses == "d" or ses == "diag":
594
+ ses = "ses-diag"
595
+ break
596
+ elif ses == "t" or ses == "term":
597
+ ses = "ses-term"
598
+ break
599
+
600
+ return ses
@@ -0,0 +1,189 @@
1
+ GNU GENERAL PUBLIC LICENSE
2
+
3
+ Version 3, 29 June 2007
4
+
5
+ Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
6
+
7
+ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for software and other kinds of works.
11
+
12
+ The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
13
+
14
+ When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
15
+
16
+ To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
17
+
18
+ For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
19
+
20
+ Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
21
+
22
+ For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
23
+
24
+ Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
25
+
26
+ Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
27
+
28
+ The precise terms and conditions for copying, distribution and modification follow.
29
+ TERMS AND CONDITIONS
30
+ 0. Definitions.
31
+
32
+ “This License” refers to version 3 of the GNU General Public License.
33
+
34
+ “Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
35
+
36
+ “The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
37
+
38
+ To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
39
+
40
+ A “covered work” means either the unmodified Program or a work based on the Program.
41
+
42
+ To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
43
+
44
+ To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
45
+
46
+ An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
47
+ 1. Source Code.
48
+
49
+ The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
50
+
51
+ A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
52
+
53
+ The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
54
+
55
+ The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
56
+
57
+ The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
58
+
59
+ The Corresponding Source for a work in source code form is that same work.
60
+ 2. Basic Permissions.
61
+
62
+ All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
63
+
64
+ You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
65
+
66
+ Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
67
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
68
+
69
+ No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
70
+
71
+ When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
72
+ 4. Conveying Verbatim Copies.
73
+
74
+ You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
75
+
76
+ You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
77
+ 5. Conveying Modified Source Versions.
78
+
79
+ You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
80
+
81
+ a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
82
+ b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
83
+ c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
84
+ d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
85
+
86
+ A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
87
+ 6. Conveying Non-Source Forms.
88
+
89
+ You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
90
+
91
+ a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
92
+ b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
93
+ c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
94
+ d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
95
+ e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
96
+
97
+ A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
98
+
99
+ A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
100
+
101
+ “Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
102
+
103
+ If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
104
+
105
+ The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
106
+
107
+ Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
108
+ 7. Additional Terms.
109
+
110
+ “Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
111
+
112
+ When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
113
+
114
+ Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
115
+
116
+ a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
117
+ b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
118
+ c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
119
+ d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
120
+ e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
121
+ f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
122
+
123
+ All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
124
+
125
+ If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
126
+
127
+ Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
128
+ 8. Termination.
129
+
130
+ You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
131
+
132
+ However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
133
+
134
+ Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
135
+
136
+ Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
137
+ 9. Acceptance Not Required for Having Copies.
138
+
139
+ You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
140
+ 10. Automatic Licensing of Downstream Recipients.
141
+
142
+ Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
143
+
144
+ An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
145
+
146
+ You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
147
+ 11. Patents.
148
+
149
+ A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
150
+
151
+ A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
152
+
153
+ Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
154
+
155
+ In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
156
+
157
+ If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
158
+
159
+ If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
160
+
161
+ A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
162
+
163
+ Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
164
+ 12. No Surrender of Others' Freedom.
165
+
166
+ If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
167
+ 13. Use with the GNU Affero General Public License.
168
+
169
+ Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
170
+ 14. Revised Versions of this License.
171
+
172
+ The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
173
+
174
+ Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
175
+
176
+ If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
177
+
178
+ Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
179
+ 15. Disclaimer of Warranty.
180
+
181
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
182
+ 16. Limitation of Liability.
183
+
184
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
185
+ 17. Interpretation of Sections 15 and 16.
186
+
187
+ If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
188
+
189
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.1
2
+ Name: ensemble_eeg
3
+ Version: 0.0.1
4
+ Summary: Package used to analyze preprocess edf files for the ENSEMBLE2 study
5
+ Author: Bauke van der Velde
6
+ Author-email: Bauke van der Velde <b.vandervelde-3@umcutrecht.nl>
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
9
+ Classifier: Operating System :: OS Independent
10
+ Requires-Python: >3.10
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ License-File: NOTICE
14
+ Requires-Dist: numpy
15
+ Requires-Dist: defusedxml
16
+
17
+ # ENSEMBLE EEG
18
+
19
+ Ensemble EEG is a library of EEG analyis tools for the ENSEMBLE study. As of
20
+ today it is focuses on 4 seperate things:
21
+
22
+ - **Anonymizing** EDF files in accordance with the ENSEMBLE study and the
23
+ requirements of EDF+
24
+ - **Converting** BRM to EDF+ files
25
+ - **Combining** seperate aEEG channels into one EDF+ file
26
+ - **Renaming** EEG files according to ENSEMBLE and BIDS standards
27
+ - **Fixing** EDF headers to adhere to the EDF+ standard
28
+
29
+ ## Installation
30
+ ##### Pip
31
+ ```
32
+ python3 -m pip install ensemble_eeg
33
+ ```
34
+
35
+ ## Usage
36
+ ##### Anonymizing EDF-files
37
+ ```
38
+ >>> import ensemble_eeg
39
+ >>> ensemble_eeg.anonymize_edf_header('path/2/your/edf/file')
40
+ ```
41
+ ##### Fixing EDF headers
42
+ ```
43
+ >>> import ensemble_eeg
44
+ >>> ensemble_eeg.fix_edf_header('path/2/your/edf/file')
45
+ ```
46
+ ##### Converting BRM to EDF files
47
+ ```
48
+ >>> import brm_to_edf
49
+ >>> brm_to_edf.convert_brm_to_edf('path/2/your/brm/file')
50
+ ```
51
+ ##### Combine left and right aEEG channels into one single file
52
+ ```
53
+ >>> import ensemble_eeg
54
+ >>> ensemble_eeg.combine_aeeg_channels('path/2/your/left/channel', 'path/2/your/right/channel', 'new_filename')
55
+ ```
56
+ ##### Rename EDF-files according to BIDS and ENSEMBLE standards
57
+ ```
58
+ >>> import ensemble_eeg
59
+ >>> ensemble_eeg.rename_for_ensemble('path/2/your/edf/file')
60
+ ```
61
+ ### Situations
62
+ ##### 1) File is already EDF, but you do not know whether header is EDF+, the file is not anonymized, and not renamed
63
+ ```
64
+ >>> import ensemble_eeg
65
+ >>> file = 'path/2/your/edf/file'
66
+ >>> ensemble_eeg.fix_edf_header(file) # for header check
67
+ >>> ensemble_eeg.anonymize_edf_header(file) # for anonymization
68
+ >>> ensemble_eeg.rename_for_ensemble(file) # for renaming
69
+
70
+ ```
71
+ ##### 2) File is BRM
72
+ ```
73
+ >>> import ensemble_eeg
74
+ >>> brm_file = 'path/2/your/brm/file'
75
+ >>> brm_to_edf.convert_brm_to_edf(brm_file) # for conversion, output edf is already anonymized
76
+ >>> edf_file = 'path/2/your/edf/file' # check which file was made in previous step
77
+ >>> ensemble_eeg.rename_for_ensemble(edf_file) # for renaming
78
+
79
+ ```
80
+ ##### 3) Files are edf, but left and right channel are seperate
81
+ ```
82
+ >>> import ensemble_eeg
83
+ >>> left_file = 'path/2/your/left/edf/file'
84
+ >>> right_file = 'path/2/your/right/edf/file'
85
+ >>> ensemble_eeg.combine_aeeg_channels(left_file, right_file) # output is automatically anonymized
86
+ >>> ensemble_eeg.rename_for_ensemble(file) # for renaming
87
+
88
+ ```
89
+
90
+
91
+ ## Acknowledgements
92
+
@@ -0,0 +1,25 @@
1
+ ensemble_eeg is a Python 3 software library to preprocess eeg data for the ENSEMBLE
2
+ study, based - in part - on the edfrd library
3
+
4
+ Copyright 2018 Christoph Jansen
5
+ Copyright 2024 Bauke van der Velde
6
+
7
+ This program is free software: you can redistribute it and/or modify
8
+ it under the terms of the GNU Lesser General Public License as published by
9
+ the Free Software Foundation, either version 3 of the License, or
10
+ (at your option) any later version.
11
+
12
+ This program is distributed in the hope that it will be useful,
13
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
+ GNU Lesser General Public License for more details.
16
+
17
+ You should have received a copy of the GNU Lesser General Public License
18
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
19
+
20
+ Web:
21
+ - https://github.com/ensemble2/ensemble_eeg
22
+ - https://fondationparalysiecerebrale.org/projet-ensemble
23
+
24
+ E-Mail:
25
+ - b.vandervelde-3@umcutrecht.nl
@@ -0,0 +1,9 @@
1
+ ensemble_eeg/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ ensemble_eeg/brm_to_edf.py,sha256=0oUa92uCgYcnVaV-NoZhpLDdraDDXMTeCLrbNvrEvFI,11325
3
+ ensemble_eeg/ensemble_edf.py,sha256=zCp2gSOP9LA6B-Lg7KQvaMteMNZ1uJpxfNwq1UStIUg,17502
4
+ ensemble_eeg-0.0.1.dist-info/LICENSE,sha256=qXzAXUqPurJdhVIJzMejS0Qgs8zlMa9LWe8XyTBO9MA,32005
5
+ ensemble_eeg-0.0.1.dist-info/METADATA,sha256=GNc6yNt6vu1p2kNkxUG6jWvd3ardtO1_zeAH5F0SW6Y,2926
6
+ ensemble_eeg-0.0.1.dist-info/NOTICE,sha256=nHgkntXezqQ-K2wUhC-_jmiM6xl3Gc-9f6wNdcjjwIk,989
7
+ ensemble_eeg-0.0.1.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
8
+ ensemble_eeg-0.0.1.dist-info/top_level.txt,sha256=wZe3epOvL0kHDHu6RagQJUAE6TDvw-QTFz07xMcDzeY,37
9
+ ensemble_eeg-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.42.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ brm_to_edf
2
+ ensemble_edf
3
+ ensemble_eeg