python-intan 0.0.2__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.
- intan/__init__.py +42 -0
- intan/control/__init__.py +1 -0
- intan/control/_messaging.py +171 -0
- intan/io/__init__.py +64 -0
- intan/io/_block_parser.py +253 -0
- intan/io/_channel_utils.py +86 -0
- intan/io/_data_processing.py +193 -0
- intan/io/_exceptions.py +37 -0
- intan/io/_file_utils.py +110 -0
- intan/io/_header_parsing.py +383 -0
- intan/io/_metadata_utils.py +150 -0
- intan/io/_rhd_loader.py +199 -0
- intan/plotting/__init__.py +2 -0
- intan/plotting/_emg_plots.py +245 -0
- intan/plotting/_waterfall.py +132 -0
- intan/processing/__init__.py +20 -0
- intan/processing/_filters.py +569 -0
- intan/processing/_metrics_utils.py +84 -0
- python_intan-0.0.2.dist-info/METADATA +185 -0
- python_intan-0.0.2.dist-info/RECORD +23 -0
- python_intan-0.0.2.dist-info/WHEEL +5 -0
- python_intan-0.0.2.dist-info/licenses/LICENSE +21 -0
- python_intan-0.0.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import math
|
|
2
|
+
import numpy as np
|
|
3
|
+
from intan.io._file_utils import print_progress
|
|
4
|
+
|
|
5
|
+
def parse_data(header, data):
|
|
6
|
+
"""Parses raw data into user readable and interactable forms (for example,
|
|
7
|
+
extracting raw digital data to separate channels and scaling data to units
|
|
8
|
+
like microVolts, degrees Celsius, or seconds.)
|
|
9
|
+
"""
|
|
10
|
+
print('Parsing data...')
|
|
11
|
+
extract_digital_data(header, data)
|
|
12
|
+
scale_analog_data(header, data)
|
|
13
|
+
scale_timestamps(header, data)
|
|
14
|
+
|
|
15
|
+
def scale_timestamps(header, data):
|
|
16
|
+
"""Verifies no timestamps are missing, and scales timestamps to seconds.
|
|
17
|
+
"""
|
|
18
|
+
# Check for gaps in timestamps.
|
|
19
|
+
num_gaps = np.sum(np.not_equal(
|
|
20
|
+
data['t_amplifier'][1:]-data['t_amplifier'][:-1], 1))
|
|
21
|
+
if num_gaps == 0:
|
|
22
|
+
print('No missing timestamps in data.')
|
|
23
|
+
else:
|
|
24
|
+
print('Warning: {0} gaps in timestamp data found. '
|
|
25
|
+
'Time scale will not be uniform!'
|
|
26
|
+
.format(num_gaps))
|
|
27
|
+
|
|
28
|
+
# Scale time steps (units = seconds).
|
|
29
|
+
data['t_amplifier'] = data['t_amplifier'] / header['sample_rate']
|
|
30
|
+
data['t_aux_input'] = data['t_amplifier'][range(
|
|
31
|
+
0, len(data['t_amplifier']), 4)]
|
|
32
|
+
data['t_supply_voltage'] = data['t_amplifier'][range(
|
|
33
|
+
0, len(data['t_amplifier']), header['num_samples_per_data_block'])]
|
|
34
|
+
data['t_board_adc'] = data['t_amplifier']
|
|
35
|
+
data['t_dig'] = data['t_amplifier']
|
|
36
|
+
data['t_temp_sensor'] = data['t_supply_voltage']
|
|
37
|
+
|
|
38
|
+
def scale_analog_data(header, data):
|
|
39
|
+
"""Scales all analog data signal types (amplifier data, aux input data,
|
|
40
|
+
supply voltage data, board ADC data, and temp sensor data) to suitable
|
|
41
|
+
units (microVolts, Volts, deg C).
|
|
42
|
+
"""
|
|
43
|
+
# Scale amplifier data (units = microVolts).
|
|
44
|
+
data['amplifier_data'] = np.multiply(
|
|
45
|
+
0.195, (data['amplifier_data'].astype(np.int32) - 32768))
|
|
46
|
+
|
|
47
|
+
# Scale aux input data (units = Volts).
|
|
48
|
+
data['aux_input_data'] = np.multiply(
|
|
49
|
+
37.4e-6, data['aux_input_data'])
|
|
50
|
+
|
|
51
|
+
# Scale supply voltage data (units = Volts).
|
|
52
|
+
data['supply_voltage_data'] = np.multiply(
|
|
53
|
+
74.8e-6, data['supply_voltage_data'])
|
|
54
|
+
|
|
55
|
+
# Scale board ADC data (units = Volts).
|
|
56
|
+
if header['eval_board_mode'] == 1:
|
|
57
|
+
data['board_adc_data'] = np.multiply(
|
|
58
|
+
152.59e-6, (data['board_adc_data'].astype(np.int32) - 32768))
|
|
59
|
+
elif header['eval_board_mode'] == 13:
|
|
60
|
+
data['board_adc_data'] = np.multiply(
|
|
61
|
+
312.5e-6, (data['board_adc_data'].astype(np.int32) - 32768))
|
|
62
|
+
else:
|
|
63
|
+
data['board_adc_data'] = np.multiply(
|
|
64
|
+
50.354e-6, data['board_adc_data'])
|
|
65
|
+
|
|
66
|
+
# Scale temp sensor data (units = deg C).
|
|
67
|
+
data['temp_sensor_data'] = np.multiply(
|
|
68
|
+
0.01, data['temp_sensor_data'])
|
|
69
|
+
|
|
70
|
+
def extract_digital_data(header, data):
|
|
71
|
+
"""Extracts digital data from raw (a single 16-bit vector where each bit
|
|
72
|
+
represents a separate digital input channel) to a more user-friendly 16-row
|
|
73
|
+
list where each row represents a separate digital input channel. Applies to
|
|
74
|
+
digital input and digital output data.
|
|
75
|
+
"""
|
|
76
|
+
for i in range(header['num_board_dig_in_channels']):
|
|
77
|
+
data['board_dig_in_data'][i, :] = np.not_equal(
|
|
78
|
+
np.bitwise_and(
|
|
79
|
+
data['board_dig_in_raw'],
|
|
80
|
+
(1 << header['board_dig_in_channels'][i]['native_order'])
|
|
81
|
+
),
|
|
82
|
+
0)
|
|
83
|
+
|
|
84
|
+
for i in range(header['num_board_dig_out_channels']):
|
|
85
|
+
data['board_dig_out_data'][i, :] = np.not_equal(
|
|
86
|
+
np.bitwise_and(
|
|
87
|
+
data['board_dig_out_raw'],
|
|
88
|
+
(1 << header['board_dig_out_channels'][i]['native_order'])
|
|
89
|
+
),
|
|
90
|
+
0)
|
|
91
|
+
|
|
92
|
+
def apply_notch_filter(header, data, verbose=True):
|
|
93
|
+
"""Checks header to determine if notch filter should be applied, and if so,
|
|
94
|
+
apply notch filter to all signals in data['amplifier_data'].
|
|
95
|
+
"""
|
|
96
|
+
# If data was not recorded with notch filter turned on, return without
|
|
97
|
+
# applying notch filter. Similarly, if data was recorded from Intan RHX
|
|
98
|
+
# software version 3.0 or later, any active notch filter was already
|
|
99
|
+
# applied to the saved data, so it should not be re-applied.
|
|
100
|
+
if (header['notch_filter_frequency'] == 0
|
|
101
|
+
or header['version']['major'] >= 3):
|
|
102
|
+
return
|
|
103
|
+
|
|
104
|
+
# Apply notch filter individually to each channel in order
|
|
105
|
+
print('Applying notch filter...')
|
|
106
|
+
print_step = 10
|
|
107
|
+
percent_done = print_step
|
|
108
|
+
for i in range(header['num_amplifier_channels']):
|
|
109
|
+
data['amplifier_data'][i, :] = notch_filter(
|
|
110
|
+
data['amplifier_data'][i, :],
|
|
111
|
+
header['sample_rate'],
|
|
112
|
+
header['notch_filter_frequency'],
|
|
113
|
+
10)
|
|
114
|
+
|
|
115
|
+
if verbose:
|
|
116
|
+
percent_done = print_progress(i+1, header['num_amplifier_channels'],
|
|
117
|
+
print_step, percent_done)
|
|
118
|
+
|
|
119
|
+
def notch_filter(signal_in, f_sample, f_notch, bandwidth):
|
|
120
|
+
"""Implements a notch filter (e.g., for 50 or 60 Hz) on vector 'signal_in'.
|
|
121
|
+
|
|
122
|
+
f_sample = sample rate of data (input Hz or Samples/sec)
|
|
123
|
+
f_notch = filter notch frequency (input Hz)
|
|
124
|
+
bandwidth = notch 3-dB bandwidth (input Hz). A bandwidth of 10 Hz is
|
|
125
|
+
recommended for 50 or 60 Hz notch filters; narrower bandwidths lead to
|
|
126
|
+
poor time-domain properties with an extended ringing response to
|
|
127
|
+
transient disturbances.
|
|
128
|
+
|
|
129
|
+
Example: If neural data was sampled at 30 kSamples/sec
|
|
130
|
+
and you wish to implement a 60 Hz notch filter:
|
|
131
|
+
|
|
132
|
+
out = notch_filter(signal_in, 30000, 60, 10);
|
|
133
|
+
"""
|
|
134
|
+
# Calculate parameters used to implement IIR filter
|
|
135
|
+
t_step = 1.0/f_sample
|
|
136
|
+
f_c = f_notch*t_step
|
|
137
|
+
signal_length = len(signal_in)
|
|
138
|
+
iir_parameters = calculate_iir_parameters(bandwidth, t_step, f_c)
|
|
139
|
+
|
|
140
|
+
# Create empty signal_out NumPy array
|
|
141
|
+
signal_out = np.zeros(signal_length)
|
|
142
|
+
|
|
143
|
+
# Set the first 2 samples of signal_out to signal_in.
|
|
144
|
+
# If filtering a continuous data stream, change signal_out[0:1] to the
|
|
145
|
+
# previous final two values of signal_out
|
|
146
|
+
signal_out[0] = signal_in[0]
|
|
147
|
+
signal_out[1] = signal_in[1]
|
|
148
|
+
|
|
149
|
+
# Run filter.
|
|
150
|
+
for i in range(2, signal_length):
|
|
151
|
+
signal_out[i] = calculate_iir(i, signal_in, signal_out, iir_parameters)
|
|
152
|
+
|
|
153
|
+
return signal_out
|
|
154
|
+
|
|
155
|
+
def calculate_iir_parameters(bandwidth, t_step, f_c):
|
|
156
|
+
"""Calculates parameters d, b, a0, a1, a2, a, b0, b1, and b2 used for
|
|
157
|
+
IIR filter and return them in a dict.
|
|
158
|
+
"""
|
|
159
|
+
parameters = {}
|
|
160
|
+
d = math.exp(-2.0*math.pi*(bandwidth/2.0)*t_step)
|
|
161
|
+
b = (1.0 + d*d) * math.cos(2.0*math.pi*f_c)
|
|
162
|
+
a0 = 1.0
|
|
163
|
+
a1 = -b
|
|
164
|
+
a2 = d*d
|
|
165
|
+
a = (1.0 + d*d)/2.0
|
|
166
|
+
b0 = 1.0
|
|
167
|
+
b1 = -2.0 * math.cos(2.0*math.pi*f_c)
|
|
168
|
+
b2 = 1.0
|
|
169
|
+
|
|
170
|
+
parameters['d'] = d
|
|
171
|
+
parameters['b'] = b
|
|
172
|
+
parameters['a0'] = a0
|
|
173
|
+
parameters['a1'] = a1
|
|
174
|
+
parameters['a2'] = a2
|
|
175
|
+
parameters['a'] = a
|
|
176
|
+
parameters['b0'] = b0
|
|
177
|
+
parameters['b1'] = b1
|
|
178
|
+
parameters['b2'] = b2
|
|
179
|
+
return parameters
|
|
180
|
+
|
|
181
|
+
def calculate_iir(i, signal_in, signal_out, iir_parameters):
|
|
182
|
+
"""Calculates a single sample of IIR filter passing signal_in through
|
|
183
|
+
iir_parameters, resulting in signal_out.
|
|
184
|
+
"""
|
|
185
|
+
sample = ((
|
|
186
|
+
iir_parameters['a'] * iir_parameters['b2'] * signal_in[i - 2]
|
|
187
|
+
+ iir_parameters['a'] * iir_parameters['b1'] * signal_in[i - 1]
|
|
188
|
+
+ iir_parameters['a'] * iir_parameters['b0'] * signal_in[i]
|
|
189
|
+
- iir_parameters['a2'] * signal_out[i - 2]
|
|
190
|
+
- iir_parameters['a1'] * signal_out[i - 1])
|
|
191
|
+
/ iir_parameters['a0'])
|
|
192
|
+
|
|
193
|
+
return sample
|
intan/io/_exceptions.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# Auto-generated from _loaders.py
|
|
2
|
+
|
|
3
|
+
class UnrecognizedFileError(Exception):
|
|
4
|
+
"""Exception returned when reading a file as an RHD header yields an
|
|
5
|
+
invalid magic number (indicating this is not an RHD header file).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class UnknownChannelTypeError(Exception):
|
|
10
|
+
"""Exception returned when a channel field in RHD header does not have
|
|
11
|
+
a recognized signal_type value. Accepted values are:
|
|
12
|
+
0: amplifier channel
|
|
13
|
+
1: aux input channel
|
|
14
|
+
2: supply voltage channel
|
|
15
|
+
3: board adc channel
|
|
16
|
+
4: dig in channel
|
|
17
|
+
5: dig out channel
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class FileSizeError(Exception):
|
|
22
|
+
"""Exception returned when file reading fails due to the file size
|
|
23
|
+
being invalid or the calculated file size differing from the actual
|
|
24
|
+
file size.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class QStringError(Exception):
|
|
29
|
+
"""Exception returned when reading a QString fails because it is too long.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ChannelNotFoundError(Exception):
|
|
34
|
+
"""Exception returned when plotting fails due to the specified channel
|
|
35
|
+
not being found.
|
|
36
|
+
"""
|
|
37
|
+
|
intan/io/_file_utils.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
import os
|
|
3
|
+
import platform
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from intan.io._exceptions import FileSizeError
|
|
6
|
+
|
|
7
|
+
def adjust_path(path):
|
|
8
|
+
system = platform.system()
|
|
9
|
+
|
|
10
|
+
# Check if the system is running under WSL
|
|
11
|
+
if "microsoft" in platform.uname().release.lower():
|
|
12
|
+
system = "WSL"
|
|
13
|
+
|
|
14
|
+
# Modify the path based on the system type
|
|
15
|
+
if system == "Windows":
|
|
16
|
+
# If running on native Windows, return the path as is
|
|
17
|
+
return path
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
elif system == "WSL":
|
|
21
|
+
# If running on WSL, convert "C:/" to "/mnt/c/"
|
|
22
|
+
if len(path) > 1 and path[1] == ":":
|
|
23
|
+
drive_letter = path[0].lower()
|
|
24
|
+
# Properly replace backslashes without using them in f-string
|
|
25
|
+
linux_path = path[2:].replace("\\", "/")
|
|
26
|
+
return f"/mnt/{drive_letter}{linux_path}"
|
|
27
|
+
else:
|
|
28
|
+
return path
|
|
29
|
+
|
|
30
|
+
elif system == "Linux":
|
|
31
|
+
# If running on native Linux, assume Linux paths are provided correctly
|
|
32
|
+
return path
|
|
33
|
+
|
|
34
|
+
else:
|
|
35
|
+
raise ValueError(f"Unsupported system: {system}")
|
|
36
|
+
|
|
37
|
+
def check_file_present(file, metrics_file, verbose=False):
|
|
38
|
+
"""
|
|
39
|
+
Checks if the file is present in the metrics file.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
file: The file to check.
|
|
43
|
+
metrics_file: The metrics file to search.
|
|
44
|
+
verbose: (Optional) Boolean indicating if the function should print messages.
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
filename: The name of the file.
|
|
48
|
+
is_present: Boolean indicating if the file is present in the metrics file.
|
|
49
|
+
"""
|
|
50
|
+
filename = Path(file).name
|
|
51
|
+
if filename not in metrics_file['File Name'].tolist():
|
|
52
|
+
if verbose:
|
|
53
|
+
print(f"File {filename} not found in metrics file")
|
|
54
|
+
return filename, False
|
|
55
|
+
|
|
56
|
+
return filename, True
|
|
57
|
+
|
|
58
|
+
def check_end_of_file(filesize, fid):
|
|
59
|
+
"""Checks that the end of the file was reached at the expected position.
|
|
60
|
+
If not, raise FileSizeError.
|
|
61
|
+
"""
|
|
62
|
+
bytes_remaining = filesize - fid.tell()
|
|
63
|
+
if bytes_remaining != 0:
|
|
64
|
+
raise FileSizeError('Error: End of file not reached.')
|
|
65
|
+
|
|
66
|
+
def get_rhd_file_paths(directory, verbose=False):
|
|
67
|
+
"""
|
|
68
|
+
Returns a list of full paths for files ending with .rhd in the given directory and its subdirectories.
|
|
69
|
+
|
|
70
|
+
Args:
|
|
71
|
+
directory: The directory to search for .rhd files.
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
rhd_files: List of full paths to .rhd files.
|
|
75
|
+
"""
|
|
76
|
+
if verbose:
|
|
77
|
+
print("Searching in directory:", directory)
|
|
78
|
+
|
|
79
|
+
# Convert the directory to an absolute path and a Path object for compatibility
|
|
80
|
+
directory = Path(os.path.abspath(directory))
|
|
81
|
+
|
|
82
|
+
# Check if the directory exists
|
|
83
|
+
if not directory.exists() or not directory.is_dir():
|
|
84
|
+
print(f"Directory '{directory}' not found or is not a valid directory.")
|
|
85
|
+
return []
|
|
86
|
+
|
|
87
|
+
# Recursively find all .rhd files
|
|
88
|
+
file_paths = list(directory.rglob('*.rhd'))
|
|
89
|
+
if verbose:
|
|
90
|
+
print(f"Found {len(file_paths)} .rhd files")
|
|
91
|
+
return file_paths
|
|
92
|
+
|
|
93
|
+
def print_progress(i, target, print_step, percent_done, bar_length=40):
|
|
94
|
+
"""Prints an updating progress bar in the terminal while respecting print_step and percent_done."""
|
|
95
|
+
fraction_done = 100 * (1.0 * i / target)
|
|
96
|
+
|
|
97
|
+
# Only update if we've crossed a new step
|
|
98
|
+
if fraction_done >= percent_done:
|
|
99
|
+
fraction_bar = i / target
|
|
100
|
+
arrow = '=' * int(fraction_bar * bar_length - 1) + '>' if fraction_bar > 0 else ''
|
|
101
|
+
padding = ' ' * (bar_length - len(arrow))
|
|
102
|
+
|
|
103
|
+
ending = '\n' if i == target - 1 else '\r'
|
|
104
|
+
|
|
105
|
+
print(f'Progress: [{arrow}{padding}] {int(fraction_bar * 100)}%', end=ending)
|
|
106
|
+
sys.stdout.flush()
|
|
107
|
+
|
|
108
|
+
percent_done += print_step
|
|
109
|
+
|
|
110
|
+
return percent_done
|