-
Notifications
You must be signed in to change notification settings - Fork 0
/
lfp_analysis.py
2446 lines (2070 loc) · 99.8 KB
/
lfp_analysis.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import glob
import subprocess
import os
import warnings
from collections import defaultdict
import trodes.read_exported
import pandas as pd
import numpy as np
from scipy import stats
from spectral_connectivity import Multitaper, Connectivity
import logging
import h5py
from scipy.interpolate import interp1d
from scipy.signal import savgol_filter
import matplotlib.pyplot as plt
import spikeinterface.extractors as se
import spikeinterface.preprocessing as sp
# Constants
SPIKE_GADGETS_MULTIPLIER = 0.6745
class LfpExperiment:
"""
list_of_lfp_objects: list of LFPObject objects
for file in recording_dir:
generate_lfp_object(file)
mainly for analysis, graphs, and overall trends
"""
def __init__(self, experiment):
self.list_of_lfp_objects = {}
self.experiment = experiment
def add_lfp_object(self, lfp_object, subject):
self.list_of_lfp_objects[(subject, self.experiment)] = lfp_object
class LfpRecordingObject:
#TODO: Changed recording extention to merged.rec here, debug here if needed
"""
class for each recording
__init__:
- path (str): path to recording
- channel_map_path (str): path to channel map
- sleap_path (str): path to sleap data
- events_path (str): path to events
- experiment_name (str): name of experiment
- subject (str): name/ id of subject
- output_path (str): path to save output
- encoding_dict (dict str: str): dictionary of encoding
- time_window_step (int): time window step
- time_window_duration (int): time window duration
- time_half_bandwidth_prod (int): time half bandwidth product
- zscore_threshold=4 (int): zscore threshold, default 4
- voltage_scaling_value=0.195 (float): voltage scaling value, default 0.195
- resample_rate=1000 (int): resample rate, default 1000
- sampling_rate=20000 (int): sampling rate, default 20000
- frame_rate=22 (int): frame rate, default 22
- ecu=False (bool): ecu, default False
make_output_dir:
Verifies or creates the output directory exists
make_object:
Creates the LFP object and saves the metadata, state_df, video_df, final_df
make_spike_df:
Calls combine_lfp_traces_and_metadata and saves the spike_df
make_power_df:
Calls preprocess_lfp_data and calculate_power and saves the power_df
make_phase_df:
Calls calculate_phase and saves the phase_df
make_coherence_df:
Calls calculate_coherence and saves the coherence_df
make_granger_df:
Calls calculate_granger_causality and saves the granger_df
make_filter_bands_df:
Calls calculate_filter_bands and saves the filter_bands_df
make_sleap_df:
Calls process_sleap_data and saves the sleap_df and start_stop_df
analyze_sleap:
Calls analyze_sleap_file, produces plots and saves them based on user input
add_labels:
Combines labels with the LFP object and saves the labels_and_spectral
add_label_encoding:
Adds trial label encoding to the LFP object and saves the label_encoding
"""
def make_object(self):
self.recording_names_dict = extract_lfp_traces(
all_session_dir=self.path,
ECU_STREAM_ID="ECU",
TRODES_STREAM_ID="trodes",
recording_extention="*merged.rec")
# call extract_all_trodes
session_to_trodes_temp, paths = extract_all_trodes(input_dir=self.path)
# call add_video_timestamps
session_to_trodes_temp = add_video_timestamps(
session_to_trodes_data=session_to_trodes_temp,
directory_path=self.path)
# call create_metadata_df
metadata = create_metadata_df(
session_to_trodes=session_to_trodes_temp, session_to_path=paths)
# call adjust_first_timestamps
self.metadata, self.state_df, self.video_df, self.final_df = adjust_first_timestamps(
trodes_metadata_df=metadata, output_dir=self.path, experiment_prefix=self.experiment_name)
print(self.output_path)
# Pickle all
self.metadata.to_pickle(self.output_path + "/metadata.pkl")
self.state_df.to_pickle(self.output_path + "/state_df.pkl")
self.video_df.to_pickle(self.output_path + "/video_df.pkl")
self.final_df.to_pickle(self.output_path + "/final_df.pkl")
print("LFP Object has been created for " +
self.subject + " at " + self.path)
def make_spike_df(self):
self.spike_df = combine_lfp_traces_and_metadata(
spikegadgets_extracted_df=self.final_df,
recording_name_to_all_ch_lfp=self.recording_names_dict,
channel_map_df=self.channel_map,
EPHYS_SAMPLING_RATE=20000,
LFP_SAMPLING_RATE=1000)
print("Spike dataframe has been created at " +
self.output_path + "/spike_df.pkl")
self.spike_df.to_pickle(self.output_path + "/spike_df.pkl")
def make_power_df(self):
self.lfp_trace_df = preprocess_lfp_data(
lfp_traces_df=self.spike_df,
voltage_scaling_value=self.voltage_scaling_value,
zscore_threshold=self.zscore_threshold,
resample_rate=self.resample_rate)
print("LFP TRACES DF")
print(self.lfp_trace_df.head())
# call get_power
power_df = calculate_power(
self.spike_df,
self.resample_rate,
self.time_half_bandwidth_prod,
self.time_window_duration,
self.time_window_step)
# assign variables
self.power_df = power_df
print("Power dataframe has been created at " +
self.output_path + "/power_df.pkl")
self.power_df.to_pickle(self.output_path + "/power_df.pkl")
def make_phase_df(self):
# call get_phase
phase_df = calculate_phase(self.spike_df, fs=1000)
# assign variables
print("Phase dataframe has been created at " +
self.output_path + "/phase_df.pkl")
self.phase_df.to_pickle(self.output_path + "/phase_df.pkl")
self.phase_df = phase_df
def make_coherence_df(self):
# call get_coherence
# lfp_traces_df, resample_rate, time_halfbandwidth_product, time_window_duration, time_window_step
coherence_df = calculate_coherence(self.spike_df, self.resample_rate,
self.time_half_bandwidth_prod,
self.time_window_duration,
self.time_window_step)
print("Coherence dataframe has been created at " +
self.output_path + "/coherence_df.pkl")
self.coherence_df.to_pickle(self.output_path + "/coherence_df.pkl")
# assign variables
self.coherence_df = coherence_df
def make_granger_df(self):
# call get_granger
# lfp_traces_df, resample_rate, time_halfbandwidth_product, time_window_duration, time_window_step
granger_df = calculate_granger_causality(
lfp_traces_df=self.spike_df,
resample_rate=self.resample_rate,
time_halfbandwidth_product=self.time_half_bandwidth_prod,
time_window_duration=self.time_window_duration,
time_window_step=self.time_window_step)
print("Granger dataframe has been created at " +
self.output_path + "/granger_df.pkl")
self.granger_df.to_pickle(self.output_path + "/granger_df.pkl")
# assign variables
self.granger_df = granger_df
def make_filter_bands_df(self):
# call get_filter_bands
# (lfp_spectral_df, theta_band, gamma_band, output_dir, output_prefix):
filter_bands_df = calculate_filter_bands(
lfp_spectral_df=self.power_df,
theta_band=self.BAND_TO_FREQ["theta"],
gamma_band=self.BAND_TO_FREQ["gamma"],
output_dir=os.getcwd(),
output_prefix="test")
print("Filter bands dataframe has been created at " +
self.output_path + "/filter_bands_df.pkl")
self.filter_bands_df.to_pickle(
self.output_path + "/filter_bands_df.pkl")
# assign variables
self.filter_bands_df = filter_bands_df
def make_sleap_df(self):
# call get_start_stop
# todo: init with medpc width and height; window size; distance
sleap_df, start_stop_df = process_sleap_data(sleap_dir=self.sleap_path,
output_dir=self.output_path,
med_pc_width=1,
med_pc_height=1,
frame_rate=self.frame_rate,
window_size=90,
distance_threshold=0.1,
start_stop_frame_df=pd.read_excel(
self.events_path),
lfp_spectral_df=self.filter_bands_df,
thorax_index=1,
output_prefix=self.experiment_name)
print(
"Sleap and start/stop dataframes has been created at " +
self.output_path +
"/sleap_df.pkl and " +
self.output_path +
"/start_stop_df.pkl")
self.sleap_df.to_pickle(self.output_path + "/sleap_df.pkl")
self.start_stop_df.to_pickle(self.output_path + "/start_stop_df.pkl")
# assign variables
self.sleap_df = sleap_df
self.start_stop_df = start_stop_df
def analyze_sleap(self, thorax_index):
print("Analysis of sleap data started.")
analyze_sleap_file(
start_stop_frame_df=self.start_stop_df,
plot_output_dir=self.output_path +
"/plots/",
output_prefix=self.experiment_name,
thorax_index=thorax_index,
thorax_plots=True,
save_plots=True)
print("Analysis of sleap data completed.")
def make_output_dir(self):
print("IN MAKE OUTPUT DIR")
os.makedirs(self.output_path, exist_ok=True)
self.output_path = self.output_path + "/" + self.subject
os.makedirs(self.output_path, exist_ok=True)
print("Output path is " + self.output_path)
def add_labels(self, labels_path):
self.labels_df = pd.read_excel(labels_path)
self.labels_and_spectral = make_labels_df(
labels_df=self.labels_df, filter_bands_df=self.filter_bands_df)
self.labels_and_spectral.to_pickle(
self.output_path + "/labels_and_spectral.pkl")
def add_label_encoding(self):
self.label_encoding = encode_labels(
filter_bands_df=self.filter_bands_df,
labels_df=self.labels_df,
encoding_dict=self.encoding_dict)
self.label_encoding.to_pickle(
self.output_path + "/label_encoding.pkl")
#TODO updated ecu params for meta data
def __init__(self,
path,
channel_map_path,
sleap_path,
events_path,
experiment_name,
subject,
output_path,
encoding_dict,
time_window_step,
time_window_duration,
time_half_bandwidth_prod,
zscore_threshold=4,
voltage_scaling_value=0.195,
resample_rate=1000,
sampling_rate=20000,
frame_rate=22,
ecu=False):
self.labels_df = None
self.path = path
self.channel_map_path = channel_map_path
self.sleap_path = sleap_path
self.events_path = events_path
self.experiment_name = experiment_name
self.events = {}
self.channel_map = {}
self.recording = None
self.subject = subject
self.sampling_rate = sampling_rate
self.frame_rate = frame_rate
self.encoding_dict = encoding_dict
self.output_path = output_path
# add variables from make object function
self.metadata = None
self.state_df = None
self.video_df = None
self.final_df = None
self.pkl_path = None
# inputs needed for notebook 2 (power)
self.lfp_trace_df = None
self.original_trace_columns = None
self.voltage_scaling_value = voltage_scaling_value
self.zscore_threshold = zscore_threshold
self.resample_rate = resample_rate
self.time_half_bandwidth_prod = time_half_bandwidth_prod
self.time_window_duration = time_window_duration
self.time_window_step = time_window_step
self.BAND_TO_FREQ = {"theta": (4, 12), "gamma": (30, 51)}
# granger
self.power_df = None
self.phase_df = None
self.coherence_df = None
self.granger_df = None
# notebook 3 "bands"
self.filter_bands_df = None
# notebook 4 sleap, events
self.sleap_df = None
self.start_stop_df = None
# labels notebook
self.labels_and_spectral = None
self.label_encoding = None
# get channel map and lfp
# ALL_SESSION_DIR, ECU_STREAM_ID, TRODES_STREAM_ID,
# RECORDING_EXTENTION, LFP_FREQ_MIN, LFP_FREQ_MAX, ELECTRIC_NOISE_FREQ,
# LFP_SAMPLING_RATE, EPHYS_SAMPLING_RATE):
self.recording_names_dict = None
self.channel_map = load_channel_map(
channel_map_path=self.channel_map_path)
self.spike_df = None
def helper_filter_array_by_values(arr, start_value=0, stop_value=1000000):
"""
Filters elements of a 1D or rows of a 2D numpy array based on specified value range.
Parameters:
- arr (numpy array): The input numpy array to filter.
- start_value (numeric): The lower bound for the filtering. Default is 0.
- stop_value (numeric): The upper bound for the filtering. Default is 1000000.
Returns:
- numpy array: A numpy array containing only the filtered elements or rows.
Raises:
- ValueError: If the input array has more than two dimensions.
"""
result = np.array(arr)
if result.ndim == 1:
# Apply filter for a 1D array
mask = (result > start_value) & (result < stop_value)
return result[mask], mask
elif result.ndim == 2:
# Apply filter based on the first column for a 2D array
mask = (result[:, 0] > start_value) & (result[:, 0] < stop_value)
return result[mask], mask
else:
raise ValueError("The input array must be either 1D or 2D.")
def helper_combine_grouped_rows(df, array_columns):
"""
Combine rows within groups of a DataFrame. Uses the `overlay_arrays` for specified columns
and takes the first instance for other columns.
Parameters:
- df (pd.DataFrame): DataFrame to process.
- array_columns (list): List of column names in `df` that contain array values to be combined using `overlay_arrays`.
Returns:
- pd.DataFrame: DataFrame after combining rows within groups.
"""
def custom_aggregator(x):
if x.name in array_columns:
# Reduce the column by overlaying arrays
return x.dropna().aggregate(lambda arrays: arrays.reduce(helper_overlay_arrays))
else:
# For other columns, simply return the first element
return x.iloc[0]
# Apply the custom aggregator to each column individually
return df.groupby(df.index).aggregate(custom_aggregator)
def helper_extract_start_stop_elements(array, start_index=0, stop_index=-1):
"""
Extracts elements from an array at specified start and stop indices.
Parameters:
- array (list or array-like): The array from which elements are to be extracted.
- start_index (int): The index of the start element. Default is 0.
- stop_index (int): The index of the stop element. Default is -1, which corresponds to the last element.
Returns:
- tuple: A tuple containing the elements at the start and stop indices.
If the stop_index is out of the array's range, it defaults to the last element of the array.
"""
if stop_index >= len(array) or stop_index < 0:
stop_index = -1 # Ensure the stop_index points to the last element if it's out of range
return array[start_index], array[stop_index]
def helper_overlay_arrays(array1, array2):
"""
Overlays two 2D NumPy arrays of the same shape, preferring non-NaN values from the first array.
If both arrays have a non-NaN value at the same position, the value from the first array is used.
Parameters:
- array1 (np.ndarray): The primary 2D array.
- array2 (np.ndarray): The secondary 2D array, used only where array1 has NaNs.
Returns:
- np.ndarray: A 2D array composed of the overlaid results of array1 and array2.
Raises:
- ValueError: If `array1` and `array2` do not have the same shape.
"""
if array1.shape != array2.shape:
raise ValueError("Both arrays must have the same shape.")
# Create a copy of the first array to ensure that no changes are made to
# the original
result = np.copy(array1)
# Find indices where array1 is NaN and array2 is not NaN
mask = np.isnan(array1) & ~np.isnan(array2)
# Place non-NaN values from array2 where array1 has NaNs
result[mask] = array2[mask]
return result
def helper_mask_slices(array_2d, slice_index):
"""
Masks elements outside a specified slice in a 2D array with NaN.
Parameters:
- array_2d (np.ndarray): The input 2D array to mask.
- slice_index (tuple): A tuple of two integers that specifies the start and end indices
of the slice to retain. The elements outside this slice are set to NaN.
Returns:
- np.ndarray: A 2D array with elements outside the specified slice set to NaN.
Raises:
- ValueError: If `slice_index` is not a tuple or does not contain exactly two elements.
- IndexError: If the slice indices are out of the array bounds.
"""
if not isinstance(slice_index, tuple) or len(slice_index) != 2:
raise ValueError(
"slice_index must be a tuple of two integers (start, end).")
try:
result = array_2d.copy()
mask_2d = np.ones(result.shape, dtype=bool)
mask_2d[slice_index[0]:slice_index[1]] = False
# Set values outside the defined slice to NaN
result[mask_2d] = np.nan
return result
except IndexError as e:
warnings.warn(f"Slice index out of bounds: {e}")
return np.nan
except Exception as e:
warnings.warn(f"An error occurred while masking the array: {e}")
return np.nan
def helper_filter_by_timestamp_range(start, stop, timestamps, items):
"""
Filters an array of timestamps and corresponding items based on a timestamp range.
Parameters:
- start (int or float): The start of the timestamp range.
- stop (int or float): The end of the timestamp range.
- timestamps (numpy.ndarray): A sorted array of timestamps.
- items (numpy.ndarray): An array of items corresponding to the timestamps.
Returns:
- tuple: Two numpy.ndarrays, the filtered timestamps and the corresponding items.
"""
# Create a boolean mask for the timestamps within the range
mask = (timestamps >= start) & (timestamps <= stop)
# Apply the mask to the timestamps
filtered_timestamps = timestamps[mask]
# Apply the mask to the items, adjusting the length if necessary
if len(items) > len(mask):
# If items is longer than mask, shorten items
filtered_items = items[:len(mask)][mask]
elif len(items) < len(mask):
# If items is shorter than mask, pad items with NaNs
padded_items = np.pad(
items, (0, len(mask) - len(items)), constant_values=np.nan)
filtered_items = padded_items[mask]
else:
# If items and mask are the same length, just apply the mask
filtered_items = items[mask]
return filtered_timestamps, filtered_items
def helper_find_nearest_indices(array1, array2):
"""
Finds the indices of the elements in array2 that are nearest to the elements in array1.
This function flattens array1 and for each number in the flattened array, finds the index of the
number in array2 that is nearest to it. The indices are then reshaped to match the shape of array1.
Parameters:
- array1 (numpy.ndarray): The array to find the nearest numbers to.
- array2 (numpy.ndarray): The array to find the nearest numbers in.
Returns:
- numpy.ndarray: An array of the same shape as array1, containing the indices of the nearest numbers
in array2 to the numbers in array1.
"""
array1_flat = array1.flatten()
indices = np.array([np.abs(array2 - num).argmin() for num in array1_flat])
return indices.reshape(array1.shape)
def helper_generate_pairs(lst):
"""
Generates all unique pairs from a list.
Parameters:
- lst (list): The list to generate pairs from.
Returns:
- list: A list of tuples, each containing a unique pair from the input list.
"""
n = len(lst)
return [(lst[i], lst[j]) for i in range(n) for j in range(i + 1, n)]
def helper_update_array_by_mask(array, mask, value=np.nan):
"""
Update elements of an array based on a mask and replace them with a specified value.
Parameters:
- array (np.array): The input numpy array whose values are to be updated.
- mask (np.array): A boolean array with the same shape as `array`. Elements of `array` corresponding to True in the mask are replaced.
- value (scalar, optional): The value to assign to elements of `array` where `mask` is True. Defaults to np.nan.
Returns:
- np.array: A copy of the input array with updated values where the mask is True.
Example:
array = np.array([1, 2, 3, 4])
mask = np.array([False, True, False, True])
update_array_by_mask(array, mask, value=0)
array([1, 0, 3, 0])
"""
result = array.copy()
result[mask] = value
return result
def helper_compute_velocity(node_loc, window_size=25, polynomial_order=3):
"""
Calculate the velocity of tracked nodes from pose data.
The function utilizes the Savitzky-Golay filter to smooth the data and compute the velocity.
Parameters:
----------
node_loc : numpy.ndarray
The location of nodes, represented as an array of shape [frames, 2].
Each row represents x and y coordinates for a particular frame.
window_size : int, optional
The size of the window used for the Savitzky-Golay filter.
Represents the number of consecutive data points used when smoothing the data.
Default is 25.
polynomial_order : int, optional
The order of the polynomial fit to the data within the Savitzky-Golay filter window.
Default is 3.
Returns:
-------
numpy.ndarray
The velocity for each frame, calculated from the smoothed x and y coordinates.
"""
node_loc_vel = np.zeros_like(node_loc)
# For each coordinate (x and y), smooth the data and calculate the
# derivative (velocity)
for c in range(node_loc.shape[-1]):
node_loc_vel[:, c] = savgol_filter(
node_loc[:, c], window_size, polynomial_order, deriv=1)
# Calculate the magnitude of the velocity vectors for each frame
node_vel = np.linalg.norm(node_loc_vel, axis=1)
return node_vel
def get_sleap_tracks_from_h5(filename):
"""
Retrieve pose tracking data (tracks) from a SLEAP-generated h5 file.
This function is intended for use with Pandas' apply method on columns containing filenames.
Parameters:
----------
filename : str
Path to the SLEAP h5 file containing pose tracking data.
Returns:
-------
np.ndarray
A transposed version of the 'tracks' dataset in the provided h5 file.
Example:
--------
df['tracks'] = df['filename_column'].apply(get_sleap_tracks_from_h5)
"""
with h5py.File(filename, "r") as f:
return f["tracks"][:].T
def get_node_names_from_sleap(filename):
"""
Retrieve node names from a SLEAP h5 file.
Parameters:
- filename (str): Path to the SLEAP h5 file.
Returns:
- list of str: List of node names.
"""
with h5py.File(filename, "r") as f:
return [n.decode() for n in f["node_names"][:]]
def fill_missing(Y, kind="linear"):
"""Fills missing values independently along each dimension after the first."""
# Store initial shape.
initial_shape = Y.shape
# Flatten after first dim.
Y = Y.reshape((initial_shape[0], -1))
# Interpolate along each slice.
for i in range(Y.shape[-1]):
y = Y[:, i]
# Build interpolant.
x = np.flatnonzero(~np.isnan(y))
f = interp1d(x, y[x], kind=kind, fill_value=np.nan, bounds_error=False)
# Fill missing
xq = np.flatnonzero(np.isnan(y))
y[xq] = f(xq)
# Fill leading or trailing NaNs with the nearest non-NaN values
mask = np.isnan(y)
y[mask] = np.interp(np.flatnonzero(
mask), np.flatnonzero(~mask), y[~mask])
# Save slice
Y[:, i] = y
# Restore to initial shape.
Y = Y.reshape(initial_shape)
return Y
def compute_velocity(node_loc, window_size=25, polynomial_order=3):
"""
Calculate the velocity of tracked nodes from pose data.
The function utilizes the Savitzky-Golay filter to smooth the data and compute the velocity.
Parameters:
----------
node_loc : numpy.ndarray
The location of nodes, represented as an array of shape [frames, 2].
Each row represents x and y coordinates for a particular frame.
window_size : int, optional
The size of the window used for the Savitzky-Golay filter.
Represents the number of consecutive data points used when smoothing the data.
Default is 25.
polynomial_order : int, optional
The order of the polynomial fit to the data within the Savitzky-Golay filter window.
Default is 3.
Returns:
-------
numpy.ndarray
The velocity for each frame, calculated from the smoothed x and y coordinates.
"""
node_loc_vel = np.zeros_like(node_loc)
# For each coordinate (x and y), smooth the data and calculate the
# derivative (velocity)
for c in range(node_loc.shape[-1]):
node_loc_vel[:, c] = savgol_filter(
node_loc[:, c], window_size, polynomial_order, deriv=1)
# Calculate the magnitude of the velocity vectors for each frame
node_vel = np.linalg.norm(node_loc_vel, axis=1)
return node_vel
def extract_sleap_data(filename):
"""
Extracts coordinates, names of body parts, and track names from a SLEAP file.
Parameters:
- filename (str): Path to the SLEAP file.
Returns:
- tuple: A tuple containing the following elements:
* locations (numpy.ndarray): Array containing the coordinates.
* node_names (list of str): List of body part names.
* track_names (list of str): List of track names.
Example: locations, node_names, track_names = extract_sleap_data("path/to/sleap/file.h5")
"""
result = {}
with h5py.File(filename, "r") as f:
result["locations"] = f["tracks"][:].T
result["node_names"] = [n.decode() for n in f["node_names"][:]]
result["track_names"] = [n.decode() for n in f["track_names"][:]]
return result
def rescale_dimension_in_array(arr, dimension=0, ratio=1):
"""
Rescale values of a specified dimension in a 3D numpy array for the entire array.
Parameters:
- arr (numpy.ndarray): A 3D numpy array where the third dimension is being rescaled.
- dimension (int, default=0): Specifies which dimension (0 or 1) of the third
dimension in the array should be rescaled.
For instance, in many contexts:
0 represents the x-coordinate,
1 represents the y-coordinate.
- ratio (float, default=1): The scaling factor to be applied.
Returns:
- numpy.ndarray: The rescaled array.
"""
arr[:, :, dimension] *= ratio
return arr
def convert_to_mp4(experiment_dir):
"""
Converts .h264 files to .mp4 files using the bash script convert_to_mp4.sh
convert_to_mp4.sh should exist in the same directory as this script.
Args:
experiment_dir (String): Path to the experiment directory containing subdirectories with .h264 files.
For example, if your experiment contains the following subdirectories:
/path/to/experiment/trial1
/path/to/experiment/trial2
Your experiment_dir should be /path/to/experiment.
Returns:
None
"""
bash_path = "./convert_to_mp4.sh"
subprocess.run([bash_path, experiment_dir])
def extract_all_trodes(input_dir):
"""
Args:
input_dir (String): Path containing the session directories to process.
Returns:
session_to_trodes_data (defaultdict): A nested dictionary containing the metadata for each session.
"""
def recursive_dict():
return defaultdict(recursive_dict)
session_to_trodes_data = recursive_dict()
session_to_path = {}
# This loop will process each session directory using the trodes extract functions and store the metadata in a
# nested dictionary.
for session in glob.glob(input_dir):
try:
session_basename = os.path.splitext(os.path.basename(session))[0]
print("Processing session: ", session_basename)
session_to_trodes_data[session_basename] = trodes.read_exported.organize_all_trodes_export(
session)
session_to_path[session_basename] = session
except Exception as e:
print("Error processing session: ", session_basename)
print(e)
# print(session_to_trodes_data)
return session_to_trodes_data, session_to_path
def add_video_timestamps(session_to_trodes_data, directory_path):
"""
Args:
session_to_trodes_data (Nested Dictionary): Generate from extract_all_trodes.
directory_path (String): Path containing the session directories to process.
Returns:
session_to_trodes_data (Nested Dictionary): A nested dictionary containing the metadata for each session.
"""
# Loops through each session and video_timestamps file and adds the timestamps to the session_to_trodes_data
# dictionary. Timestamp array is generated using the read_trodes_extracted_data_file function from the
# trodes.read_exported module.
for session in glob.glob(directory_path):
try:
session_basename = os.path.splitext(os.path.basename(session))[0]
print("Current Session: {}".format(session_basename))
for video_timestamps in glob.glob(
os.path.join(session, "*cameraHWSync")):
video_basename = os.path.basename(video_timestamps)
print("Current Video Name: {}".format(video_basename))
timestamp_array = trodes.read_exported.read_trodes_extracted_data_file(
video_timestamps)
if "video_timestamps" not in session_to_trodes_data[session_basename][session_basename]:
session_to_trodes_data[session_basename][session_basename]["video_timestamps"] = defaultdict(
dict)
session_to_trodes_data[session_basename][session_basename]["video_timestamps"][video_basename.split(
".")[-3]] = timestamp_array
print("Timestamp Array for {}: ".format(video_basename))
print(session_to_trodes_data[session_basename][session_basename]
["video_timestamps"][video_basename.split(".")[-3]]) #TODO: what is video timestamps
except Exception as e:
print("Error processing session: ", session_basename)
print(e)
return session_to_trodes_data
def create_metadata_df(session_to_trodes, session_to_path):
"""
Args:
session_to_trodes (nested dictionary): Generated from extract_all_trodes.
session_to_path (empty dictionary): {}
columns_to_keep (dictionary): Provide a dictionary of the columns to keep in the metadata dataframe.
Returns:
trodes_metadata_df (pandas dataframe): A dataframe containing the metadata for each session.
"""
trodes_metadata_df = pd.DataFrame.from_dict({(i, j, k, l): session_to_trodes[i][j][k][l]
for i in session_to_trodes.keys()
for j in session_to_trodes[i].keys()
for k in session_to_trodes[i][j].keys()
for l in session_to_trodes[i][j][k].keys()},
orient='index')
trodes_metadata_df = trodes_metadata_df.reset_index()
trodes_metadata_df = trodes_metadata_df.rename(
columns={
'level_0': 'session_dir',
'level_1': 'recording',
'level_2': 'metadata_dir',
'level_3': 'metadata_file'},
errors="ignore")
trodes_metadata_df["session_path"] = trodes_metadata_df["session_dir"].map(
session_to_path)
# Adjust data types
#TODO is this nessary?
trodes_metadata_df["first_dtype_name"] = trodes_metadata_df["data"].apply(
lambda x: x.dtype.names[0])
trodes_metadata_df["first_item_data"] = trodes_metadata_df["data"].apply(
lambda x: x[x.dtype.names[0]])
trodes_metadata_df["last_dtype_name"] = trodes_metadata_df["data"].apply(
lambda x: x.dtype.names[-1])
trodes_metadata_df["last_item_data"] = trodes_metadata_df["data"].apply(
lambda x: x[x.dtype.names[-1]])
print("unique recordings ")
print(trodes_metadata_df["recording"].unique())
return trodes_metadata_df
def add_subjects_to_metadata(metadata):
"""
Adds the subjects to the metadata dataframe.
Args:
metadata (pandas dataframe): Generated from create_metadata_df.
Returns:
metadata (pandas dataframe): A dataframe containing the metadata for each session with the subjects added.
"""
# TODO: find a better way to do this without regex on the session_dir
#TODO: this can be fixed when initiallizing the LFP object
metadata["all_subjects"] = metadata["session_dir"].apply(lambda x: x.replace(
"-", "_").split("subj")[-1].split("t")[0].strip("_").replace("_", ".").split(".and."))
metadata["all_subjects"] = metadata["all_subjects"].apply(
lambda x: sorted([i.strip().strip(".") for i in x]))
metadata["current_subject"] = metadata["recording"].apply(lambda x: x.replace(
"-", "_").split("subj")[-1].split("t")[0].strip("_").replace("_", ".").split(".and.")[0])
print(metadata["all_subjects"])
print(metadata["current_subject"])
return metadata
def get_trodes_video_df(trodes_metadata_df):
"""
Extracts the video data from the trodes_metadata_df and calculates the first timestamp for each session.
Args:
trodes_metadata_df (pandas dataframe): Generated from create_metadata_df.
Returns:
trodes_video_df (pandas dataframe): A dataframe containing the video data for each session.
"""
trodes_video_df = trodes_metadata_df[trodes_metadata_df["metadata_dir"]
== "video_timestamps"].copy().reset_index(drop=True)
trodes_video_df = trodes_video_df[trodes_video_df["metadata_file"] == "1"].copy(
)
trodes_video_df["video_timestamps"] = trodes_video_df["first_item_data"]
trodes_video_df = trodes_video_df[[
"filename", "video_timestamps", "session_dir"]].copy()
trodes_video_df = trodes_video_df.rename(
columns={"filename": "video_name"})
print(trodes_video_df.head())
return trodes_video_df
def get_trodes_state_df(trodes_metadata_df):
"""
Extracts the state data from the trodes_metadata_df and calculates the timestamps for each event.
Args:
trodes_metadata_df (pandas dataframe): Generated from create_metadata_df.
Returns:
trodes_state_df (pandas dataframe): A dataframe containing the state data for each session.
"""
trodes_state_df = trodes_metadata_df[trodes_metadata_df["metadata_dir"].isin([
"DIO"])].copy()
trodes_state_df = trodes_metadata_df[trodes_metadata_df["id"].isin(
["ECU_Din1", "ECU_Din2"])].copy()
trodes_state_df["event_indexes"] = trodes_state_df.apply(
lambda x: np.column_stack([np.where(x["last_item_data"] == 1)[
0], np.where(x["last_item_data"] == 1)[0] + 1]),
axis=1)
#TODO: what is event indexes
trodes_state_df["event_indexes"] = trodes_state_df.apply(
lambda x: x["event_indexes"][x["event_indexes"][:, 1] <= x["first_item_data"].shape[0] - 1], axis=1)
trodes_state_df["event_timestamps"] = trodes_state_df.apply(
lambda x: x["first_item_data"][x["event_indexes"]], axis=1)
print(trodes_state_df.head())
return trodes_state_df