-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalignment_code.py
2821 lines (2202 loc) · 117 KB
/
alignment_code.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 os
import glob
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import resample
from scipy.interpolate import interp1d
import xml.etree.ElementTree as ET
import plotly.express as px
import seaborn as sns
from scipy.optimize import curve_fit
from scipy.stats import norm
from scipy.stats import pearsonr
from scipy.stats import spearmanr
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import h5py
import random
#nwb imports for additins to the nwb
from pynwb import NWBHDF5IO
from pynwb.ophys import RoiResponseSeries, DfOverF
import tables
#%%
#nwb imports
#%%
from datetime import datetime
from dateutil import tz
from pathlib import Path
from neuroconv.datainterfaces import Suite2pSegmentationInterface, CsvTimeIntervalsInterface
from neuroconv.tools.roiextractors import roiextractors
import data_import as di #from pycoontrol ulitity functions
#%%
def correct_align_and_add_orientations(session_df, xml_file_path, fluorescence_df):
#grab photodector times from sesh_df
photodetector_times = session_df[session_df['name'] == 'photodetector']['time'].values
#func to find closest photodector time for strt times
def find_nearest_photodetector_time(reference_time, time_range=300):
potential_times = photodetector_times[(photodetector_times >= reference_time - time_range) &
(photodetector_times <= reference_time + time_range)]
return potential_times[np.argmin(np.abs(potential_times - reference_time))] if len(potential_times) > 0 else reference_time
#same idea but for the stop times
def find_distant_photodetector_time(reference_time, time_range=500):
potential_times = photodetector_times[(photodetector_times >= reference_time - time_range) &
(photodetector_times <= reference_time + time_range)]
return potential_times[np.argmax(np.abs(potential_times - reference_time))] if len(potential_times) > 0 else reference_time
#clear out nans in 'name' col
session_df['name'] = session_df['name'].fillna('')
#get rows that start with degrees_ for orientation
degree_states = session_df[session_df['name'].str.startswith('degrees_')].copy()
#make a dict for corrected times for the degree states
corrected_times_dict = {}
for _, row in degree_states.iterrows():
state_name = row['name']
start_time = row['time']
stop_time = start_time + row['duration']
#fix the start&stop based on photodetector
corrected_start_time = find_nearest_photodetector_time(start_time)
corrected_stop_time = find_distant_photodetector_time(stop_time)
#throw it in the dict
if state_name not in corrected_times_dict:
corrected_times_dict[state_name] = []
corrected_times_dict[state_name].append((corrected_start_time, corrected_stop_time))
#load up the xml to get frame details
xml = ET.parse(xml_file_path)
root = xml.getroot()
sequenceElement = root.find('Sequence')
frameElements = [frameElement for frameElement in sequenceElement.iter('Frame')]
frame_period = float(frameElements[1].get('relativeTime')) - float(frameElements[0].get('relativeTime'))
duration = float(frameElements[-1].get('relativeTime')) + frame_period - float(frameElements[0].get('relativeTime'))
frames = len(frameElements)
frame_relative_time = np.arange(0, duration, frame_period)
#figure out the frame nums for the corrected times
key_frames = {}
for state, times in corrected_times_dict.items():
key_frames[state] = []
for start_time, stop_time in times:
start = start_time / 1000 #sec conversion
end = stop_time / 1000 #sec conversion
closest_start = min(frame_relative_time, key=lambda x: abs(x - start))
closest_end = min(frame_relative_time, key=lambda x: abs(x - end))
start_frame = np.where(frame_relative_time == closest_start)[0][0]
end_frame = np.where(frame_relative_time == closest_end)[0][0]
key_frames[state].append((start_frame, end_frame))
#add orientation info to fluorescence df
deltaF_F = fluorescence_df.copy()
#add time col from relative time
print(len(deltaF_F))
deltaF_F['time'] = frame_relative_time[:len(deltaF_F)]
for angle, frame_start_stops in key_frames.items():
deltaF_F[f'{angle}'] = 0
for frame_start_stop in frame_start_stops:
start = frame_start_stop[0]
end = frame_start_stop[1] + 1
deltaF_F.loc[start:end, f'{angle}'] = 1
return deltaF_F
#%%
#def correct_align_and_add_orientations_folder(folder_path, window_size=30, percentile=10, video_fps=20, method='percentile'):
def correct_align_and_add_orientations_folder(*, folder_path, window_size=30, video_fps=20, method='percentile', stable_frames=300, step_size=10, sliding_size=300, percentile_s=10):
#find files by pattern
txt_file_path = glob.glob(os.path.join(folder_path, '*.txt'))[0]
xml_file_path = glob.glob(os.path.join(folder_path, '*.xml'))[0]
speed_file_path = glob.glob(os.path.join(folder_path, '*_Speed.pca'))[0]
direction_file_path = glob.glob(os.path.join(folder_path, '*_Direction.pca'))[0]
#paths for the numpy files
F_path = os.path.join(folder_path, 'F.npy')
print(F_path)
iscell_path = os.path.join(folder_path, 'iscell.npy')
spks_path = os.path.join(folder_path, 'spks.npy')
ops_path = os.path.join(folder_path, 'ops.npy')
Fneu_path = os.path.join(folder_path, 'Fneu.npy')
pupil_csv_path = os.path.join(folder_path, 'pupil_output.csv')
#pycontrol files
session_df = di.session_dataframe(txt_file_path)
#load npy arrays from paths
F = np.load(F_path)
iscell = np.load(iscell_path)
spks = np.load(spks_path)
Fneu = np.load(Fneu_path)
#print(ops_path)
ops = np.load(ops_path, allow_pickle=True)
ops = ops.item()
print("done ops loading")
print(ops_path)
speed_np = di.load_analog_data(speed_file_path)
direction_np = di.load_analog_data(direction_file_path)
print(f"Shape of F: {F.shape}")
print(f"Shape of iscell: {iscell.shape}")
print(f"Shape of spks: {spks.shape}")
print(f"Shape of Fneu: {Fneu.shape}")
#gen the fluorescence DataFrame using the delta_fifty_window function
#fluorescence_data = delta_fify_method_folder_three(F=F, iscell=iscell, spks=spks, Fneu=Fneu, window_size=window_size, percentile_s=percentile, method=method, stable_frames=stable_frames, step_size=step_size, sliding_size=sliding_window_size)
#fluorescence_df = pd.DataFrame(fluorescence_data)
#v4 of the dff calcucaltion from the dec meeting
fluorescence_data, frames_rate = dff_baseline_sliding(F=F, iscell=iscell, spks=spks, Fneu=Fneu, sliding_size=sliding_size, percentile_s=percentile_s, window_size=window_size, step_size=step_size)
fluorescence_df = pd.DataFrame(fluorescence_data)
#grab photodector times from sesh_df
photodetector_times = session_df[session_df['name'] == 'photodetector']['time'].values
#func to find closest photodector time for strt times
def find_nearest_photodetector_time(reference_time, time_range=300):
potential_times = photodetector_times[(photodetector_times >= reference_time - time_range) &
(photodetector_times <= reference_time + time_range)]
return potential_times[np.argmin(np.abs(potential_times - reference_time))] if len(potential_times) > 0 else reference_time
#same idea but for the stop times
def find_distant_photodetector_time(reference_time, time_range=500):
potential_times = photodetector_times[(photodetector_times >= reference_time - time_range) &
(photodetector_times <= reference_time + time_range)]
return potential_times[np.argmax(np.abs(potential_times - reference_time))] if len(potential_times) > 0 else reference_time
#clear out nans in 'name' col
session_df['name'] = session_df['name'].fillna('')
#get rows that start with degrees_ for orientation
degree_states = session_df[session_df['name'].str.startswith('degrees_')].copy()
#make a dict for corrected times for the degree states
corrected_times_dict = {}
for _, row in degree_states.iterrows():
state_name = row['name']
start_time = row['time']
stop_time = start_time + row['duration']
#fix the start&stop based on photodetector
corrected_start_time = find_nearest_photodetector_time(start_time)
corrected_stop_time = find_distant_photodetector_time(stop_time)
#throw it in the dict
if state_name not in corrected_times_dict:
corrected_times_dict[state_name] = []
corrected_times_dict[state_name].append((corrected_start_time, corrected_stop_time))
#load up the xml to get frame details
xml = ET.parse(xml_file_path)
root = xml.getroot()
sequenceElement = root.find('Sequence')
frameElements = [frameElement for frameElement in sequenceElement.iter('Frame')]
frame_period = float(frameElements[1].get('relativeTime')) - float(frameElements[0].get('relativeTime'))
duration = float(frameElements[-1].get('relativeTime')) + frame_period - float(frameElements[0].get('relativeTime'))
frames = len(frameElements)
frame_relative_time = np.arange(0, duration, frame_period)
fs = 1 / frame_period
ops['fs'] = fs
print("done ops")
#save the ops np array as npy file
print(ops_path)
np.save(ops_path, ops)
print("done ops saving")
#figure out the frame nums for the corrected times
key_frames = {}
for state, times in corrected_times_dict.items():
key_frames[state] = []
for start_time, stop_time in times:
start = start_time / 1000 #sec conversion
end = stop_time / 1000 #sec conversion
closest_start = min(frame_relative_time, key=lambda x: abs(x - start))
closest_end = min(frame_relative_time, key=lambda x: abs(x - end))
start_frame = np.where(frame_relative_time == closest_start)[0][0]
end_frame = np.where(frame_relative_time == closest_end)[0][0]
key_frames[state].append((start_frame, end_frame))
#add orientation info to fluorescence df
deltaF_F = fluorescence_df.copy()
#add time col from relative time
deltaF_F['time'] = frame_relative_time[:len(deltaF_F)]
for angle, frame_start_stops in key_frames.items():
deltaF_F[f'{angle}'] = 0
for frame_start_stop in frame_start_stops:
start = frame_start_stop[0]
end = frame_start_stop[1] + 1
deltaF_F.loc[start:end, f'{angle}'] = 1
align_movement_data_to_fluorescence(deltaF_F, speed_np, direction_np)
upsample_and_append_pupil(deltaF_F, xml_file_path, pupil_csv_path, video_fps=video_fps)
deltaF_F.columns = deltaF_F.columns.astype(str)
return deltaF_F
#%%
def simple_align_and_add_orientations_folder(*, folder_path, window_size=30, video_fps=20, method='percentile', stable_frames=300, step_size=10, sliding_size=300, percentile_s=10):
# Find files by pattern
txt_file_path = glob.glob(os.path.join(folder_path, '*.txt'))[0]
xml_file_path = glob.glob(os.path.join(folder_path, '*.xml'))[0]
speed_file_path = glob.glob(os.path.join(folder_path, '*_Speed.pca'))[0]
direction_file_path = glob.glob(os.path.join(folder_path, '*_Direction.pca'))[0]
# Paths for the numpy files
F_path = os.path.join(folder_path, 'F.npy')
iscell_path = os.path.join(folder_path, 'iscell.npy')
spks_path = os.path.join(folder_path, 'spks.npy')
ops_path = os.path.join(folder_path, 'ops.npy')
Fneu_path = os.path.join(folder_path, 'Fneu.npy')
pupil_csv_path = os.path.join(folder_path, 'pupil_output.csv')
# Load session data
#session_df = pd.read_csv(txt_file_path, delimiter='\t') # Adjust as necessary for your data format
session_df = di.session_dataframe(txt_file_path)
# Load numpy arrays
F = np.load(F_path, allow_pickle=True)
iscell = np.load(iscell_path, allow_pickle=True)
spks = np.load(spks_path, allow_pickle=True)
Fneu = np.load(Fneu_path, allow_pickle=True)
ops = np.load(ops_path, allow_pickle=True).item()
# Load analog data
speed_np = di.load_analog_data(speed_file_path)
direction_np = di.load_analog_data(direction_file_path)
# Calculate fluorescence data
fluorescence_data, frames_rate = dff_baseline_sliding(F=F, iscell=iscell, spks=spks, Fneu=Fneu, sliding_size=sliding_size, percentile_s=percentile_s, window_size=window_size, step_size=step_size)
fluorescence_df = pd.DataFrame(fluorescence_data)
# Get rows that start with degrees_ for orientation
session_df['name'] = session_df['name'].fillna('')
degree_states = session_df[session_df['name'].str.startswith('degrees_')].copy()
# Use XML to get frame details
xml = ET.parse(xml_file_path)
root = xml.getroot()
sequenceElement = root.find('Sequence')
frameElements = [frameElement for frameElement in sequenceElement.iter('Frame')]
frame_period = float(frameElements[1].get('relativeTime')) - float(frameElements[0].get('relativeTime'))
duration = float(frameElements[-1].get('relativeTime')) + frame_period - float(frameElements[0].get('relativeTime'))
frames = len(frameElements)
frame_relative_time = np.arange(0, duration, frame_period)
# Set fs in ops and save
fs = 1 / frame_period
ops['fs'] = fs
np.save(ops_path, ops)
# Determine the frame numbers for the times
key_frames = {}
for _, row in degree_states.iterrows():
state_name = row['name']
start_time = row['time'] / 1000 # Convert ms to seconds
end_time = start_time + row['duration'] / 1000 # Convert ms to seconds
start_frame = np.searchsorted(frame_relative_time, start_time, side='left')
end_frame = np.searchsorted(frame_relative_time, end_time, side='right') - 1
if state_name not in key_frames:
key_frames[state_name] = []
key_frames[state_name].append((start_frame, end_frame))
# Add orientation info to fluorescence dataframe
for angle, frame_start_stops in key_frames.items():
fluorescence_df[f'{angle}'] = 0
for start, end in frame_start_stops:
fluorescence_df.loc[start:end, f'{angle}'] = 1
return fluorescence_df
# %%
def align_movement_data_to_fluorescence(fl_df, speed_npy, direction_npy):
#first cols timestamp, second is the data
speed_timestamps = speed_npy[:, 0]
speed_samples = speed_npy[:, 1]
direction_timestamps = direction_npy[:, 0]
direction_samples = direction_npy[:, 1]
#gotta resample to match the df rate
num_target_samples = int(fl_df.shape[0])
#resample the speed and dir
resampled_speed = resample(speed_samples, num_target_samples)
resampled_direction = resample(direction_samples, num_target_samples)
#stick the new cols on df
fl_df['speed'] = resampled_speed
fl_df['direction'] = resampled_direction
return fl_df
# %%
#parses frame deetails from the xml
def get_frame_details(xml_file_path):
xml = ET.parse(xml_file_path)
root = xml.getroot()
sequenceElement = root.find('Sequence')
frameElements = [frameElement for frameElement in sequenceElement.iter('Frame')]
frame_period = float(frameElements[1].get('relativeTime')) - float(frameElements[0].get('relativeTime'))
duration = float(frameElements[-1].get('relativeTime')) + frame_period - float(frameElements[0].get('relativeTime'))
frames = len(frameElements)
frame_relative_time = np.arange(0, duration, frame_period)
return {"frame_period": frame_period, "session_duration": duration, "total_frames": frames, "frame_relative_time": frame_relative_time}
#upsamples and appends pupil data, gotta match the frames
def upsample_and_append_pupil_depr(target_csv_df, xml_file_path, pupil_csv_path, video_fps, delay=0.03):
#load pupil data
pupil_df = pd.read_csv(pupil_csv_path)
#assuming pupil's in 'processedPupil'
original_data = pupil_df['processedPupil'].values
original_rate = video_fps #video fps
original_timestamps = np.arange(0, len(original_data)/original_rate, 1/original_rate)
#get frame info frm xml
frame_details = get_frame_details(xml_file_path)
target_rate = 1 / frame_details['frame_period'] #target fps
#interp to fit the target
interpolation_function = interp1d(original_timestamps, original_data, kind='linear', fill_value="extrapolate")
target_timestamps = frame_details['frame_relative_time'] + delay
upsampled_data = interpolation_function(target_timestamps)
#slap it onto the df
target_csv_df['pupil_size'] = upsampled_data
return target_csv_df
# accounts for the difference in index after interpolation
#%%
def upsample_and_append_pupil(target_csv_df, xml_file_path, pupil_csv_path, video_fps, fill_initial_30ms_with_mean=True):
# Load the pupil CSV
pupil_df = pd.read_csv(pupil_csv_path)
# Assuming the pupil data is in a column named 'processedPupil'
original_data = pupil_df['processedPupil'].values
original_rate = video_fps # Original sampling rate of the video
original_timestamps = np.arange(0, len(original_data)/original_rate, 1/original_rate)
# Get frame details from the XML file
frame_details = get_frame_details(xml_file_path)
target_rate = 1 / frame_details['frame_period'] # Target sampling rate
# Calculate the number of points equivalent to 30ms in the target rate
num_points_30ms = int(np.ceil(0.03 * target_rate))
# Calculate the mean of the original pupil data
mean_pupil_size = np.mean(original_data)
# If we want to fill the initial 30ms with the mean value
if fill_initial_30ms_with_mean:
# Fill the first equivalent of 30ms with the mean value
original_data[:num_points_30ms] = mean_pupil_size
# Interpolate the pupil data to the target rate
interpolation_function = interp1d(original_timestamps, original_data, kind='linear', fill_value="extrapolate")
target_timestamps = frame_details['frame_relative_time']
print(target_timestamps)
upsampled_data = interpolation_function(target_timestamps)
# Adjust the length of upsampled_data to match target_csv_df
if len(upsampled_data) > len(target_csv_df):
# If upsampled_data is longer, trim it
upsampled_data = upsampled_data[:len(target_csv_df)]
elif len(upsampled_data) < len(target_csv_df):
# If upsampled_data is shorter, pad it with the mean value
mean_value = np.mean(upsampled_data)
padding_length = len(target_csv_df) - len(upsampled_data)
padding = np.full(padding_length, mean_value)
upsampled_data = np.concatenate([upsampled_data, padding])
# Append the upsampled data to the target dataframe
target_csv_df['pupil_size'] = upsampled_data
return target_csv_df
# %%
#takes npy files, does deltaF/F
def delta_fify_window(F, iscell, spks, Fneu, window_size=30, percentile=10):
#only take cells marked '1'
Fofiscell = F[iscell[:, 0] == 1, :]
Fneuofiscell = Fneu[iscell[:, 0] == 1, :]
Spksofiscell = spks[iscell[:, 0] == 1, :]
#correct for neuropil
correctedFofiscell = Fofiscell - 0.7 * Fneuofiscell
correctedFofiscell = np.transpose(correctedFofiscell)
#make dFF array
dFF = np.zeros(correctedFofiscell.shape)
Spksofiscell = np.transpose(Spksofiscell)
Fofiscell = np.transpose(Fofiscell)
#loop thru and calc dFF
for i in range(Fofiscell.shape[1]):
#smooth it out with running avg
filteredtrace = np.convolve(correctedFofiscell[:, i], np.ones(window_size) / window_size, mode='same')
#baseline as 10th percentile
bl = np.percentile(filteredtrace, percentile)
dFF[:, i] = (filteredtrace - bl) / bl
return dFF
#sliding window dff calcucaltion code with center of the window #after meetign in dec23
def dff_baseline_sliding(F, iscell, Fneu, spks, window_size=30, sliding_size=1800, percentile_s=10, step_size=10):
#fucn to fill the zeros with last value for padding
def fill_zeros_with_last(arr):
mask = arr > 0
arr = np.where(mask, arr, np.maximum.accumulate(mask * arr))
return arr
#only take cells marked '1'
Fofiscell = F[iscell[:, 0] == 1, :]
Fneuofiscell = Fneu[iscell[:, 0] == 1, :]
#correct for neuropil
correctedFofiscell = Fofiscell - 0.7 * Fneuofiscell
correctedFofiscell = np.transpose(correctedFofiscell)
#make dFF array
dFF = np.zeros(correctedFofiscell.shape)
baseline = None
#loop thru and calc dFF
for i in range(correctedFofiscell.shape[1]):
neuron_trace = np.convolve(correctedFofiscell[:, i], np.ones(window_size) / window_size, mode='same')
baseline = np.zeros_like(neuron_trace)
#print(range(len(neuron_trace) - sliding_size + 1))
#baseline as sliding window
half_sliding_size = sliding_size // 2
for j in range(half_sliding_size, len(neuron_trace) - half_sliding_size + 1, step_size):
#print(j)
start = max(0, j - half_sliding_size)
end = min(len(neuron_trace), j + half_sliding_size)
baseline[start:end] = np.percentile(neuron_trace[start:end], percentile_s)
#print(baseline[start:end])
pad_width = sliding_size // 2
####*** fill the remiahng with prior values but dsiregard the last value for next calcution
neuron_trace_padded = np.pad(neuron_trace, (pad_width, pad_width), mode='edge') #
baseline_padded = np.pad(baseline, (pad_width, pad_width), mode='edge')
baseline_padded = fill_zeros_with_last(baseline_padded)
dFF[:, i] = (neuron_trace_padded[pad_width:-pad_width] - baseline_padded[pad_width:-pad_width]) / baseline_padded[pad_width:-pad_width]
return dFF, baseline
def dff_baseline_sliding(F, iscell, Fneu, spks, window_size=30, sliding_size=1800, percentile_s=10, step_size=10):
# Function to fill the zeros with last value for padding
def fill_zeros_with_last(arr):
mask = arr > 0
arr = np.where(mask, arr, np.maximum.accumulate(mask * arr))
return arr
# Only take cells marked '1'
Fofiscell = F[iscell[:, 0] == 1, :]
Fneuofiscell = Fneu[iscell[:, 0] == 1, :]
# Correct for neuropil
correctedFofiscell = Fofiscell - 0.7 * Fneuofiscell
correctedFofiscell = np.transpose(correctedFofiscell)
# Make dFF array
dFF = np.zeros(correctedFofiscell.shape)
baseline = None
# Loop through and calculate dFF
for i in range(correctedFofiscell.shape[1]):
neuron_trace = np.convolve(correctedFofiscell[:, i], np.ones(window_size) / window_size, mode='same')
baseline = np.zeros_like(neuron_trace)
# Baseline as sliding window
half_sliding_size = sliding_size // 2
for j in range(half_sliding_size, len(neuron_trace) - half_sliding_size + 1, step_size):
start = max(0, j - half_sliding_size)
end = min(len(neuron_trace), j + half_sliding_size)
baseline[start:end] = np.percentile(neuron_trace[start:end], percentile_s)
pad_width = sliding_size // 2
# Fill the remaining with prior values but disregard the last value for next calculation
neuron_trace_padded = np.pad(neuron_trace, (pad_width, pad_width), mode='edge')
baseline_padded = np.pad(baseline, (pad_width, pad_width), mode='edge')
baseline_padded = fill_zeros_with_last(baseline_padded)
dFF[:, i] = (neuron_trace_padded[pad_width:-pad_width] - baseline_padded[pad_width:-pad_width]) / baseline_padded[pad_width:-pad_width]
# Rescale the responses between 0 and 100
dFF[:, i] = (dFF[:, i] - np.min(dFF[:, i])) / (np.max(dFF[:, i]) - np.min(dFF[:, i])) * 100
return dFF, baseline
#%% test
def delta_fify_method_update(session_folder="None", F=None, iscell=None, spks=None, Fneu=None, method ="percentile", step_size=10, percentile_s=10, stable_frames=300, window_size=30, sliding_size=1800):
"""
Calculate the delta F/F values for each cell in a given session.
Parameters:
session_folder (str): The path to the folder containing the session data.
method (str, optional): The method to calculate the baseline. Defaults to 'percentile'.
percentile (int, optional): The percentile used to calculate the baseline when method is 'percentile'. Defaults to 10.
stable_frames (int, optional): The number of stable frames used to calculate the baseline when method is 'stable_baseline'. Defaults to 300.
window_size (int, optional): The size of the window used for smoothing the data. Defaults to 30.
Returns:
np.ndarray: The delta F/F values for each cell in the session.
"""
# Only take cells marked '1'
Fofiscell = F[iscell[:, 0] == 1, :]
Fneuofiscell = Fneu[iscell[:, 0] == 1, :]
Spksofiscell = spks[iscell[:, 0] == 1, :]
# Correct for neuropil
correctedFofiscell = Fofiscell - 0.7 * Fneuofiscell
correctedFofiscell = np.transpose(correctedFofiscell)
# Make dFF array
dFF = np.zeros(correctedFofiscell.shape)
# Loop through and calculate dFF
for i in range(correctedFofiscell.shape[1]):
# Smooth it out with running avg
filteredtrace = np.convolve(correctedFofiscell[:, i], np.ones(window_size) / window_size, mode='same')
if method == 'percentile':
# Baseline as specified percentile
bl = np.percentile(filteredtrace, percentile_s)
elif method == 'stable_baseline':
# Baseline as mean of the first 'stable_frames' frames
bl = np.mean(filteredtrace[:stable_frames])
elif method == 'sliding':
#neuron_trace = correctedFofiscell[:, i]
neuron_trace = np.convolve(correctedFofiscell[:, i], np.ones(window_size) / window_size, mode='same')
baseline = np.zeros_like(neuron_trace)
pad_width = sliding_size // 2
#pad_width = (pad_width, 0)
neuron_trace = np.pad(neuron_trace, (pad_width, pad_width), mode='edge') #
baseline = np.pad(baseline, (pad_width, pad_width), mode='edge')
#baseline as sliding window
half_sliding_size = sliding_size // 2
for j in range(half_sliding_size, len(neuron_trace) - half_sliding_size + 1, step_size):
# print(j)
start = max(0, j - half_sliding_size)
end = min(len(neuron_trace), j + half_sliding_size)
baseline[start:end] = np.percentile(neuron_trace[start:end], percentile_s)
filteredtrace = neuron_trace[pad_width:-pad_width]
bl = baseline[pad_width:-pad_width]
else:
raise ValueError("Invalid method. Choose 'percentile' or 'stable_baseline'.")
dFF[:, i] = (filteredtrace - bl) / bl
return dFF
#%%
def delta_fify_method_folder_three(session_folder="None", F=None, iscell=None, spks=None, Fneu=None, method ="percentile", percentile_s=10, stable_frames=300, window_size=30, sliding_size=1800, step_size=10):
# Only take cells marked '1'
Fofiscell = F[iscell[:, 0] == 1, :]
Fneuofiscell = Fneu[iscell[:, 0] == 1, :]
# Correct for neuropil
correctedFofiscell = Fofiscell - 0.7 * Fneuofiscell
correctedFofiscell = np.transpose(correctedFofiscell)
# Make array for final data (dFF or smoothed raw fluorescence)
final_data = np.zeros(correctedFofiscell.shape)
# Loop through and calculate dFF or return smoothed raw fluorescence
for i in range(correctedFofiscell.shape[1]):
# Smooth it out with running avg
if window_size == 0:
Fofiscell_raw = np.transpose(Fofiscell)
smoothed_trace = Fofiscell_raw[:, i]
else:
smoothed_trace = np.convolve(correctedFofiscell[:, i], np.ones(window_size) / window_size, mode='same')
if method == 'percentile':
# Baseline as specified percentile
bl = np.percentile(smoothed_trace, percentile_s)
final_data[:, i] = (smoothed_trace - bl) / bl
elif method == 'stable_baseline':
# Baseline as mean of the specified frames, or all frames if stable_frames is -1
baseline_frames = smoothed_trace if stable_frames == -1 else smoothed_trace[:stable_frames]
bl = np.mean(baseline_frames)
final_data[:, i] = (smoothed_trace - bl) / bl
elif method == 'raw':
# Return smoothed raw fluorescence
final_data[:, i] = smoothed_trace
elif method == 'sliding':
final_data, baseline_discard = dff_baseline_sliding_2(F=F, iscell=iscell, spks=spks, Fneu=Fneu, window_size=30, percentile_s=20, step_size=10, sliding_size=1800)
break
#final_data[:, i] = (neuron_trace[pad_width:-pad_width] - baseline[pad_width:-pad_width]) / baseline[pad_width:-pad_width]
return final_data
#%%
def plot_stimulus_responses(csv_file_path):
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Load the data
fluorescence_data = pd.read_csv(csv_file_path)
fluorescence_data.columns = fluorescence_data.columns.astype(str)
# Assuming uniform frame rate
time_per_frame = fluorescence_data['time'][1] - fluorescence_data['time'][0]
frame_rate = 1 / time_per_frame # Frames per second if time is in seconds
# Calculate the number of frames for 2 seconds before and 4 seconds after the stimulus presentation
frames_before = int(2 * frame_rate)
frames_after = int(4 * frame_rate)
# Define stimuli
stimuli = ['degrees_0', 'degrees_45', 'degrees_90', 'degrees_135', 'degrees_180', 'degrees_225', 'degrees_270', 'degrees_315']
# Initialize a figure
plt.figure(figsize=(20, 15))
for i, stimulus in enumerate(stimuli, 1):
stimulus_times = fluorescence_data.index[fluorescence_data[stimulus] == 1].tolist()
# Aggregate ROI responses for each stimulus
aggregated_responses = []
for time in stimulus_times:
start = max(time - frames_before, 0)
end = min(time + frames_after, len(fluorescence_data))
# Mean across all ROI columns (first 100 columns are assumed to be ROIs)
response = fluorescence_data.iloc[start:end, :100].mean(axis=1)
aggregated_responses.append(response)
# Calculate the mean of aggregated responses across all similar stimuli presentations
if aggregated_responses:
mean_response = pd.concat(aggregated_responses, axis=1).mean(axis=1)
time_axis = np.linspace(-2, 4, len(mean_response))
plt.subplot(4, 2, i)
plt.plot(time_axis, mean_response)
plt.title(f'Mean Response for {stimulus}')
plt.xlabel('Time from stimulus onset (s)')
plt.ylabel('Mean ΔF/F (%)')
plt.tight_layout()
plt.suptitle('Aggregated Mean Responses of All ROIs to Different Stimuli')
plt.show()
#test code
# center of the window
def dff_baseline_sliding_folder(folder_path, window_size=30, sliding_size=1800, percentile_s=10, step_size=10):
##paths for the numpy files
F_path = os.path.join(folder_path, 'F.npy')
iscell_path = os.path.join(folder_path, 'iscell.npy')
spks_path = os.path.join(folder_path, 'spks.npy')
Fneu_path = os.path.join(folder_path, 'Fneu.npy')
#load npy arrays from paths
F = np.load(F_path)
iscell = np.load(iscell_path)
spks = np.load(spks_path)
Fneu = np.load(Fneu_path)
#only take cells marked '1'
Fofiscell = F[iscell[:, 0] == 1, :]
Fneuofiscell = Fneu[iscell[:, 0] == 1, :]
#correct for neuropil
correctedFofiscell = Fofiscell - 0.7 * Fneuofiscell
correctedFofiscell = np.transpose(correctedFofiscell)
#print(correctedFofiscell.shape)
#make dFF array
dFF = np.zeros(correctedFofiscell.shape)
baseline = None
#loop thru and calc dFF
for i in range(correctedFofiscell.shape[1]):
#neuron_trace = correctedFofiscell[:, i]
neuron_trace = np.convolve(correctedFofiscell[:, i], np.ones(window_size) / window_size, mode='same')
baseline = np.zeros_like(neuron_trace)
#print(range(len(neuron_trace) - sliding_size + 1))
pad_width = sliding_size // 2
# ###*** fill the remiahng with prior values but dsiregard the last value for next calcution
#if j + sliding_size < len(neuron_trace):
#pad_width = (pad_width, 0)
neuron_trace = np.pad(neuron_trace, (pad_width, pad_width), mode='edge') #
#baseline[j+sliding_size:] = baseline[j+sliding_size-1]
#baseline[j+sliding_size:] = np.pad(baseline, (pad_width, 0), mode='edge')
baseline = np.pad(baseline, (pad_width, pad_width), mode='edge')
#print(f"neuron trace shape {neuron_trace.shape}, baseline shape {baseline.shape}")
#baseline as sliding window
half_sliding_size = sliding_size // 2
for j in range(half_sliding_size, len(neuron_trace) - half_sliding_size + 1, step_size):
# print(j)
start = max(0, j - half_sliding_size)
end = min(len(neuron_trace), j + half_sliding_size)
baseline[start:end] = np.percentile(neuron_trace[start:end], percentile_s)
# print(start,end)
# print(baseline.shape)
#print(f"wihtout padding {neuron_trace[900:-900].shape}")
# print(f"{baseline.shape}")
# plt.plot(neuron_trace, color="blue")
# plt.plot(baseline, color = "yellow")
# plt.show()
# alculate dFF
dFF[:, i] = (neuron_trace[pad_width:-pad_width] - baseline[pad_width:-pad_width]) / baseline[pad_width:-pad_width]
return dFF, baseline
#%%
def dff_baseline_sliding_2(F=None, iscell=None, spks=None, Fneu=None, window_size=30, sliding_size=1800, percentile_s=10, step_size=10):
#only take cells marked '1'
Fofiscell = F[iscell[:, 0] == 1, :]
Fneuofiscell = Fneu[iscell[:, 0] == 1, :]
#correct for neuropil
correctedFofiscell = Fofiscell - 0.7 * Fneuofiscell
correctedFofiscell = np.transpose(correctedFofiscell)
#print(correctedFofiscell.shape)
#make dFF array
dFF = np.zeros(correctedFofiscell.shape)
baseline = None
#loop thru and calc dFF
for i in range(correctedFofiscell.shape[1]):
#neuron_trace = correctedFofiscell[:, i]
neuron_trace = np.convolve(correctedFofiscell[:, i], np.ones(window_size) / window_size, mode='same')
baseline = np.zeros_like(neuron_trace)
#print(range(len(neuron_trace) - sliding_size + 1))
pad_width = sliding_size // 2
# ###*** fill the remiahng with prior values but dsiregard the last value for next calcution
#if j + sliding_size < len(neuron_trace):
#pad_width = (pad_width, 0)
neuron_trace = np.pad(neuron_trace, (pad_width, pad_width), mode='edge') #
#baseline[j+sliding_size:] = baseline[j+sliding_size-1]
#baseline[j+sliding_size:] = np.pad(baseline, (pad_width, 0), mode='edge')
baseline = np.pad(baseline, (pad_width, pad_width), mode='edge')
#print(f"neuron trace shape {neuron_trace.shape}, baseline shape {baseline.shape}")
#baseline as sliding window
half_sliding_size = sliding_size // 2
for j in range(half_sliding_size, len(neuron_trace) - half_sliding_size + 1, step_size):
# print(j)
start = max(0, j - half_sliding_size)
end = min(len(neuron_trace), j + half_sliding_size)
baseline[start:end] = np.percentile(neuron_trace[start:end], percentile_s)
# print(start,end)
# print(baseline.shape)
#print(f"wihtout padding {neuron_trace[900:-900].shape}")
# print(f"{baseline.shape}")
# plt.plot(neuron_trace, color="blue")
# plt.plot(baseline, color = "yellow")
# plt.show()
# alculate dFF
dFF[:, i] = (neuron_trace[pad_width:-pad_width] - baseline[pad_width:-pad_width]) / baseline[pad_width:-pad_width]
return dFF, baseline
#%%
def delta_fify_window_folder(session_folder, window_size=30, percentile=10):
# Function to load .npy files from a given folder
def load_session_data(folder):
F = np.load(os.path.join(folder, 'F.npy'))
iscell = np.load(os.path.join(folder, 'iscell.npy'))
Fneu = np.load(os.path.join(folder, 'Fneu.npy'))
spks = np.load(os.path.join(folder, 'spks.npy'))
return F, iscell, Fneu, spks
# Load data for each session
F, iscell, Fneu, spks = load_session_data(session_folder)
#only take cells marked '1'
Fofiscell = F[iscell[:, 0] == 1, :]
Fneuofiscell = Fneu[iscell[:, 0] == 1, :]
Spksofiscell = spks[iscell[:, 0] == 1, :]
#correct for neuropil
correctedFofiscell = Fofiscell - 0.7 * Fneuofiscell
correctedFofiscell = np.transpose(correctedFofiscell)
#make dFF array
dFF = np.zeros(correctedFofiscell.shape)
Spksofiscell = np.transpose(Spksofiscell)
Fofiscell = np.transpose(Fofiscell)
#loop thru and calc dFF
for i in range(Fofiscell.shape[1]):
#smooth it out with running avg
filteredtrace = np.convolve(correctedFofiscell[:, i], np.ones(window_size) / window_size, mode='same')
#baseline as 10th percentile
bl = np.percentile(filteredtrace, percentile)
dFF[:, i] = (filteredtrace - bl) / bl
return dFF
#%% CHECK THIS
def delta_fify_method_folder(session_folder, method='percentile', percentile=10, stable_frames=300):
# Function to load .npy files from a given folder
def load_session_data(folder):
F = np.load(os.path.join(folder, 'F.npy'))
iscell = np.load(os.path.join(folder, 'iscell.npy'))
Fneu = np.load(os.path.join(folder, 'Fneu.npy'))
spks = np.load(os.path.join(folder, 'spks.npy'))
return F, iscell, Fneu, spks
# Load data for each session
F, iscell, Fneu, spks = load_session_data(session_folder)
# Only take cells marked '1'
Fofiscell = F[iscell[:, 0] == 1, :]
Fneuofiscell = Fneu[iscell[:, 0] == 1, :]
Spksofiscell = spks[iscell[:, 0] == 1, :]
# Correct for neuropil
correctedFofiscell = Fofiscell - 0.7 * Fneuofiscell
correctedFofiscell = np.transpose(correctedFofiscell)
# Make dFF array
dFF = np.zeros(correctedFofiscell.shape)
# Loop through and calculate dFF
for i in range(correctedFofiscell.shape[1]):
if method == 'percentile':
# Baseline as specified percentile
bl = np.percentile(correctedFofiscell[:, i], percentile)
elif method == 'stable_baseline':
# Baseline as mean of the first 'stable_frames' frames
bl = np.mean(correctedFofiscell[:stable_frames, i])
else:
raise ValueError("Invalid method. Choose 'percentile' or 'stable_baseline'.")
dFF[:, i] = (correctedFofiscell[:, i] - bl) / bl
return dFF
#%%
def extract_stimuli_timestamps_modified(dataframe):
"""
Modified function to extract the timestamps of stimuli from the given DataFrame using the 'time' column.
Parameters:
dataframe (pd.DataFrame): DataFrame containing dF/F values, stimuli information, and time column.
Returns:
pd.DataFrame: DataFrame with columns 'stimuli', 'start_time_index', 'stop_time_index', 'start_time', 'stop_time'.
"""
# Identifying columns related to stimuli (degrees_x)
stimuli_columns = [col for col in dataframe.columns if 'degrees_' in str(col)]
# Creating a new DataFrame to store the extracted timestamps
stimuli_df = pd.DataFrame(columns=["stimuli", "start_time_index", "stop_time_index", "start_time", "stop_time"])
# Iterating over each stimuli column to extract start and stop times
for stimuli in stimuli_columns:
# Identifying the start (rising edge) and stop (falling edge) of the stimuli
start_indices = dataframe.index[dataframe[stimuli].diff() == 1].tolist()
stop_indices = dataframe.index[dataframe[stimuli].diff() == -1].tolist()
# Adjust for stimuli starting at the beginning or ending at the end of the recording
if start_indices and start_indices[0] > stop_indices[0]:
start_indices.insert(0, 0)
if stop_indices and (len(stop_indices) < len(start_indices)):
stop_indices.append(dataframe.shape[0] - 1)
# Extracting time values for each start and stop index
for start, stop in zip(start_indices, stop_indices):
start_time = dataframe.loc[start, 'time']
stop_time = dataframe.loc[stop, 'time']
stimuli_df = stimuli_df.append({"stimuli": stimuli,
"start_time_index": start,
"stop_time_index": stop,
"start_time": start_time,
"stop_time": stop_time},
ignore_index=True)
return stimuli_df
#%%
def convert_s2p_to_nwb(folder_path, nwbfile_path, csv_timepoints_path, dffcsv_path):
"""
Convert suite2p data from the suite2p folder continaing plane files to NWB file.
Args:
folder_path (str): The path to the folder containing the data. eg. r"H:\stress\wt\TSeries-07312023-2113-1gp-001\suite2p"
nwbfile_path (str): The path to save the converted NWB file. eg. r"H:\stress\wt\TSeries-07312023-2113-1gp-001\suite2p\output_file5.nwb"
Returns:
None
"""
#ops_file_path = os.path.join(folder_path, "ops.npy")
ops_file_path = folder_path + "\\plane0\\ops.npy"
ops = np.load(ops_file_path, allow_pickle=True).item()
#ops = ops.item()
fs = ops['fs']
#ops['fs'] = 1/frame_period