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 ADDED
@@ -0,0 +1,42 @@
1
+ """
2
+ python-intan: A Python package for reading and visualizing data from Intan Technologies' RHD2000 series of integrated circuits.
3
+
4
+ Subpackages
5
+ -----------
6
+ io --- Reading and writing Intan data files
7
+ plotting --- Plotting and visualization
8
+ control --- UART and TCP communication helpers
9
+ processing --- Signal processing functions
10
+ """
11
+
12
+ import importlib as _importlib
13
+
14
+ submodules = [
15
+ 'io',
16
+ 'plotting',
17
+ 'control',
18
+ 'processing',
19
+ ]
20
+
21
+ __all__ = submodules + [
22
+ 'LowLevelCallable',
23
+ 'test',
24
+ 'show_config',
25
+ '__version__',
26
+ ]
27
+
28
+
29
+ def __dir__():
30
+ return __all__
31
+
32
+
33
+ def __getattr__(name):
34
+ if name in submodules:
35
+ return _importlib.import_module(f'scipy.{name}')
36
+ else:
37
+ try:
38
+ return globals()[name]
39
+ except KeyError:
40
+ raise AttributeError(
41
+ f"Module 'scipy' has no attribute '{name}'"
42
+ )
@@ -0,0 +1 @@
1
+ from ._messaging import PicoMessager, TCPClient, RingBuffer
@@ -0,0 +1,171 @@
1
+ import time
2
+ import socket
3
+ import serial
4
+ import numpy as np
5
+ from statistics import mode, StatisticsError
6
+ import collections
7
+
8
+
9
+ class PicoMessager:
10
+ """Class for managing serial communication with a Raspberry Pi Pico."""
11
+
12
+ def __init__(self, port='COM13', baudrate=9600, buffer_size=1, verbose=False):
13
+ """Initializes the PicoMessager.
14
+
15
+ Args:
16
+ port (str): The serial port to connect to (e.g., 'COM13').
17
+ baudrate (int): The baud rate for serial communication.
18
+ buffer_size (int): The number of past gestures to keep in the buffer.
19
+ verbose (bool): Whether to print incoming messages automatically.
20
+ """
21
+ self.port = port
22
+ self.baudrate = baudrate
23
+ self.buffer = collections.deque(maxlen=buffer_size)
24
+ self.current_gesture = None # Keep track of the current gesture being sent
25
+ self.verbose = verbose
26
+ self.running = True # To control the connection
27
+
28
+ # Connect to the Pico via serial
29
+ try:
30
+ self.serial_connection = serial.Serial(self.port, self.baudrate, timeout=1)
31
+ print(f"Connected to Pico on {self.port} at {self.baudrate} baud.")
32
+ except serial.SerialException as e:
33
+ print(f"Error connecting to Pico: {e}")
34
+ self.serial_connection = None
35
+
36
+ def dump_output(self, mute=False):
37
+ """Reads all available bytes from the serial connection and prints them.
38
+
39
+ This function reads all incoming messages from the Pico until there are no more bytes left.
40
+ """
41
+ if self.serial_connection and self.serial_connection.is_open:
42
+ try:
43
+ if self.serial_connection.in_waiting > 0:
44
+ incoming_message = self.serial_connection.readline().decode().strip()
45
+ if incoming_message and not mute:
46
+ print(f"Message from Pico: {incoming_message}")
47
+ except serial.SerialException as e:
48
+ print(f"Error reading message: {e}")
49
+
50
+ def update_gesture(self, new_gesture):
51
+ """Updates the gesture buffer and sends the most common gesture if it changes.
52
+
53
+ Args:
54
+ new_gesture (str): The newly detected gesture.
55
+ """
56
+ # Update the gesture buffer
57
+ self.buffer.append(new_gesture)
58
+
59
+ # Find the most common gesture in the buffer
60
+ try:
61
+ most_common_gesture = mode(self.buffer)
62
+ except StatisticsError:
63
+ # If mode cannot be determined, continue without change
64
+ most_common_gesture = None
65
+
66
+ # If the most common gesture changes, update current_gesture and send the new message
67
+ if most_common_gesture and most_common_gesture != self.current_gesture:
68
+ self.current_gesture = most_common_gesture
69
+ self.send_message(self.current_gesture)
70
+
71
+ def send_message(self, message):
72
+ """Sends a message to the Pico over serial.
73
+
74
+ Args:
75
+ message (str): The message to send.
76
+ """
77
+ if self.serial_connection and self.serial_connection.is_open:
78
+ try:
79
+ formatted_message = f"{message};" # Add terminator character to the message
80
+ self.serial_connection.write(formatted_message.encode())
81
+ print(f"Sent message to Pico: {formatted_message}")
82
+ except serial.SerialException as e:
83
+ print(f"Error sending message: {e}")
84
+ else:
85
+ print("Serial connection not available or not open.")
86
+
87
+ def close_connection(self):
88
+ """Closes the serial connection to the Pico and stops the background listener."""
89
+ # Stop the background thread
90
+ self.running = False
91
+
92
+ if self.serial_connection and self.serial_connection.is_open:
93
+ self.serial_connection.close()
94
+ print("Closed connection to Pico.")
95
+
96
+
97
+ class TCPClient:
98
+ """ Class for managing TCP connections to the Intan system."""
99
+ def __init__(self, name, host, port, buffer=1024):
100
+ """Initializes the TCPClient.
101
+
102
+ Args:
103
+ name (str): Name of the client.
104
+ host (str): The IP address of the host to connect to.
105
+ port (int): The port number to connect to.
106
+ buffer (int): The buffer size for receiving data.
107
+ """
108
+ self.name = name
109
+ self.host = host
110
+ self.port = port
111
+ self.buffer = buffer
112
+ self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
113
+ self.s.settimeout(5) # Timeout after 5 seconds if no data received
114
+
115
+ def connect(self):
116
+ """Connects to the host server."""
117
+ self.s.setblocking(True)
118
+ self.s.connect((self.host, self.port))
119
+ self.s.setblocking(False)
120
+
121
+ def send(self, data, wait_for_response=False):
122
+ """Sends data to the host server and optionally waits for a response."""
123
+ # convert data to bytes if it is not already
124
+ if not isinstance(data, bytes):
125
+ data = data.encode()
126
+ self.s.sendall(data)
127
+ time.sleep(0.01)
128
+
129
+ if wait_for_response:
130
+ return self.read()
131
+
132
+ def read(self, bytes=None):
133
+ """ Reads and returns bytes by the buffer size unless specified """
134
+ if bytes is None:
135
+ return self.s.recv(self.buffer)
136
+ else:
137
+ return self.s.recv(bytes)
138
+
139
+ def close(self):
140
+ self.s.close()
141
+
142
+
143
+ class RingBuffer:
144
+ """Fixed-size ring buffer for storing recent data up to max number of samples."""
145
+
146
+ def __init__(self, num_channels, size_max=4000):
147
+ self.max = size_max
148
+ self.samples = collections.deque(maxlen=size_max) # Stores (timestamp, data)
149
+ self.num_channels = num_channels
150
+
151
+ def append(self, t, x):
152
+ """Adds a new sample to the buffer, automatically removing the oldest if full."""
153
+ x = np.array(x, dtype=np.float32).reshape(1, -1) # Ensure it remains multi-channel
154
+ self.samples.append((t, x))
155
+
156
+ def get_samples(self, n=1):
157
+ """Returns the last n samples from the buffer as NumPy arrays."""
158
+ if len(self.samples) < n:
159
+ raise ValueError("Requested more samples than available in the buffer.")
160
+
161
+ recent_samples = list(self.samples)[-n:] # Get last n elements
162
+ timestamps, data = zip(*recent_samples) # Separate timestamps and data
163
+
164
+ # Convert to NumPy arrays and ensure shape is correct
165
+ data_array = np.vstack(data) # Stack samples to shape (n, num_channels)
166
+
167
+ return data_array, np.array(timestamps)
168
+
169
+ def is_full(self):
170
+ """Checks if the buffer is at max capacity."""
171
+ return len(self.samples) == self.max
intan/io/__init__.py ADDED
@@ -0,0 +1,64 @@
1
+ from ._channel_utils import print_all_channel_names, find_channel_in_header, find_channel_in_group, print_names_in_group
2
+ from ._file_utils import adjust_path, check_file_present, get_rhd_file_paths, print_progress
3
+ from ._metadata_utils import plural, get_bytes_per_data_block, calculate_data_size, bytes_per_signal_type, calculate_num_samples, print_record_time_summary
4
+ from ._exceptions import UnrecognizedFileError, UnknownChannelTypeError, FileSizeError, QStringError, ChannelNotFoundError
5
+
6
+ from ._block_parser import (
7
+ get_timestamp_signed,
8
+ read_one_data_block,
9
+ read_timestamps,
10
+ read_analog_signals,
11
+ read_analog_signal_type,
12
+ read_digital_signals,
13
+ read_digital_signal_type,
14
+ read_all_data_blocks,
15
+ initialize_memory,
16
+ advance_indices,
17
+ plural
18
+ )
19
+
20
+ from ._header_parsing import (
21
+ read_header,
22
+ read_version_number,
23
+ set_num_samples_per_data_block,
24
+ read_sample_rate,
25
+ read_freq_settings,
26
+ read_impedance_test_frequencies,
27
+ read_notes,
28
+ read_eval_board_mode,
29
+ read_reference_channel,
30
+ set_sample_rates,
31
+ set_frequency_parameters,
32
+ initialize_channels,
33
+ read_signal_summary,
34
+ add_signal_group_information,
35
+ add_channel_information,
36
+ read_new_channel,
37
+ add_num_channels,
38
+ append_new_channel,
39
+ header_to_result,
40
+ print_header_summary,
41
+ read_qstring
42
+ )
43
+
44
+ from ._data_processing import (
45
+ parse_data,
46
+ scale_timestamps,
47
+ scale_analog_data,
48
+ extract_digital_data,
49
+ apply_notch_filter,
50
+ notch_filter,
51
+ calculate_iir_parameters,
52
+ calculate_iir
53
+ )
54
+ from ._rhd_loader import (
55
+ load_rhd_file,
56
+ read_time_file,
57
+ read_amplifier_file,
58
+ read_auxiliary_file,
59
+ read_adc_file,
60
+ load_dat_file,
61
+ load_per_signal_files,
62
+ load_files_from_path
63
+ )
64
+
@@ -0,0 +1,253 @@
1
+ import numpy as np
2
+ import struct
3
+ from intan.io._file_utils import print_progress
4
+
5
+ def get_timestamp_signed(header):
6
+ """Checks version (major and minor) in 'header' to determine if data
7
+ recorded from this version of Intan software saved timestamps as signed or
8
+ unsigned integer. Returns True if signed, False if unsigned.
9
+ """
10
+ # All Intan software v1.2 and later saves timestamps as signed
11
+ if header['version']['major'] > 1:
12
+ return True
13
+
14
+ if header['version']['major'] == 1 and header['version']['minor'] >= 2:
15
+ return True
16
+
17
+ # Intan software before v1.2 saves timestamps as unsigned
18
+ return False
19
+
20
+ def read_one_data_block(data, header, indices, fid):
21
+ """Reads one 60 or 128 sample data block from fid into data,
22
+ at the location indicated by indices."""
23
+ samples_per_block = header['num_samples_per_data_block']
24
+
25
+ # In version 1.2, we moved from saving timestamps as unsigned
26
+ # integers to signed integers to accommodate negative (adjusted)
27
+ # timestamps for pretrigger data
28
+ read_timestamps(fid,
29
+ data,
30
+ indices,
31
+ samples_per_block,
32
+ get_timestamp_signed(header))
33
+
34
+ read_analog_signals(fid,
35
+ data,
36
+ indices,
37
+ samples_per_block,
38
+ header)
39
+
40
+ read_digital_signals(fid,
41
+ data,
42
+ indices,
43
+ samples_per_block,
44
+ header)
45
+
46
+ def read_timestamps(fid, data, indices, num_samples, timestamp_signed):
47
+ """Reads timestamps from binary file as a NumPy array, indexing them
48
+ into 'data'.
49
+ """
50
+ start = indices['amplifier']
51
+ end = start + num_samples
52
+ format_sign = 'i' if timestamp_signed else 'I'
53
+ format_expression = '<' + format_sign * num_samples
54
+ read_length = 4 * num_samples
55
+ data['t_amplifier'][start:end] = np.array(struct.unpack(
56
+ format_expression, fid.read(read_length)))
57
+
58
+ def read_analog_signals(fid, data, indices, samples_per_block, header):
59
+ """Reads all analog signal types present in RHD files: amplifier_data,
60
+ aux_input_data, supply_voltage_data, temp_sensor_data, and board_adc_data,
61
+ into 'data' dict.
62
+ """
63
+
64
+ read_analog_signal_type(fid,
65
+ data['amplifier_data'],
66
+ indices['amplifier'],
67
+ samples_per_block,
68
+ header['num_amplifier_channels'])
69
+
70
+ read_analog_signal_type(fid,
71
+ data['aux_input_data'],
72
+ indices['aux_input'],
73
+ int(samples_per_block / 4),
74
+ header['num_aux_input_channels'])
75
+
76
+ read_analog_signal_type(fid,
77
+ data['supply_voltage_data'],
78
+ indices['supply_voltage'],
79
+ 1,
80
+ header['num_supply_voltage_channels'])
81
+
82
+ read_analog_signal_type(fid,
83
+ data['temp_sensor_data'],
84
+ indices['supply_voltage'],
85
+ 1,
86
+ header['num_temp_sensor_channels'])
87
+
88
+ read_analog_signal_type(fid,
89
+ data['board_adc_data'],
90
+ indices['board_adc'],
91
+ samples_per_block,
92
+ header['num_board_adc_channels'])
93
+
94
+ def read_digital_signals(fid, data, indices, samples_per_block, header):
95
+ """Reads all digital signal types present in RHD files: board_dig_in_raw
96
+ and board_dig_out_raw, into 'data' dict.
97
+ """
98
+
99
+ read_digital_signal_type(fid,
100
+ data['board_dig_in_raw'],
101
+ indices['board_dig_in'],
102
+ samples_per_block,
103
+ header['num_board_dig_in_channels'])
104
+
105
+ read_digital_signal_type(fid,
106
+ data['board_dig_out_raw'],
107
+ indices['board_dig_out'],
108
+ samples_per_block,
109
+ header['num_board_dig_out_channels'])
110
+
111
+ def read_analog_signal_type(fid, dest, start, num_samples, num_channels):
112
+ """Reads data from binary file as a NumPy array, indexing them into
113
+ 'dest', which should be an analog signal type within 'data', for example
114
+ data['amplifier_data'] or data['aux_input_data']. Each sample is assumed
115
+ to be of dtype 'uint16'.
116
+ """
117
+
118
+ if num_channels < 1:
119
+ return
120
+ end = start + num_samples
121
+ tmp = np.fromfile(fid, dtype='uint16', count=num_samples*num_channels)
122
+ dest[range(num_channels), start:end] = (
123
+ tmp.reshape(num_channels, num_samples))
124
+
125
+ def read_digital_signal_type(fid, dest, start, num_samples, num_channels):
126
+ """Reads data from binary file as a NumPy array, indexing them into
127
+ 'dest', which should be a digital signal type within 'data', either
128
+ data['board_dig_in_raw'] or data['board_dig_out_raw'].
129
+ """
130
+
131
+ if num_channels < 1:
132
+ return
133
+ end = start + num_samples
134
+ dest[start:end] = np.array(struct.unpack(
135
+ '<' + 'H' * num_samples, fid.read(2 * num_samples)))
136
+
137
+ def read_all_data_blocks(header, num_samples, num_blocks, fid, verbose=True):
138
+ """Reads all data blocks present in file, allocating memory for and
139
+ returning 'data' dict containing all data.
140
+ """
141
+ data, indices = initialize_memory(header, num_samples)
142
+ print("Reading data from file...")
143
+ print_step = 10
144
+ percent_done = print_step
145
+ for i in range(num_blocks):
146
+ read_one_data_block(data, header, indices, fid)
147
+ advance_indices(indices, header['num_samples_per_data_block'])
148
+ if verbose:
149
+ percent_done = print_progress(i+1, num_blocks, print_step, percent_done)
150
+ return data
151
+
152
+ def initialize_memory(header, num_samples):
153
+ """Pre-allocates NumPy arrays for each signal type that will be filled
154
+ during this read, and initializes unique indices for data access to each
155
+ signal type.
156
+ """
157
+ print('\nAllocating memory for data...')
158
+ data = {}
159
+
160
+ # Create zero array for amplifier timestamps.
161
+ t_dtype = np.int_ if get_timestamp_signed(header) else np.uint
162
+ data['t_amplifier'] = np.zeros(num_samples['amplifier'], t_dtype)
163
+
164
+ # Create zero array for amplifier data.
165
+ data['amplifier_data'] = np.zeros(
166
+ [header['num_amplifier_channels'], num_samples['amplifier']],
167
+ dtype=np.uint)
168
+
169
+ # Create zero array for aux input data.
170
+ data['aux_input_data'] = np.zeros(
171
+ [header['num_aux_input_channels'], num_samples['aux_input']],
172
+ dtype=np.uint)
173
+
174
+ # Create zero array for supply voltage data.
175
+ data['supply_voltage_data'] = np.zeros(
176
+ [header['num_supply_voltage_channels'], num_samples['supply_voltage']],
177
+ dtype=np.uint)
178
+
179
+ # Create zero array for temp sensor data.
180
+ data['temp_sensor_data'] = np.zeros(
181
+ [header['num_temp_sensor_channels'], num_samples['supply_voltage']],
182
+ dtype=np.uint)
183
+
184
+ # Create zero array for board ADC data.
185
+ data['board_adc_data'] = np.zeros(
186
+ [header['num_board_adc_channels'], num_samples['board_adc']],
187
+ dtype=np.uint)
188
+
189
+ # By default, this script interprets digital events (digital inputs
190
+ # and outputs) as booleans. if unsigned int values are preferred
191
+ # (0 for False, 1 for True), replace the 'dtype=np.bool_' argument
192
+ # with 'dtype=np.uint' as shown.
193
+ # The commented lines below illustrate this for digital input data;
194
+ # the same can be done for digital out.
195
+
196
+ # data['board_dig_in_data'] = np.zeros(
197
+ # [header['num_board_dig_in_channels'], num_samples['board_dig_in']],
198
+ # dtype=np.uint)
199
+ # Create 16-row zero array for digital in data, and 1-row zero array for
200
+ # raw digital in data (each bit of 16-bit entry represents a different
201
+ # digital input.)
202
+ data['board_dig_in_data'] = np.zeros(
203
+ [header['num_board_dig_in_channels'], num_samples['board_dig_in']],
204
+ dtype=np.bool_)
205
+ data['board_dig_in_raw'] = np.zeros(
206
+ num_samples['board_dig_in'],
207
+ dtype=np.uint)
208
+
209
+ # Create 16-row zero array for digital out data, and 1-row zero array for
210
+ # raw digital out data (each bit of 16-bit entry represents a different
211
+ # digital output.)
212
+ data['board_dig_out_data'] = np.zeros(
213
+ [header['num_board_dig_out_channels'], num_samples['board_dig_out']],
214
+ dtype=np.bool_)
215
+ data['board_dig_out_raw'] = np.zeros(
216
+ num_samples['board_dig_out'],
217
+ dtype=np.uint)
218
+
219
+ # Create dict containing each signal type's indices, and set all to zero.
220
+ indices = {}
221
+ indices['amplifier'] = 0
222
+ indices['aux_input'] = 0
223
+ indices['supply_voltage'] = 0
224
+ indices['board_adc'] = 0
225
+ indices['board_dig_in'] = 0
226
+ indices['board_dig_out'] = 0
227
+
228
+ return data, indices
229
+
230
+ def advance_indices(indices, samples_per_block):
231
+ """Advances indices used for data access by suitable values per data block.
232
+ """
233
+ # Signal types sampled at the sample rate:
234
+ # Index should be incremented by samples_per_block every data block.
235
+ indices['amplifier'] += samples_per_block
236
+ indices['board_adc'] += samples_per_block
237
+ indices['board_dig_in'] += samples_per_block
238
+ indices['board_dig_out'] += samples_per_block
239
+
240
+ # Signal types sampled at 1/4 the sample rate:
241
+ # Index should be incremented by samples_per_block / 4 every data block.
242
+ indices['aux_input'] += int(samples_per_block / 4)
243
+
244
+ # Signal types sampled once per data block:
245
+ # Index should be incremented by 1 every data block.
246
+ indices['supply_voltage'] += 1
247
+
248
+ def plural(number_of_items):
249
+ """Utility function to pluralize words based on the number of items.
250
+ """
251
+ if number_of_items == 1:
252
+ return ''
253
+ return 's'
@@ -0,0 +1,86 @@
1
+
2
+ def print_all_channel_names(result):
3
+ """Searches through all present signal types in 'result' dict, and prints
4
+ the names of these channels. Useful, for example, to determine names of
5
+ channels that can be plotted.
6
+ """
7
+ if 'amplifier_channels' in result:
8
+ print_names_in_group(result['amplifier_channels'])
9
+
10
+ if 'aux_input_channels' in result:
11
+ print_names_in_group(result['aux_input_channels'])
12
+
13
+ if 'supply_voltage_channels' in result:
14
+ print_names_in_group(result['supply_voltage_channels'])
15
+
16
+ if 'board_adc_channels' in result:
17
+ print_names_in_group(result['board_adc_channels'])
18
+
19
+ if 'board_dig_in_channels' in result:
20
+ print_names_in_group(result['board_dig_in_channels'])
21
+
22
+ if 'board_dig_out_channels' in result:
23
+ print_names_in_group(result['board_dig_out_channels'])
24
+
25
+ def print_names_in_group(signal_group):
26
+ """Searches through all channels in this group and print them.
27
+ """
28
+ for this_channel in signal_group:
29
+ print(this_channel['custom_channel_name'])
30
+
31
+ def find_channel_in_group(channel_name, signal_group):
32
+ """Finds a channel with this name in this group, returning whether or not
33
+ it's present and, if so, the position of this channel in signal_group.
34
+ """
35
+ for count, this_channel in enumerate(signal_group):
36
+ if this_channel['custom_channel_name'] == channel_name:
37
+ return True, count
38
+ return False, 0
39
+
40
+ def find_channel_in_header(channel_name, header):
41
+ """Looks through all present signal groups in header, searching for
42
+ 'channel_name'. If found, return the signal group and the index of that
43
+ channel within the group.
44
+ """
45
+ signal_group_name = ''
46
+ if 'amplifier_channels' in header:
47
+ channel_found, channel_index = find_channel_in_group(
48
+ channel_name, header['amplifier_channels'])
49
+ if channel_found:
50
+ signal_group_name = 'amplifier_channels'
51
+
52
+ if not channel_found and 'aux_input_channels' in header:
53
+ channel_found, channel_index = find_channel_in_group(
54
+ channel_name, header['aux_input_channels'])
55
+ if channel_found:
56
+ signal_group_name = 'aux_input_channels'
57
+
58
+ if not channel_found and 'supply_voltage_channels' in header:
59
+ channel_found, channel_index = find_channel_in_group(
60
+ channel_name, header['supply_voltage_channels'])
61
+ if channel_found:
62
+ signal_group_name = 'supply_voltage_channels'
63
+
64
+ if not channel_found and 'board_adc_channels' in header:
65
+ channel_found, channel_index = find_channel_in_group(
66
+ channel_name, header['board_adc_channels'])
67
+ if channel_found:
68
+ signal_group_name = 'board_adc_channels'
69
+
70
+ if not channel_found and 'board_dig_in_channels' in header:
71
+ channel_found, channel_index = find_channel_in_group(
72
+ channel_name, header['board_dig_in_channels'])
73
+ if channel_found:
74
+ signal_group_name = 'board_dig_in_channels'
75
+
76
+ if not channel_found and 'board_dig_out_channels' in header:
77
+ channel_found, channel_index = find_channel_in_group(
78
+ channel_name, header['board_dig_out_channels'])
79
+ if channel_found:
80
+ signal_group_name = 'board_dig_out_channels'
81
+
82
+ if channel_found:
83
+ return True, signal_group_name, channel_index
84
+
85
+ return False, '', 0
86
+