python-intan 0.0.2__tar.gz
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.
- python_intan-0.0.2/LICENSE +21 -0
- python_intan-0.0.2/PKG-INFO +185 -0
- python_intan-0.0.2/README.md +166 -0
- python_intan-0.0.2/intan/__init__.py +42 -0
- python_intan-0.0.2/intan/control/__init__.py +1 -0
- python_intan-0.0.2/intan/control/_messaging.py +171 -0
- python_intan-0.0.2/intan/io/__init__.py +64 -0
- python_intan-0.0.2/intan/io/_block_parser.py +253 -0
- python_intan-0.0.2/intan/io/_channel_utils.py +86 -0
- python_intan-0.0.2/intan/io/_data_processing.py +193 -0
- python_intan-0.0.2/intan/io/_exceptions.py +37 -0
- python_intan-0.0.2/intan/io/_file_utils.py +110 -0
- python_intan-0.0.2/intan/io/_header_parsing.py +383 -0
- python_intan-0.0.2/intan/io/_metadata_utils.py +150 -0
- python_intan-0.0.2/intan/io/_rhd_loader.py +199 -0
- python_intan-0.0.2/intan/plotting/__init__.py +2 -0
- python_intan-0.0.2/intan/plotting/_emg_plots.py +245 -0
- python_intan-0.0.2/intan/plotting/_waterfall.py +132 -0
- python_intan-0.0.2/intan/processing/__init__.py +20 -0
- python_intan-0.0.2/intan/processing/_filters.py +569 -0
- python_intan-0.0.2/intan/processing/_metrics_utils.py +84 -0
- python_intan-0.0.2/pyproject.toml +24 -0
- python_intan-0.0.2/python_intan.egg-info/PKG-INFO +185 -0
- python_intan-0.0.2/python_intan.egg-info/SOURCES.txt +30 -0
- python_intan-0.0.2/python_intan.egg-info/dependency_links.txt +1 -0
- python_intan-0.0.2/python_intan.egg-info/requires.txt +6 -0
- python_intan-0.0.2/python_intan.egg-info/top_level.txt +1 -0
- python_intan-0.0.2/setup.cfg +4 -0
- python_intan-0.0.2/tests/test_RHD2164_SPI.py +83 -0
- python_intan-0.0.2/tests/test_denoise.py +124 -0
- python_intan-0.0.2/tests/test_pc_server.py +40 -0
- python_intan-0.0.2/tests/test_pico_server.py +32 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Neuromechatronics Lab
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: python-intan
|
|
3
|
+
Version: 0.0.2
|
|
4
|
+
Summary: Python utilities for working with Intan electrophysiology data
|
|
5
|
+
Author-email: Jonathan Shulgach <jshulgac@andrew.cmu.edu>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Neuro-Mechatronics-Interfaces/python-intan
|
|
8
|
+
Keywords: intan,emg,neurotech,signal processing,biomedical
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: numpy>=1.26.0
|
|
13
|
+
Requires-Dist: scipy==1.14.1
|
|
14
|
+
Requires-Dist: matplotlib
|
|
15
|
+
Requires-Dist: pandas
|
|
16
|
+
Requires-Dist: PySerial
|
|
17
|
+
Requires-Dist: scikit-learn
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# Python Intan
|
|
21
|
+
|
|
22
|
+
[](https://www.python.org/)
|
|
23
|
+
[](https://opensource.org/licenses/MIT)
|
|
24
|
+
[](https://github.com/Neuro-Mechatronics-Interfaces/python-intan/actions)
|
|
25
|
+
[](https://badge.fury.io/py/python-intan)
|
|
26
|
+
|
|
27
|
+
<p align="center">
|
|
28
|
+
<img src="./docs/figs/logo.png">
|
|
29
|
+
</p>
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
## Overview
|
|
33
|
+
|
|
34
|
+
**`python-intan`** is a Python package for working with EMG data acquired from Intan Technologies systems. It provides utilities for:
|
|
35
|
+
|
|
36
|
+
- Reading `.rhd` and `.dat` data files
|
|
37
|
+
- Preprocessing and feature extraction
|
|
38
|
+
- Integration with external hardware for closed-loop applications
|
|
39
|
+
|
|
40
|
+
Whether you're analyzing offline data or streaming real-time EMG from the RHX system, `python-intan` aims to make the workflow seamless and modular.
|
|
41
|
+
|
|
42
|
+
---
|
|
43
|
+
|
|
44
|
+
## Contents
|
|
45
|
+
|
|
46
|
+
- [Installation](#installation)
|
|
47
|
+
- [Getting Started](#getting-started)
|
|
48
|
+
- [Project Structure](#project-structure)
|
|
49
|
+
- [Future Improvements](#future-improvements)
|
|
50
|
+
- [License](#license)
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
## Installation
|
|
55
|
+
|
|
56
|
+
Using `pip`:
|
|
57
|
+
```shell script
|
|
58
|
+
pip install python-intan
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
or clone the repository from GitHub for the latest features:
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
git clone https://github.com/Neuro-Mechatronics-Interfaces/python-intan.git
|
|
65
|
+
cd python-intan
|
|
66
|
+
pip install -e .
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
---
|
|
70
|
+
|
|
71
|
+
## Getting Started
|
|
72
|
+
|
|
73
|
+
We can quickly load EMG signals from an Intan `.rhd` file.
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
import intan
|
|
77
|
+
|
|
78
|
+
result = intan.io.load_rhd_file() # Opens Popup window to select file, or pass filepath
|
|
79
|
+
```
|
|
80
|
+
`.dat` files are also supported
|
|
81
|
+
```python
|
|
82
|
+
dat_folderpath = "path/to/your/dat/files"
|
|
83
|
+
result = intan.io.load_dat_file(dat_folderpath)
|
|
84
|
+
```
|
|
85
|
+
The `result` dictionary contains:
|
|
86
|
+
- `amplifier_data`: Raw EMG data (shape: channels x samples)
|
|
87
|
+
- `amplifier_channels`: Channel metadata (names, gain, etc.)
|
|
88
|
+
- `frequency_parameters`: Sampling rate information for the amplifier, aux, and digital inputs
|
|
89
|
+
- `t_amplifier`: Time vector for the amplifier data
|
|
90
|
+
- `board_adc_data`: ADC data from the board
|
|
91
|
+
|
|
92
|
+
Loading multiple `.rhd` files with the option to concatenate can be done with:
|
|
93
|
+
```python
|
|
94
|
+
result_list = intan.io.load_rhd_files(concatenate=True)
|
|
95
|
+
```
|
|
96
|
+
Some quick filtering to remove DC offset and noise:
|
|
97
|
+
```python
|
|
98
|
+
fs = result['frequency_parameters']['amplifier_sample_rate']
|
|
99
|
+
emg = result['amplifier_data'] # Shape: (channels, samples)
|
|
100
|
+
|
|
101
|
+
notch_emg = intan.processing.notch_filter(emg, fs, f0=60) # 60Hz notch filter
|
|
102
|
+
filt_emg = intan.processing.filter_emg(notch_emg, 'bandpass', fs, lowcut=10, highcut=500) # 10-500Hz bandpass filter
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
We can visualize the raw EMG data using the `plotting` module. Let's use a waterfall plot to look at the raw activity across a subset of channels:
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
t_s = result['t_amplifier']
|
|
110
|
+
chans = range(0, 64) # Selecting channels to plot
|
|
111
|
+
intan.plotting.waterfall(filt_emg, chans, t_s, plot_title='Intan EMG data')
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
If there is a single channel of interest, we can plot it directly by name or index:
|
|
115
|
+
```python
|
|
116
|
+
intan.plotting.plot_channel_by_name('A-005', result) # By name (Be sure the channel name exists)
|
|
117
|
+
intan.plotting.plot_channel_by_index(8, result) # By index
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Some other processing features:
|
|
121
|
+
```python
|
|
122
|
+
# Normalize the EMG data
|
|
123
|
+
norm_emg = intan.processing.normalize(filt_emg, method='zscore') # Z-score normalization
|
|
124
|
+
|
|
125
|
+
# Downsample the EMG data
|
|
126
|
+
downsampled_emg = intan.processing.downsample(filt_emg, factor=2) # Downsample by a factor of 2
|
|
127
|
+
|
|
128
|
+
# Rectify
|
|
129
|
+
rectified_emg = intan.processing.rectify(filt_emg) # Rectify the EMG data
|
|
130
|
+
|
|
131
|
+
# Rolling RMS window
|
|
132
|
+
samples = int(0.1 * fs) # 100ms window
|
|
133
|
+
rms_emg = intan.processing.window_rms(filt_emg, window_size=samples) # 100ms RMS window
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
---
|
|
138
|
+
|
|
139
|
+
## Project Structure
|
|
140
|
+
|
|
141
|
+
```text
|
|
142
|
+
intan/
|
|
143
|
+
├── io/ # Load and parse Intan .rhd or .rhs files
|
|
144
|
+
├── processing/ # Filtering, normalization, and segmentation
|
|
145
|
+
├── control/ # Real-time control scripts for robot arm or other peripherals
|
|
146
|
+
├── plotting/ # Plotting and GUI scripts
|
|
147
|
+
|
|
148
|
+
load_rhd_demo.py # Quick-start script for plotting waveform data
|
|
149
|
+
requirements.txt
|
|
150
|
+
README.md
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
---
|
|
154
|
+
|
|
155
|
+
## Future Improvements
|
|
156
|
+
|
|
157
|
+
- [x] Real-time gesture decoding via TCP from RHX
|
|
158
|
+
- [x] Serial control for wearable robotics (e.g. grippers, arms)
|
|
159
|
+
- [x] CNN feature pipeline support
|
|
160
|
+
- [ ] GUI for real-time signal monitoring
|
|
161
|
+
- [ ] Public datasets with training/testing support
|
|
162
|
+
- [ ] Cross-platform support for macOS/Linux (currently optimized for Windows)
|
|
163
|
+
|
|
164
|
+
---
|
|
165
|
+
|
|
166
|
+
## Citation
|
|
167
|
+
|
|
168
|
+
This package can be cited as follows:
|
|
169
|
+
|
|
170
|
+
```bibtex
|
|
171
|
+
@software{Shulgach_Python_Intan_2025,
|
|
172
|
+
author = {Shulgach, Jonathan, Murphy, Max and Foy, Adrian},
|
|
173
|
+
title = {{Python Intan Package}},
|
|
174
|
+
year = {2025},
|
|
175
|
+
month = {05},
|
|
176
|
+
version = {0.1.0},
|
|
177
|
+
url = {https://github.com/Neuro-Mechatronics-Interfaces/python-intan},
|
|
178
|
+
note = "{\tt jshulgac@andrew.cmu.edu}"
|
|
179
|
+
}
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
## License
|
|
184
|
+
|
|
185
|
+
This project is licensed under the MIT License — see the [LICENSE](LICENSE) file for details.
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
# Python Intan
|
|
2
|
+
|
|
3
|
+
[](https://www.python.org/)
|
|
4
|
+
[](https://opensource.org/licenses/MIT)
|
|
5
|
+
[](https://github.com/Neuro-Mechatronics-Interfaces/python-intan/actions)
|
|
6
|
+
[](https://badge.fury.io/py/python-intan)
|
|
7
|
+
|
|
8
|
+
<p align="center">
|
|
9
|
+
<img src="./docs/figs/logo.png">
|
|
10
|
+
</p>
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
## Overview
|
|
14
|
+
|
|
15
|
+
**`python-intan`** is a Python package for working with EMG data acquired from Intan Technologies systems. It provides utilities for:
|
|
16
|
+
|
|
17
|
+
- Reading `.rhd` and `.dat` data files
|
|
18
|
+
- Preprocessing and feature extraction
|
|
19
|
+
- Integration with external hardware for closed-loop applications
|
|
20
|
+
|
|
21
|
+
Whether you're analyzing offline data or streaming real-time EMG from the RHX system, `python-intan` aims to make the workflow seamless and modular.
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## Contents
|
|
26
|
+
|
|
27
|
+
- [Installation](#installation)
|
|
28
|
+
- [Getting Started](#getting-started)
|
|
29
|
+
- [Project Structure](#project-structure)
|
|
30
|
+
- [Future Improvements](#future-improvements)
|
|
31
|
+
- [License](#license)
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## Installation
|
|
36
|
+
|
|
37
|
+
Using `pip`:
|
|
38
|
+
```shell script
|
|
39
|
+
pip install python-intan
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
or clone the repository from GitHub for the latest features:
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
git clone https://github.com/Neuro-Mechatronics-Interfaces/python-intan.git
|
|
46
|
+
cd python-intan
|
|
47
|
+
pip install -e .
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
---
|
|
51
|
+
|
|
52
|
+
## Getting Started
|
|
53
|
+
|
|
54
|
+
We can quickly load EMG signals from an Intan `.rhd` file.
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
import intan
|
|
58
|
+
|
|
59
|
+
result = intan.io.load_rhd_file() # Opens Popup window to select file, or pass filepath
|
|
60
|
+
```
|
|
61
|
+
`.dat` files are also supported
|
|
62
|
+
```python
|
|
63
|
+
dat_folderpath = "path/to/your/dat/files"
|
|
64
|
+
result = intan.io.load_dat_file(dat_folderpath)
|
|
65
|
+
```
|
|
66
|
+
The `result` dictionary contains:
|
|
67
|
+
- `amplifier_data`: Raw EMG data (shape: channels x samples)
|
|
68
|
+
- `amplifier_channels`: Channel metadata (names, gain, etc.)
|
|
69
|
+
- `frequency_parameters`: Sampling rate information for the amplifier, aux, and digital inputs
|
|
70
|
+
- `t_amplifier`: Time vector for the amplifier data
|
|
71
|
+
- `board_adc_data`: ADC data from the board
|
|
72
|
+
|
|
73
|
+
Loading multiple `.rhd` files with the option to concatenate can be done with:
|
|
74
|
+
```python
|
|
75
|
+
result_list = intan.io.load_rhd_files(concatenate=True)
|
|
76
|
+
```
|
|
77
|
+
Some quick filtering to remove DC offset and noise:
|
|
78
|
+
```python
|
|
79
|
+
fs = result['frequency_parameters']['amplifier_sample_rate']
|
|
80
|
+
emg = result['amplifier_data'] # Shape: (channels, samples)
|
|
81
|
+
|
|
82
|
+
notch_emg = intan.processing.notch_filter(emg, fs, f0=60) # 60Hz notch filter
|
|
83
|
+
filt_emg = intan.processing.filter_emg(notch_emg, 'bandpass', fs, lowcut=10, highcut=500) # 10-500Hz bandpass filter
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
We can visualize the raw EMG data using the `plotting` module. Let's use a waterfall plot to look at the raw activity across a subset of channels:
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
t_s = result['t_amplifier']
|
|
91
|
+
chans = range(0, 64) # Selecting channels to plot
|
|
92
|
+
intan.plotting.waterfall(filt_emg, chans, t_s, plot_title='Intan EMG data')
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
If there is a single channel of interest, we can plot it directly by name or index:
|
|
96
|
+
```python
|
|
97
|
+
intan.plotting.plot_channel_by_name('A-005', result) # By name (Be sure the channel name exists)
|
|
98
|
+
intan.plotting.plot_channel_by_index(8, result) # By index
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Some other processing features:
|
|
102
|
+
```python
|
|
103
|
+
# Normalize the EMG data
|
|
104
|
+
norm_emg = intan.processing.normalize(filt_emg, method='zscore') # Z-score normalization
|
|
105
|
+
|
|
106
|
+
# Downsample the EMG data
|
|
107
|
+
downsampled_emg = intan.processing.downsample(filt_emg, factor=2) # Downsample by a factor of 2
|
|
108
|
+
|
|
109
|
+
# Rectify
|
|
110
|
+
rectified_emg = intan.processing.rectify(filt_emg) # Rectify the EMG data
|
|
111
|
+
|
|
112
|
+
# Rolling RMS window
|
|
113
|
+
samples = int(0.1 * fs) # 100ms window
|
|
114
|
+
rms_emg = intan.processing.window_rms(filt_emg, window_size=samples) # 100ms RMS window
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
---
|
|
119
|
+
|
|
120
|
+
## Project Structure
|
|
121
|
+
|
|
122
|
+
```text
|
|
123
|
+
intan/
|
|
124
|
+
├── io/ # Load and parse Intan .rhd or .rhs files
|
|
125
|
+
├── processing/ # Filtering, normalization, and segmentation
|
|
126
|
+
├── control/ # Real-time control scripts for robot arm or other peripherals
|
|
127
|
+
├── plotting/ # Plotting and GUI scripts
|
|
128
|
+
|
|
129
|
+
load_rhd_demo.py # Quick-start script for plotting waveform data
|
|
130
|
+
requirements.txt
|
|
131
|
+
README.md
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
---
|
|
135
|
+
|
|
136
|
+
## Future Improvements
|
|
137
|
+
|
|
138
|
+
- [x] Real-time gesture decoding via TCP from RHX
|
|
139
|
+
- [x] Serial control for wearable robotics (e.g. grippers, arms)
|
|
140
|
+
- [x] CNN feature pipeline support
|
|
141
|
+
- [ ] GUI for real-time signal monitoring
|
|
142
|
+
- [ ] Public datasets with training/testing support
|
|
143
|
+
- [ ] Cross-platform support for macOS/Linux (currently optimized for Windows)
|
|
144
|
+
|
|
145
|
+
---
|
|
146
|
+
|
|
147
|
+
## Citation
|
|
148
|
+
|
|
149
|
+
This package can be cited as follows:
|
|
150
|
+
|
|
151
|
+
```bibtex
|
|
152
|
+
@software{Shulgach_Python_Intan_2025,
|
|
153
|
+
author = {Shulgach, Jonathan, Murphy, Max and Foy, Adrian},
|
|
154
|
+
title = {{Python Intan Package}},
|
|
155
|
+
year = {2025},
|
|
156
|
+
month = {05},
|
|
157
|
+
version = {0.1.0},
|
|
158
|
+
url = {https://github.com/Neuro-Mechatronics-Interfaces/python-intan},
|
|
159
|
+
note = "{\tt jshulgac@andrew.cmu.edu}"
|
|
160
|
+
}
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
## License
|
|
165
|
+
|
|
166
|
+
This project is licensed under the MIT License — see the [LICENSE](LICENSE) file for details.
|
|
@@ -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
|
|
@@ -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
|
+
|