python-intan 0.2.3__py3-none-any.whl → 0.3.0__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 CHANGED
@@ -9,26 +9,27 @@ This package includes modules for:
9
9
  - Configuration and device control
10
10
  """
11
11
 
12
- __version__ = "0.2.3"
12
+ __version__ = "0.3.0"
13
13
  __author__ = "Jonathan Shulgach"
14
14
  __email__ = "jshulgac@andrew.cmu.edu"
15
15
  __license__ = "MIT"
16
16
  __url__ = "https://github.com/Neuro-Mechatronics-Interfaces/python-intan"
17
17
  __description__ = "Python interface for streaming, parsing, and analyzing Intan Technologies RHX files"
18
18
 
19
- from importlib import import_module as _import_module
19
+ from importlib import import_module as _import_module
20
20
 
21
- submodules = [
22
- 'applications',
23
- 'decomposition',
24
- 'io',
25
- 'ml',
26
- 'plotting',
27
- 'processing',
28
- 'interface',
29
- 'samples',
30
- 'ui',
31
- ]
21
+ submodules = [
22
+ 'applications',
23
+ 'decomposition',
24
+ 'io',
25
+ 'ml',
26
+ 'plotting',
27
+ 'processing',
28
+ 'interface',
29
+ 'samples',
30
+ 'sync',
31
+ 'ui',
32
+ ]
32
33
 
33
34
  __all__ = submodules + [
34
35
  #'LowLevelCallable',
@@ -38,18 +39,18 @@ __all__ = submodules + [
38
39
  ]
39
40
 
40
41
 
41
- def __dir__():
42
- return __all__
43
-
44
-
45
- def __getattr__(name):
46
- """Import public subpackages on first access.
47
-
48
- This keeps ``import intan`` lightweight while supporting the documented
49
- ``intan.io`` and ``intan.processing`` attribute style.
50
- """
51
- if name in submodules:
52
- module = _import_module(f"{__name__}.{name}")
53
- globals()[name] = module
54
- return module
55
- raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
42
+ def __dir__():
43
+ return __all__
44
+
45
+
46
+ def __getattr__(name):
47
+ """Import public subpackages on first access.
48
+
49
+ This keeps ``import intan`` lightweight while supporting the documented
50
+ ``intan.io`` and ``intan.processing`` attribute style.
51
+ """
52
+ if name in submodules:
53
+ module = _import_module(f"{__name__}.{name}")
54
+ globals()[name] = module
55
+ return module
56
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
intan/_optional.py ADDED
@@ -0,0 +1,17 @@
1
+ """Load feature dependencies only when a workflow needs them."""
2
+
3
+ from importlib import import_module
4
+
5
+
6
+ def require_optional(module, extra):
7
+ try:
8
+ return import_module(module)
9
+ except ModuleNotFoundError as exc:
10
+ # Preserve errors from broken installations and missing transitive
11
+ # dependencies instead of misreporting them as an absent extra.
12
+ if exc.name != module.split(".")[0]:
13
+ raise
14
+ raise ImportError(
15
+ f"{module} is required for this feature; "
16
+ f"install it with: python -m pip install 'python-intan[{extra}]'"
17
+ ) from exc
intan/_sample_clock.py ADDED
@@ -0,0 +1,99 @@
1
+ """Track Intan's 32-bit counters and decode packed digital words."""
2
+
3
+ import numpy as np
4
+
5
+ from .sync import DigitalEdge
6
+
7
+
8
+ class SampleClock:
9
+ def __init__(self, signed=True, segment=-1):
10
+ self.segment = segment
11
+ self.previous_raw = None
12
+ self.high = (1 << 31) - 1 if signed else (1 << 32) - 1
13
+ self.low = -(1 << 31) if signed else 0
14
+ self.offset = 0
15
+
16
+ def split(self, counters):
17
+ """Yield (slice, unwrapped counters, missing samples before slice)."""
18
+ if not len(counters):
19
+ return
20
+ counters = counters.astype(np.int64, copy=False)
21
+ previous = self.previous_raw
22
+ if previous is None:
23
+ self.segment += 1
24
+ previous = int(counters[0]) - 1
25
+ self.previous_raw = int(counters[-1])
26
+ deltas = np.diff(counters, prepend=previous)
27
+ # Split at gaps, restarts and wrap, working in int64 to avoid overflow.
28
+ starts = np.flatnonzero(deltas[1:] != 1) + 1
29
+ for start, end in zip(np.r_[0, starts], np.r_[starts, len(counters)]):
30
+ delta = int(deltas[start])
31
+ if start:
32
+ previous = int(counters[start - 1])
33
+ current = int(counters[start])
34
+ # Accept a wrap only close to both ends of the counter range.
35
+ # A jump elsewhere in the reverse direction starts a new segment.
36
+ if previous > self.high - 65536 and self.low <= current < self.low + 65536 and delta < 0:
37
+ self.offset += 1 << 32
38
+ delta += 1 << 32
39
+ elif delta <= 0:
40
+ self.segment += 1
41
+ self.offset = 0
42
+ selection = slice(start, end)
43
+ values = counters[selection]
44
+ yield selection, values + self.offset if self.offset else values, max(0, delta - 1)
45
+
46
+
47
+ class LSLClock:
48
+ """Map each device segment to estimated local LSL times."""
49
+
50
+ def __init__(self, sample_rate):
51
+ self.sample_rate = sample_rate
52
+ self.segment = None
53
+ self.last_time = None
54
+
55
+ def first_time(self, segment, counters, receipt_time, samples_to_end):
56
+ first = int(counters[0])
57
+ if segment != self.segment:
58
+ self.segment = segment
59
+ self.anchor_sample = first
60
+ self.anchor_time = receipt_time - samples_to_end / self.sample_rate
61
+ if self.last_time is not None:
62
+ self.anchor_time = max(self.anchor_time, self.last_time + 1 / self.sample_rate)
63
+ timestamp = self.anchor_time + (first - self.anchor_sample) / self.sample_rate
64
+ self.last_time = timestamp + (len(counters) - 1) / self.sample_rate
65
+ return timestamp
66
+
67
+
68
+ class DigitalInputs:
69
+ def __init__(self, lines, sample_rate, stream_id):
70
+ self.mask = sum(1 << (line - 1) for line in lines)
71
+ self.sample_rate = sample_rate
72
+ self.stream_id = stream_id
73
+ self.previous = None
74
+ self.segment = None
75
+
76
+ def edges(self, words, counters, segment, missing_samples):
77
+ if not len(words):
78
+ return ()
79
+ if self.previous is None or self.segment != segment or missing_samples:
80
+ previous = int(words[0])
81
+ else:
82
+ previous = self.previous
83
+ changed = np.empty_like(words)
84
+ changed[0] = int(words[0]) ^ previous
85
+ np.bitwise_xor(words[1:], words[:-1], out=changed[1:])
86
+ changed &= self.mask
87
+ self.previous = int(words[-1])
88
+ self.segment = segment
89
+ edges = []
90
+ for index in np.flatnonzero(changed):
91
+ bits = int(changed[index])
92
+ while bits:
93
+ bit = bits & -bits
94
+ edges.append(DigitalEdge(
95
+ int(counters[index]), bit.bit_length(), bool(int(words[index]) & bit),
96
+ self.sample_rate, self.stream_id, segment,
97
+ ))
98
+ bits ^= bit
99
+ return tuple(edges)
@@ -36,8 +36,9 @@ except Exception:
36
36
  ttk = None
37
37
 
38
38
  try:
39
- from intan.io import load_rhd_file
39
+ from intan.io import load_npz_file, load_rhd_file
40
40
  except Exception:
41
+ load_npz_file = None
41
42
  load_rhd_file = None
42
43
 
43
44
  try:
@@ -94,27 +95,98 @@ def _downsample_for_plot(y, max_points=2000):
94
95
  return y_ds
95
96
 
96
97
 
98
+ def _load_emg_recording(path):
99
+ """Load an RHD or NPZ recording as channel-major EMG and metadata."""
100
+ extension = os.path.splitext(os.fspath(path))[1].lower()
101
+ if extension == '.rhd':
102
+ if load_rhd_file is None:
103
+ raise RuntimeError("RHD loading is unavailable from intan.io")
104
+ result = load_rhd_file(path, verbose=False)
105
+ elif extension == '.npz':
106
+ if load_npz_file is None:
107
+ raise RuntimeError("NPZ loading is unavailable from intan.io")
108
+ result = load_npz_file(path, verbose=False)
109
+ else:
110
+ raise ValueError(f"Unsupported recording type: {extension or '<none>'}")
111
+
112
+ emg = result.get('amplifier_data')
113
+ if emg is None:
114
+ emg = result.get('data')
115
+ if emg is None:
116
+ raise ValueError("Recording does not contain amplifier/EMG data")
117
+ emg = np.asarray(emg)
118
+ if emg.ndim != 2:
119
+ raise ValueError(f"Recording EMG must be 2-D, received shape {emg.shape}")
120
+
121
+ time_vector = result.get('t_amplifier')
122
+ if time_vector is None:
123
+ time_vector = result.get('time_vector')
124
+ if time_vector is None:
125
+ time_vector = result.get('t')
126
+ if time_vector is not None:
127
+ time_vector = np.asarray(time_vector)
128
+ if time_vector.ndim != 1:
129
+ raise ValueError(
130
+ f"Recording time vector must be 1-D, received shape {time_vector.shape}"
131
+ )
132
+ if time_vector.size == emg.shape[0] and time_vector.size != emg.shape[1]:
133
+ emg = emg.T
134
+
135
+ labels = result.get('channel_names')
136
+ if labels is None:
137
+ labels = result.get('ch_names')
138
+ if labels is not None:
139
+ labels = [str(label) for label in labels]
140
+ if len(labels) == emg.shape[1] and len(labels) != emg.shape[0]:
141
+ emg = emg.T
142
+
143
+ sampling_rate = result.get('_fs_Hz')
144
+ if sampling_rate is None:
145
+ sampling_rate = result.get('sample_rate')
146
+ if sampling_rate is None:
147
+ sampling_rate = result.get('fs')
148
+ if sampling_rate is None and isinstance(result.get('frequency_parameters'), dict):
149
+ sampling_rate = result['frequency_parameters'].get('amplifier_sample_rate')
150
+ if sampling_rate is None and time_vector is not None and time_vector.size > 1:
151
+ dt = float(np.median(np.diff(time_vector)))
152
+ sampling_rate = 1.0 / dt if dt > 0 else None
153
+ if sampling_rate is not None:
154
+ sampling_rate = float(sampling_rate)
155
+
156
+ if time_vector is None and sampling_rate is not None:
157
+ time_vector = np.arange(emg.shape[1], dtype=float) / sampling_rate
158
+ elif time_vector is not None and time_vector.size != emg.shape[1]:
159
+ raise ValueError(
160
+ f"Time vector has {time_vector.size} samples but EMG has {emg.shape[1]}"
161
+ )
162
+
163
+ if labels is None or len(labels) != emg.shape[0]:
164
+ labels = [f"CH{i}" for i in range(emg.shape[0])]
165
+
166
+ return emg, time_vector, sampling_rate, labels
167
+
168
+
97
169
  # --- IO helper utilities usable without GUI ---
98
- def save_model_obj(obj, path):
99
- """Save a model object with joblib or pickle."""
170
+ def save_model_obj(obj, path):
171
+ """Save a model object with joblib or pickle."""
100
172
  try:
101
173
  if path.lower().endswith('.joblib') and joblib is not None:
102
174
  joblib.dump(obj, path); return
103
175
  except Exception:
104
176
  pass
105
- import pickle
177
+ import pickle
106
178
  with open(path, 'wb') as f:
107
179
  pickle.dump(obj, f)
108
180
 
109
181
 
110
- def load_model_obj(path):
111
- """Load a model object with joblib or pickle."""
182
+ def load_model_obj(path):
183
+ """Load a model object with joblib or pickle."""
112
184
  try:
113
185
  if path.lower().endswith('.joblib') and joblib is not None:
114
186
  return joblib.load(path)
115
187
  except Exception:
116
188
  pass
117
- import pickle
189
+ import pickle
118
190
  with open(path, 'rb') as f:
119
191
  return pickle.load(f)
120
192
 
@@ -258,7 +330,7 @@ if _HAS_PYQT:
258
330
  feat_layout.addWidget(btn_save_feat)
259
331
  tabs.addTab(feat_tab, 'Feature Dataset')
260
332
 
261
- vlay.addWidget(tabs)
333
+ vlay.addWidget(tabs)
262
334
 
263
335
  # Make waveform view taller by increasing figure height and stretch
264
336
  # plot area: waveform and RMS tabs
@@ -304,8 +376,21 @@ if _HAS_PYQT:
304
376
  path, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Open EMG file', '', 'EMG Files (*.npz *.npy *.csv *.dat *.rhd);;RHD Files (*.rhd);;All Files (*)')
305
377
  if not path: return
306
378
  try:
307
- data = np.load(path) if path.lower().endswith('.npy') else np.loadtxt(path, delimiter=',')
308
- except Exception:
379
+ extension = os.path.splitext(path)[1].lower()
380
+ if extension in ('.rhd', '.npz'):
381
+ emg, _time, sampling_rate, _labels = _load_emg_recording(path)
382
+ data = emg.T
383
+ if sampling_rate is not None:
384
+ self.fs = sampling_rate
385
+ self.spin_fs.setValue(int(round(sampling_rate)))
386
+ elif extension == '.npy':
387
+ data = np.load(path)
388
+ else:
389
+ data = np.loadtxt(path, delimiter=',')
390
+ except Exception as first_error:
391
+ if os.path.splitext(path)[1].lower() in ('.rhd', '.npz'):
392
+ QtWidgets.QMessageBox.critical(self, 'Error', str(first_error))
393
+ return
309
394
  try:
310
395
  data = np.loadtxt(path)
311
396
  except Exception as e:
@@ -422,7 +507,7 @@ if _HAS_PYQT:
422
507
  except Exception: pass
423
508
  self.plot_waveforms()
424
509
 
425
- def _toggle_play(self):
510
+ def _toggle_play(self):
426
511
  if self.data is None:
427
512
  QtWidgets.QMessageBox.information(self, 'Play', 'No data loaded')
428
513
  return
@@ -434,13 +519,13 @@ if _HAS_PYQT:
434
519
  self.scrub_slider.setMaximum(max(0, self.data.shape[0]-1))
435
520
  except Exception:
436
521
  pass
437
- self.play_timer.start(); self.playing = True; self.btn_play.setText('Pause')
438
-
439
- def _on_slider_moved(self, value):
440
- self.current_pos = int(value)
441
- self.plot_waveforms()
442
-
443
- def _on_scrub_pressed(self):
522
+ self.play_timer.start(); self.playing = True; self.btn_play.setText('Pause')
523
+
524
+ def _on_slider_moved(self, value):
525
+ self.current_pos = int(value)
526
+ self.plot_waveforms()
527
+
528
+ def _on_scrub_pressed(self):
444
529
  # pause playback while user scrubs
445
530
  self._was_playing_on_scrub = self.playing
446
531
  if self.playing:
@@ -580,13 +665,13 @@ if _HAS_PYQT:
580
665
  if not hasattr(self, 'trained_model') or self.trained_model is None:
581
666
  QtWidgets.QMessageBox.information(self, 'Save Model', 'No trained model to save')
582
667
  return
583
- path, _ = QtWidgets.QFileDialog.getSaveFileName(self, 'Save Model', '', 'Joblib (*.joblib);;Pickle (*.pkl);;All Files (*)')
668
+ path, _ = QtWidgets.QFileDialog.getSaveFileName(self, 'Save Model', '', 'Joblib (*.joblib);;Pickle (*.pkl);;All Files (*)')
584
669
  if not path:
585
670
  return
586
671
  try:
587
672
  if path.lower().endswith('.joblib') and joblib is not None:
588
673
  joblib.dump(self.trained_model, path)
589
- else:
674
+ else:
590
675
  import pickle
591
676
  with open(path, 'wb') as f:
592
677
  pickle.dump(self.trained_model, f)
@@ -595,13 +680,13 @@ if _HAS_PYQT:
595
680
  QtWidgets.QMessageBox.warning(self, 'Save Model', str(e))
596
681
 
597
682
  def load_model(self):
598
- path, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Load Model', '', 'Joblib (*.joblib);;Pickle (*.pkl);;All Files (*)')
683
+ path, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Load Model', '', 'Joblib (*.joblib);;Pickle (*.pkl);;All Files (*)')
599
684
  if not path:
600
685
  return
601
686
  try:
602
687
  if path.lower().endswith('.joblib') and joblib is not None:
603
688
  model = joblib.load(path)
604
- else:
689
+ else:
605
690
  import pickle
606
691
  with open(path, 'rb') as f:
607
692
  model = pickle.load(f)
@@ -683,7 +768,7 @@ if _HAS_PYQT:
683
768
  except Exception as e:
684
769
  QtWidgets.QMessageBox.warning(self, 'Spectrogram', str(e))
685
770
 
686
- # TO-DO: implement this into a separate intan module
771
+ # TO-DO: implement this into a separate intan module
687
772
  try:
688
773
  import joblib
689
774
  except Exception:
@@ -700,7 +785,7 @@ except Exception:
700
785
  train_test_split = None
701
786
  _HAS_SKLEARN = False
702
787
 
703
- class EMGViewerTk:
788
+ class EMGViewerTk:
704
789
  def __init__(self, root):
705
790
  self.root = root
706
791
  self.root.title("EMG Data Viewer")
@@ -1240,14 +1325,16 @@ class EMGViewerTk:
1240
1325
  print("Segment loaded and visualized.")
1241
1326
 
1242
1327
  def load_file(self):
1243
- """ Load a .rhd file and plot the first channel."""
1328
+ """Load an RHD, NPZ, or CSV file and plot the first channel."""
1244
1329
  path = filedialog.askopenfilename(filetypes=[
1245
1330
  ("RHD files", "*.rhd"),
1331
+ ("NumPy archives", "*.npz"),
1246
1332
  ("CSV Files", "*.csv"),
1247
1333
  ])
1248
1334
  if not path:
1249
1335
  return
1250
- if path.endswith('.csv'):
1336
+ extension = os.path.splitext(path)[1].lower()
1337
+ if extension == '.csv':
1251
1338
  # Load CSV file. first column has timestamp data in milliseconds elapsed, the rest are EMG channels if
1252
1339
  # they have "EMG" in the name. The first row has only header information
1253
1340
  data = np.loadtxt(path, delimiter=',', skiprows=1)
@@ -1260,25 +1347,23 @@ class EMGViewerTk:
1260
1347
  self.emg_data = data[:, emg_columns].T
1261
1348
 
1262
1349
  self.sampling_rate = 1000.0 / (self.time_vector[1] - self.time_vector[0]) # Assuming uniform sampling
1263
- elif path.endswith('.rhd') and load_rhd_file is not None:
1350
+ elif extension in ('.rhd', '.npz'):
1264
1351
  try:
1265
- result = load_rhd_file(path)
1266
- self.emg_data = result.get("amplifier_data") or result.get('data')
1267
- # fallback keys
1268
- self.time_vector = result.get("t_amplifier") or result.get('t')
1269
- self.sampling_rate = result.get("frequency_parameters", {}).get("amplifier_sample_rate")
1352
+ (
1353
+ self.emg_data,
1354
+ self.time_vector,
1355
+ self.sampling_rate,
1356
+ _labels,
1357
+ ) = _load_emg_recording(path)
1270
1358
  except Exception as e:
1271
- print(f"Failed to load .rhd with intan.io: {e}")
1359
+ print(f"Failed to load recording with intan.io: {e}")
1272
1360
  return
1273
1361
  else:
1274
1362
  # fallback: try csv or numpy loader
1275
1363
  try:
1276
- if path.endswith('.npy') or path.endswith('.npz'):
1364
+ if extension == '.npy':
1277
1365
  arr = np.load(path)
1278
- if isinstance(arr, np.lib.npyio.NpzFile):
1279
- self.emg_data = arr[arr.files[0]]
1280
- else:
1281
- self.emg_data = arr
1366
+ self.emg_data = arr
1282
1367
  else:
1283
1368
  data = np.loadtxt(path, delimiter=',')
1284
1369
  # assume first column may be time
@@ -2043,10 +2128,10 @@ class EMGViewerTk:
2043
2128
  for spine in ax.spines.values():
2044
2129
  spine.set_visible(False)
2045
2130
 
2046
- def on_closing(self):
2047
- self.root.quit()
2048
-
2049
-
2050
- # Prefer the Qt implementation when the GUI extra is installed while keeping
2051
- # the Tk implementation available to callers that rely on it.
2052
- EMGViewer = EMGViewerQt if _HAS_PYQT else EMGViewerTk
2131
+ def on_closing(self):
2132
+ self.root.quit()
2133
+
2134
+
2135
+ # Prefer the Qt implementation when the GUI extra is installed while keeping
2136
+ # the Tk implementation available to callers that rely on it.
2137
+ EMGViewer = EMGViewerQt if _HAS_PYQT else EMGViewerTk
@@ -1,6 +1,5 @@
1
1
  import numpy as np
2
- from sklearn.decomposition import PCA
3
- import matplotlib.pyplot as plt
2
+ from .._optional import require_optional
4
3
 
5
4
  def pca(X, n_components=15, variance_threshold=0.95, show_plot=False, verbose=False):
6
5
  """
@@ -15,6 +14,7 @@ def pca(X, n_components=15, variance_threshold=0.95, show_plot=False, verbose=Fa
15
14
  n_pca_95: Number of components needed to reach 95% variance.
16
15
  """
17
16
 
17
+ PCA = require_optional("sklearn.decomposition", "analysis").PCA
18
18
  pca = PCA(n_components=n_components)
19
19
  X_pca = pca.fit_transform(X) # Shape: (samples, components)
20
20
  X_reconstructed = pca.inverse_transform(X_pca).T # Shape: (channels, samples)
@@ -26,6 +26,7 @@ def pca(X, n_components=15, variance_threshold=0.95, show_plot=False, verbose=Fa
26
26
  print(f"Number of components to retain 95% variance: {n_pca_95}")
27
27
 
28
28
  if show_plot:
29
+ plt = require_optional("matplotlib.pyplot", "plot")
29
30
  plt.plot(cumulative_variance * 100)
30
31
  plt.axhline(y=95, color='r', linestyle='--', label='95% threshold')
31
32
  plt.xlabel("Number of Components")
@@ -13,3 +13,4 @@ class LSLOptions:
13
13
  marker_name: str = "EMG-Markers"
14
14
  marker_type: str = "Markers"
15
15
  channel_labels: Optional[Sequence[str]] = None
16
+ device_timestamps: bool = False # Estimate LSL time from RHX sample counters
@@ -8,11 +8,14 @@ from pylsl import StreamInfo, StreamOutlet, local_clock, cf_string, IRREGULAR_RA
8
8
 
9
9
  class LSLNumericPublisher:
10
10
  def __init__(self, name: str, stype: str, fs: float, channels: int,
11
- source_id: str, channel_labels: Optional[Sequence[str]] = None):
11
+ source_id: str, channel_labels: Optional[Sequence[str]] = None,
12
+ *, timestamp_source: Optional[str] = None):
12
13
  if StreamInfo is None:
13
14
  raise RuntimeError("pylsl is not available; install pylsl to enable LSL streaming.")
14
15
  info = StreamInfo(name=name, type=stype, channel_count=channels,
15
16
  nominal_srate=fs, channel_format='float32', source_id=source_id)
17
+ if timestamp_source is not None:
18
+ info.desc().append_child_value("timestamp_source", timestamp_source)
16
19
  # Optional metadata
17
20
  chns = info.desc().append_child("channels")
18
21
  labels = list(channel_labels) if channel_labels else [f"ch_{i}" for i in range(channels)]