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.
@@ -0,0 +1,569 @@
1
+ """ This module contains utility functions for processing EMG data.
2
+
3
+ """
4
+ import os
5
+ import time
6
+ #import pywt
7
+ #import pathlib
8
+ import numpy as np
9
+ #import pandas as pd
10
+ from scipy.signal import find_peaks, peak_widths, butter, filtfilt, hilbert, iirnotch
11
+ from sklearn.decomposition import PCA
12
+ from sklearn.preprocessing import StandardScaler
13
+
14
+ # Define constants for windowing parameters and feature extraction
15
+ #WINDOW_SIZE = 400
16
+ #OVERLAP = 200
17
+
18
+ # Definition of G'
19
+ # def Gprime(x):
20
+ # return np.tanh(x)
21
+ #
22
+ #
23
+ # # Definition of G''
24
+ # def Gsecond(x):
25
+ # return np.ones(x.shape) - np.power(np.tanh(x), 2)
26
+ #
27
+ #
28
+ # # Center matrix X
29
+ # def centerMatrix(X, N):
30
+ # mean = X.mean(axis=1)
31
+ # M = X - (mean.reshape((N, 1)) @ np.ones((1, X.shape[1])))
32
+ # return M
33
+ #
34
+ #
35
+ # # Whiten matrix X with eigenvalue decomposition
36
+ # def whitenMatrix(X):
37
+ # D, E = np.linalg.eigh(X @ X.T)
38
+ # DE = np.diag(1 / np.sqrt(D + 1e-5)) @ E.T
39
+ #
40
+ # return DE @ X
41
+ #
42
+ #
43
+ # # One-unit algorithm step
44
+ # def oneUnit(X, wp):
45
+ # term1 = np.mean((X @ Gprime(wp @ X).T), axis=1)
46
+ # term2 = np.mean(Gsecond(wp @ X), axis=1) * wp
47
+ # return term1 - term2
48
+
49
+
50
+ # Deflationary orthogonalization
51
+ def orthogonalize(W, wp, i):
52
+ return wp - ((wp @ W[:i, :].T) @ W[:i, :])
53
+
54
+
55
+ # wp normalization
56
+ def normalize(wp):
57
+ return wp / np.linalg.norm(wp)
58
+
59
+ #
60
+ # def fastICA(X, C, max_iter):
61
+ # N = X.shape[0]
62
+ # X = centerMatrix(X, N)
63
+ # X = whitenMatrix(X)
64
+ #
65
+ # W = np.zeros((C, N))
66
+ # for i in range(C):
67
+ # wp = np.random.rand(1, N)
68
+ # for _ in range(max_iter):
69
+ # wp = oneUnit(X, wp)
70
+ # wp = orthogonalize(W, wp, i)
71
+ # wp = normalize(wp)
72
+ # W[i, :] = wp
73
+ #
74
+ # return W @ X
75
+
76
+ #
77
+ #
78
+ # def process_emg_files(file_paths, metrics_data, gesture_map):
79
+ # """Processes each EMG recording file and extracts RMS features."""
80
+ # X_list, y_list = [], []
81
+ #
82
+ # for file in file_paths:
83
+ # # Load EMG Data
84
+ # result, data_present = rhd_utils.load_file(file, verbose=False)
85
+ # if not data_present:
86
+ # continue
87
+ #
88
+ # emg_data = result['amplifier_data']
89
+ # sample_rate = int(result['frequency_parameters']['board_dig_in_sample_rate'])
90
+ #
91
+ # # Preprocess the EMG signal
92
+ # rms_features = preprocess_emg(emg_data, sample_rate)
93
+ #
94
+ # # Retrieve gesture label
95
+ # file_name = os.path.basename(file)
96
+ # if file_name not in metrics_data['File Name'].values:
97
+ # print(f"⚠️ Warning: No entry found for {file_name} in metrics data. Skipping.")
98
+ # continue
99
+ #
100
+ # gesture = metrics_data[metrics_data['File Name'] == file_name]['Gesture'].values[0]
101
+ #
102
+ # # Append to lists
103
+ # X_list.append(rms_features.T) # Shape (N_samples, 128)
104
+ # y_list.append(np.full(rms_features.shape[1], gesture_map[gesture]))
105
+ #
106
+ # return X_list, y_list
107
+
108
+ def preprocess_emg(emg_data, sample_rate):
109
+ """Applies filtering and extracts RMS features."""
110
+ filtered_data = notch_filter(emg_data, fs=sample_rate, f0=60)
111
+ filtered_data = butter_bandpass_filter(filtered_data, lowcut=20, highcut=400, fs=sample_rate, order=2, axis=1)
112
+ rms_features = calculate_rms(filtered_data, int(0.1 * sample_rate))
113
+ return rms_features
114
+
115
+ def parse_channel_ranges(channel_arg):
116
+ """
117
+ Parses a channel range string (e.g., [1:8, 64:72]) and returns a flat list of integers.
118
+
119
+ Args:
120
+ channel_arg (str): The string containing channel ranges (e.g., "[1:8, 64:72]").
121
+
122
+ Returns:
123
+ list: A flat list of integers.
124
+ """
125
+ # Remove square brackets and split by commas
126
+ channel_arg = channel_arg.strip("[]")
127
+ ranges = channel_arg.split(",")
128
+
129
+ channel_list = []
130
+ for r in ranges:
131
+ if ":" in r:
132
+ start, end = map(int, r.split(":"))
133
+ #channel_list.extend(range(start - 1, end)) # Convert to 0-based indexing
134
+ channel_list.extend(range(start, end))
135
+ else:
136
+ #channel_list.append(int(r) - 1) # Convert single channel to 0-based indexing
137
+ channel_list.append(int(r))
138
+ return channel_list
139
+
140
+ #
141
+ # # Define feature extraction functions
142
+ # def extract_wavelet_features(emg_data, window_size=WINDOW_SIZE, overlap=OVERLAP):
143
+ # features = []
144
+ # num_samples, num_channels = emg_data.shape
145
+ # print(f"Num samples: {num_samples}, Num channels: {num_channels}")
146
+ # step = window_size - overlap
147
+ #
148
+ # for start in range(0, num_samples - window_size + 1, step):
149
+ # window = emg_data[start:start + window_size]
150
+ # window_features = []
151
+ #
152
+ # for channel_data in window.T:
153
+ # # Apply 2-level wavelet decomposition using dbl mother wavelet
154
+ # coeffs = pywt.wavedec(channel_data, 'db4', level=2)
155
+ #
156
+ # # Extract 19 statistical features from the detail and approximation coefficients
157
+ # # Or pick and choose the features you want to extract
158
+ # for coeff in coeffs:
159
+ # window_features.extend([
160
+ # np.sum(np.abs(coeff)), # IEMG
161
+ # np.mean(np.abs(coeff)), # MAV
162
+ # np.sum(coeff ** 2), # SSI
163
+ # np.sqrt(np.mean(coeff ** 2)), # RMS
164
+ # np.var(coeff), # VAR
165
+ # np.mean(coeff > 0), # MYOP
166
+ # np.sum(np.abs(np.diff(coeff))), # WL
167
+ # np.mean(np.abs(np.diff(coeff))), # DAMV
168
+ # np.sum(coeff ** 2) / len(coeff), # Second-order moment (M2)
169
+ # np.var(np.diff(coeff)), # DVARV
170
+ # np.std(np.diff(coeff)), # DASDV
171
+ # np.sum(np.abs(coeff) > 0.05), # WAMP (threshold = 0.05)
172
+ # np.sum(np.abs(np.diff(coeff, 2))), # IASD
173
+ # np.sum(np.abs(np.diff(coeff, 3))), # IATD
174
+ # np.sum(np.exp(np.abs(coeff))), # IEAV
175
+ # np.sum(np.log(np.abs(coeff) + 1e-6)), # IALV
176
+ # np.sum(np.exp(coeff)), # IE
177
+ # np.min(coeff), # MIN
178
+ # np.max(coeff) # MAX
179
+ # ])
180
+ # features.append(window_features)
181
+ #
182
+ # return np.array(features)
183
+
184
+ def notch_filter(data, fs=4000, f0=60.0, Q=30):
185
+ """Applies a notch filter to the data to remove 60 Hz interference.
186
+ Assumes data shape (n_channels, n_samples).
187
+ """
188
+ b, a = iirnotch(f0, Q, fs)
189
+ return filtfilt(b, a, data, axis=1)
190
+
191
+ def butter_bandpass(lowcut, highcut, fs, order=5):
192
+ # butterworth bandpass filter
193
+ nyq = 0.5 * fs
194
+ low = lowcut / nyq
195
+ high = highcut / nyq
196
+ b, a = butter(order, [low, high], btype='band')
197
+ return b, a
198
+
199
+
200
+ def butter_lowpass(cutoff, fs, order=5):
201
+ nyq = 0.5 * fs
202
+ norm_cutoff = cutoff / nyq
203
+ b, a = butter(order, norm_cutoff, btype='low')
204
+ return b, a
205
+
206
+
207
+ def butter_lowpass_filter(data, cutoff, fs, order=5, axis=0):
208
+ b, a = butter_lowpass(cutoff, fs, order)
209
+ y = filtfilt(b, a, data, axis=axis) # Filter along axis 0 (time axis) for all channels simultaneously
210
+ return y
211
+
212
+
213
+ def butter_bandpass_filter(data, lowcut, highcut, fs, order=5, axis=0, verbose=False):
214
+ if verbose:
215
+ print(f"| Applying butterworth bandpass filter: {lowcut}-{highcut} Hz {order} order")
216
+ # function to implement filter on data
217
+ b, a = butter_bandpass(lowcut, highcut, fs, order=order)
218
+ y = filtfilt(b, a, data, axis=axis) # Filter channels simultaneously
219
+ return y
220
+
221
+
222
+ def filter_emg(emg_data, filter_type='bandpass', lowcut=30, highcut=500, fs=1259, order=5, verbose=False):
223
+ """
224
+ Applies a bandpass or lowpass filter to EMG data using numpy arrays.
225
+
226
+ Args:
227
+ emg_data: Numpy array of shape (num_samples, num_channels) with EMG data.
228
+ filter_type: Type of filter to apply ('bandpass' or 'lowpass').
229
+ lowcut: Low cutoff frequency for the bandpass filter.
230
+ highcut: High cutoff frequency for the bandpass filter.
231
+ fs: Sampling rate of the EMG data.
232
+ order: Filter order.
233
+ verbose: Whether to print progress.
234
+
235
+ Returns:
236
+ Filtered data as a numpy array (same shape as input data).
237
+ """
238
+ tic = time.process_time()
239
+
240
+ if filter_type == 'bandpass':
241
+ if verbose: print(f"| Applying butterworth bandpass filter: {lowcut}-{highcut} Hz {order} order")
242
+ filtered_data = butter_bandpass_filter(emg_data, lowcut, highcut, fs, order)
243
+ elif filter_type == 'lowpass':
244
+ if verbose: print(f"| Applying butterworth lowpass filter: {lowcut} Hz {order} order")
245
+ filtered_data = butter_lowpass_filter(emg_data, lowcut, fs, order)
246
+
247
+ toc = time.process_time()
248
+ if verbose:
249
+ print(f"| | Filtering time = {1000 * (toc - tic):.2f} ms")
250
+
251
+ # Convert list of arrays to a single 2D numpy array
252
+ filtered_data = np.stack(filtered_data, axis=0) # Stack along axis 0 (channels)
253
+
254
+ return filtered_data
255
+
256
+
257
+ def rectify(emg_data):
258
+ """
259
+ Rectifies EMG data by converting all values to their absolute values.
260
+
261
+ Args:
262
+ EMGDataDF: List of numpy arrays or pandas DataFrame items with filtered EMG data.
263
+
264
+ Returns:
265
+ rectified_data: List of rectified numpy arrays (same shape as input data).
266
+ """
267
+ rectified_data = np.abs(emg_data)
268
+
269
+ return rectified_data
270
+
271
+
272
+ def window_rms(emg_data, window_size=400, verbose=False):
273
+ """
274
+ Apply windowed RMS to each channel in the multi-channel EMG data.
275
+
276
+ Args:
277
+ emg_data: Numpy array of shape (num_samples, num_channels).
278
+ window_size: Size of the window for RMS calculation.
279
+
280
+ Returns:
281
+ Smoothed EMG data with windowed RMS applied to each channel (same shape as input).
282
+ """
283
+ if verbose: print(f"| Applying windowed RMS with window size {window_size}")
284
+ num_channels, num_samples = emg_data.shape
285
+ rms_data = np.zeros((num_channels, num_samples))
286
+
287
+ for i in range(num_channels):
288
+ rms_data[i, :] = window_rms_1D(emg_data[i, :], window_size)
289
+
290
+ return rms_data
291
+
292
+
293
+ def window_rms_1D(signal, window_size):
294
+ """
295
+ Compute windowed RMS of the signal.
296
+
297
+ Args:
298
+ signal: Input EMG signal.
299
+ window_size: Size of the window for RMS calculation.
300
+
301
+ Returns:
302
+ Windowed RMS signal.
303
+ """
304
+ return np.sqrt(np.convolve(signal ** 2, np.ones(window_size) / window_size, mode='same'))
305
+
306
+
307
+
308
+ def calculate_rms(data, window_size, verbose=False):
309
+ """Calculates RMS features for each channel using non-overlapping windows."""
310
+ if verbose:
311
+ print("| Calculating RMS features...")
312
+ n_channels, n_samples = data.shape
313
+ n_windows = n_samples // window_size
314
+ rms_features = np.zeros((n_channels, n_windows))
315
+
316
+ for ch in range(n_channels):
317
+ for i in range(n_windows):
318
+ window = data[ch, i * window_size:(i + 1) * window_size]
319
+ rms_features[ch, i] = np.sqrt(np.mean(window ** 2))
320
+
321
+ return rms_features # Shape (n_channels, n_windows)
322
+
323
+ def downsample(emg_data, sampling_rate, target_fs=1000):
324
+ """
325
+ Downsamples the EMG data to the target sampling rate.
326
+
327
+ Args:
328
+ emg_data: 2D numpy array of shape (num_channels, num_samples).
329
+ sampling_rate: Sampling rate of the original EMG data.
330
+ target_fs: Target sampling rate for downsampling.
331
+
332
+ Returns:
333
+ downsampled_data: 2D numpy array of shape (num_channels, downsampled_samples).
334
+ """
335
+ # Compute the downsampling factor
336
+ downsample_factor = int(sampling_rate / target_fs)
337
+
338
+ # Downsample the data by taking every nth sample
339
+ downsampled_data = emg_data[:, ::downsample_factor]
340
+
341
+ return downsampled_data
342
+
343
+ def common_average_reference(emg_data, verbose=False):
344
+ """
345
+ Applies Common Average Referencing (CAR) to the multi-channel EMG data.
346
+
347
+ Args:
348
+ emg_data: 2D numpy array of shape (num_channels, num_samples).
349
+
350
+ Returns:
351
+ car_data: 2D numpy array after applying CAR (same shape as input).
352
+ """
353
+ if verbose:
354
+ print("| Subtracting common average reference")
355
+ # Compute the common average (mean across all channels at each time point)
356
+ common_avg = np.mean(emg_data, axis=0) # Shape: (num_samples,)
357
+
358
+ # Subtract the common average from each channel
359
+ car_data = emg_data - common_avg # Broadcast subtraction across channels
360
+
361
+ return car_data
362
+
363
+
364
+ def envelope_extraction(data, method='hilbert'):
365
+ if method == 'hilbert':
366
+ analytic_signal = hilbert(data, axis=1)
367
+ envelope = np.abs(analytic_signal)
368
+ else:
369
+ raise ValueError("Unsupported method for envelope extraction.")
370
+ return envelope
371
+
372
+
373
+ def process_emg_pipeline(data, lowcut=30, highcut=500, order=5, window_size=400, verbose=False):
374
+ # Processing steps to match the CNN-ECA methodology
375
+ # https://pmc.ncbi.nlm.nih.gov/articles/PMC10669079/
376
+ # Input data is assumed to have shape (N_channels, N_samples)
377
+
378
+ emg_data = data['amplifier_data'] # Extract EMG data
379
+ sample_rate = int(data['frequency_parameters']['board_dig_in_sample_rate']) # Extract sampling rate
380
+
381
+ # Overwrite the first and last second of the data with 0 to remove edge effects
382
+ #emg_data[:, :sample_rate] = 0.0
383
+ emg_data[:, -sample_rate:] = 0.0 # Just first second
384
+
385
+ # Apply bandpass filter
386
+ bandpass_filtered = filter_emg(emg_data, 'bandpass', lowcut, highcut, sample_rate, order)
387
+
388
+ # Rectify
389
+ #rectified = rectify_emg(bandpass_filtered)
390
+ rectified = bandpass_filtered
391
+
392
+ # Apply Smoothing
393
+ #smoothed = window_rms(rectified, window_size=window_size)
394
+ smoothed = envelope_extraction(rectified, method='hilbert')
395
+
396
+ return smoothed
397
+
398
+
399
+ def sliding_window(data, window_size, step_size):
400
+ """
401
+ Splits the data into overlapping windows.
402
+
403
+ Args:
404
+ data: 2D numpy array of shape (channels, samples).
405
+ window_size: Window size in number of samples.
406
+ step_size: Step size in number of samples.
407
+
408
+ Returns:
409
+ windows: List of numpy arrays, each representing a window of data.
410
+ """
411
+ num_channels, num_samples = data.shape
412
+ windows = []
413
+
414
+ for start in range(0, num_samples - window_size + 1, step_size):
415
+ window = data[:, start:start + window_size]
416
+ windows.append(window)
417
+
418
+ return windows
419
+
420
+
421
+ def apply_pca(data, num_components=8, verbose=False):
422
+ """
423
+ Applies PCA to reduce the number of EMG channels to the desired number of components.
424
+
425
+ Args:
426
+ data: 2D numpy array of EMG data (channels, samples) -> (128, 500,000).
427
+ num_components: Number of principal components to reduce to (e.g., 8).
428
+
429
+ Returns:
430
+ pca_data: 2D numpy array of reduced EMG data (num_components, samples).
431
+ explained_variance_ratio: Percentage of variance explained by each of the selected components.
432
+ """
433
+ # Step 1: Standardize the data across the channels
434
+ scaler = StandardScaler()
435
+ features_std = scaler.fit_transform(data) # Standardizing along the channels
436
+
437
+ # Step 2: Apply PCA
438
+ pca = PCA(n_components=num_components)
439
+ pca_data = pca.fit_transform(features_std) # Apply PCA on the transposed data
440
+
441
+ if verbose:
442
+ print("Original shape:", data.shape)
443
+ print("PCA-transformed data shape:", pca_data.shape)
444
+
445
+ # Step 3: Get the explained variance ratio (useful for understanding how much variance is retained)
446
+ explained_variance_ratio = pca.explained_variance_ratio_
447
+
448
+ return pca_data, explained_variance_ratio
449
+
450
+
451
+ # def apply_gesture_label(df, sampling_rate, data_metrics, start_index_name='Start Index', n_trials_name='N_trials', trial_interval_name='Trial Interval (s)', gesture_name='Gesture'):
452
+ # """ Applies the Gesture label to the dataframe and fills in the corresponding gesture labels for samples in the
453
+ # dataframe. The gesture labels are extracted from the data_metrics dataframe.
454
+ # """
455
+ #
456
+ # # Initialize a label column in the dataframe
457
+ # #df['Gesture'] = 'Rest' # Default is 'Rest'
458
+ #
459
+ # # Collect the data metrics for the current file
460
+ # start_idx = data_metrics[start_index_name]
461
+ # print(f"Start index: {start_idx}")
462
+ # n_trials = data_metrics[n_trials_name]
463
+ # print(f"Number of trials: {n_trials}")
464
+ # trial_interval = data_metrics[trial_interval_name]
465
+ # print(f"Trial interval: {trial_interval}")
466
+ # gesture = data_metrics[gesture_name]
467
+ # print(f"Gesture: {gesture}")
468
+ #
469
+ # # Iterate over each trial and assign the gesture label to the corresponding samples
470
+ # for i in range(n_trials):
471
+ # # Get start and end indices for the flex (gesture) and relax
472
+ # start_flex = start_idx + i * sampling_rate * trial_interval
473
+ # end_flex = start_flex + sampling_rate * trial_interval / 2 # Flex is half of interval
474
+ #
475
+ # # Label the flex periods as the gesture
476
+ # df.loc[start_flex:end_flex, 'Gesture'] = gesture
477
+ #
478
+ # return df
479
+
480
+ def z_score_norm(data):
481
+ """
482
+ Apply z-score normalization to the input data.
483
+
484
+ Args:
485
+ data: 2D numpy array of shape (channels, samples).
486
+
487
+ Returns:
488
+ normalized_data: 2D numpy array of shape (channels, samples) after z-score normalization.
489
+ """
490
+ mean = np.mean(data, axis=1)[:, np.newaxis]
491
+ std = np.std(data, axis=1)[:, np.newaxis]
492
+ normalized_data = (data - mean) / std
493
+ return normalized_data
494
+
495
+
496
+ # RMS (Root Mean Square)
497
+ def compute_rms(emg_window):
498
+ return np.sqrt(np.mean(emg_window**2))
499
+
500
+ # WL (Waveform Length)
501
+ # def compute_wl(emg_window):
502
+ # return np.sum(np.abs(np.diff(emg_window)))
503
+ #
504
+ # # MAS (Median Amplitude Spectrum)
505
+ # def compute_mas(emg_window):
506
+ # fft_values = np.fft.fft(emg_window)
507
+ # magnitude_spectrum = np.abs(fft_values)
508
+ # return np.median(magnitude_spectrum)
509
+
510
+ # SampEn (Sample Entropy)
511
+ #import antropy as ant
512
+
513
+ # def compute_sampen(emg_window, m=2, r=0.2):
514
+ # return ant.sample_entropy(emg_window, order=m)
515
+
516
+ # Extract features for a given EMG window
517
+ # def extract_features(emg_window):
518
+ # """https://link.springer.com/article/10.1007/s00521-019-04142-8"""
519
+ # features = [
520
+ # compute_rms(emg_window),
521
+ # compute_wl(emg_window),
522
+ # compute_mas(emg_window),
523
+ # compute_sampen(emg_window)
524
+ # ]
525
+ # return np.array(features)
526
+ #
527
+ # def create_lagged_features(features, n_lags=4, verbose=False):
528
+ # """
529
+ # Create lagged features by concatenating the current bin with the previous n_lags bins.
530
+ # Args:
531
+ # features: input array of shape (n_channels, n_bins).
532
+ # n_lags: Number of previous bins to concatenate with the current bin.
533
+ #
534
+ # Returns:
535
+ # lagged_features: array of shape (n_bins - n_lags, n_channels * (n_lags + 1)).
536
+ # """
537
+ # if verbose: print(f"| Creating lagged features with {n_lags} lags...")
538
+ # num_bins = features.shape[1] # Total number of bins
539
+ # lagged_features = []
540
+ # for i in range(4, num_bins):
541
+ # # Concatenate the current bin with the previous 4 bins
542
+ # current_features = features[:, (i - 4):i + 1].flatten() # Flatten to create feature vector
543
+ # lagged_features.append(current_features)
544
+ #
545
+ # if verbose: print(f"| Lagged features shape: {np.array(lagged_features).shape}")
546
+ # return np.array(lagged_features)
547
+
548
+ def compute_grid_average(emg_data, grid_spacing=8, axis=0):
549
+ """Function that computes the average of the EMG grids according to the grid spacing. For example, a spacing of 8 means that
550
+ channels 1, 9, 17, etc. will be averaged together to form the first grid, and so on.
551
+
552
+ Args:
553
+ emg_data (np.ndarray): 2D numpy array of shape (num_channels, num_samples).
554
+ grid_spacing (int): Number of channels to average together.
555
+ axis (int): Axis along which to compute the grid averages.
556
+
557
+ Returns:
558
+ grid_averages (np.ndarray): 2D numpy array of shape (num_grids, num_samples).
559
+ """
560
+ num_channels, num_samples = emg_data.shape
561
+ num_grids = num_channels // grid_spacing
562
+ grid_averages = np.zeros((num_grids, num_samples))
563
+
564
+ for i in range(num_grids):
565
+ start_idx = i * grid_spacing
566
+ end_idx = (i + 1) * grid_spacing
567
+ grid_averages[i, :] = np.mean(emg_data[start_idx:end_idx, :], axis=axis)
568
+
569
+ return grid_averages
@@ -0,0 +1,84 @@
1
+ import os
2
+ import pathlib
3
+ import pandas as pd
4
+
5
+ def read_config_file(config_file):
6
+ # Dictionary to store the key-value pairs
7
+ config_data = {}
8
+
9
+ config_filepath = pathlib.Path(config_file)
10
+
11
+ # Open the TRUECONFIG.txt file and read its contents
12
+ with open(config_filepath, 'r') as file:
13
+ for line in file:
14
+ # Strip whitespace and ignore empty lines or comments
15
+ line = line.strip()
16
+ if not line or line.startswith('#'):
17
+ continue
18
+
19
+ # Split the line into key and value at the first '='
20
+ key, value = line.split('=', 1)
21
+ config_data[key.strip()] = value.strip()
22
+
23
+ return config_data
24
+
25
+ def get_file_paths(directory, file_type=None, verbose=False):
26
+ """
27
+ Returns a list of full paths for files ending with .rhd in the given directory and its subdirectories.
28
+
29
+ Parameters:
30
+ ------------
31
+ directory: (str) The parent directory to search within.
32
+ file_type: (str) The file extension to search for (default: '.rhd').
33
+ verbose: (bool) Whether to print the number of files found.
34
+
35
+ Returns:
36
+ rhd_files: List of full paths to either folders or files
37
+ """
38
+ if verbose: print("Searching in directory:", directory)
39
+
40
+ # Convert the directory to an absolute path and a Path object for compatibility
41
+ directory = pathlib.Path(os.path.abspath(directory))
42
+
43
+ # Check if the directory exists
44
+ if not directory.exists() or not directory.is_dir():
45
+ print(f"Directory '{directory}' not found or is not a valid directory.")
46
+ return []
47
+
48
+ # If file_type is left None, we just need to return the folders within the current directory
49
+ file_paths = None
50
+ if file_type is None:
51
+ file_paths = list(directory.glob('*'))
52
+ if verbose: print(f"Found {len(file_paths)} folders")
53
+ elif file_type == '.rhd':
54
+ # Recursively find all .rhd files
55
+ file_paths = list(directory.rglob('*.rhd'))
56
+ if verbose: print(f"Found {len(file_paths)} .rhd files")
57
+ else:
58
+ print("Unsupported file type. Please specify '.rhd' or None.")
59
+
60
+ return file_paths
61
+
62
+ def load_metrics_data(metrics_filepath, verbose=True):
63
+ """ Loads the metrics data from the specified file path and returns the data along with the gesture mapping.
64
+
65
+ Args:
66
+ metrics_filepath (str): The path to the metrics data file.
67
+ verbose (bool): Whether to print the loaded data and gesture mapping.
68
+ """
69
+ if not os.path.isfile(metrics_filepath):
70
+ print(f"Metrics file not found: {metrics_filepath}. Please correct file path or generate the metrics file.")
71
+ return None
72
+ metrics_data = pd.read_csv(metrics_filepath)
73
+ if verbose:
74
+ print(f"Loaded metrics data from {metrics_filepath}: unique labels {metrics_data['Gesture'].unique()}")
75
+ print(metrics_data)
76
+
77
+ # Generate gesture mapping
78
+ gestures = metrics_data['Gesture'].unique()
79
+ gesture_map = {gesture: i for i, gesture in enumerate(gestures)}
80
+ if verbose:
81
+ print(f"Gesture mapping: {gesture_map}")
82
+
83
+ return metrics_data, gesture_map
84
+