-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconcatenate_psychometric_curves_v4.py
2517 lines (2143 loc) · 144 KB
/
concatenate_psychometric_curves_v4.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
from datetime import datetime # Only for formating title
import json
import numpy as np
import random
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from ibllib.io.raw_data_loaders import load_data
from one.api import ONE
from matplotlib import colors
import psychofit as psy ### install w/ pip install Psychofit
# from ibl_pipeline import behavior, acquisition, subject
# from ibl_pipeline.analyses.behavior import PsychResultsBlock, PsychResults
from scipy import stats
import re
import sys
sys.path.append('/Users/natemiska/python/bias_coding')
sys.path.append('/Users/natemiska/python/bias_coding/Allen')
# from functions_optostim import signed_contrast, peri_event_time_histogram, generate_pseudo_sessions, isbiasblockselective_03
from metadata_opto_allsessions_B import sessions, find_sessions_by_advanced_criteria
# look at trials+1 for 37 (DLS) to see if bias is still there
#create criteria for minimum bias to accept session
#create criteria for minimum perf in both nonstim and stim trials to accept session
one=ONE(mode='remote')
# one = ONE(mode='local')
# from pathlib import Path
# from one.api import ONE, OneAlyx
# # Local mode with optional access to Alyx methods
# one = ONE(mode='local')
# one.load_cache(cache_dir=Path.home())
# assert isinstance(one, OneAlyx)
# print(one) # One (offline, https://alyx.internationalbrainlab.org)
# # Fully local with no Alyx methods
# one = ONE(cache_dir=Path.home())
# assert not isinstance(one, OneAlyx)
# print(one) # One (offline, C:\Users\User)
###cache_dir = one.cache_dir
###
# # Load with ONE in local mode
# save_dir = os.path.join(os.path.expanduser('~'), 'data_pi-uraiae/ONE/alyx.internationalbrainlab.org/', project)
# one = ONE(mode='local', cache_dir=save_dir)
def makepretty():
"""A simple function to format our psychometric plots"""
# Ensure x label is not cut off
plt.gcf().subplots_adjust(bottom=0.15)
# Plot lines at zero and .5
plt.plot((0, 0), (0, 1), 'k:')
plt.plot((-100, 100), (.5, .5), 'k:')
# Set limits and labels
plt.gca().set(ylim=[-.05, 1.05], xlabel='contrast (%)', ylabel='proportion rightward')
sns.despine(offset=10, trim=True)
# Wrangle the data into the correct form
def signed_contrast(trials):
"""Returns an array of signed contrasts in percent, where -ve values are on the left"""
# Replace NaNs with zeros, stack and take the difference
contrast = np.nan_to_num(np.c_[trials.contrastLeft, trials.contrastRight])
return np.diff(contrast).flatten() * 100
def calculate_choice_probability(condition_data, block_type, contrast_level):
"""
Calculate the probability of making a leftward choice for a given block type and contrast level.
:param condition_data: Dictionary with condition numbers as keys and lists of trial data as values.
:param block_type: String, either 'left' or 'right' to specify the block.
:param contrast_level: Numeric value of the contrast level for which to calculate the probability.
:return: Probability of making a leftward choice.
"""
# Filter trials based on block type and contrast level
if block_type == 'left':
relevant_trials = [trial for trial in condition_data if trial['contrast'] == contrast_level and trial['probabilityLeft'] == 0.8]
else: # 'right' block
relevant_trials = [trial for trial in condition_data if trial['contrast'] == contrast_level and trial['probabilityLeft'] == 0.2]
# Count the number of rightward choices
leftward_choices = sum(1 for trial in relevant_trials if trial['choice'] == -1)
# Calculate the probability of rightward choice
if len(relevant_trials) == 0:
return None # Avoid division by zero if there are no relevant trials
else:
return leftward_choices / len(relevant_trials)
# # Example usage:
# # Assuming condition_data[53] is a list of trial data dictionaries for nonstim condition
# # and you want to calculate the choice probability for the left block at a contrast of 25
# contrast_level = 25
# left_block_prob = calculate_choice_probability(condition_data[53], 'left', contrast_level)
# print(f'Left block probability at contrast {contrast_level}:', left_block_prob)
############### OPTIONS ####################
is_zapit_session = 0
BL_perf_thresh = 0.70 #0.79
stim_perf_thresh = 0.5 #0.5
min_num_trials = 300 #300
min_bias_threshold = 0.5 #0.5 #0.75
min_bias_threshold_zapit = 1.5 #1.5
RT_threshold = 20 #20
trials_per_datapoint = 5 ### specifically for num choices to avg for bias assessment
use_trials_after_stim = 0
subsample_trials_after_stim = 0
save_figures = 0
figure_save_path = '/Users/natemiska/Desktop/other_figures/CP/'
figure_prefix = 'D2_ex_DLS'
title_text = 'all'
flag_failed_loads = 1
############## WHEEL OPTIONS ##############
length_of_time_to_analyze_wheel_movement = 10
interval = 0.1
stim_rt_threshold = 100
align_to = 'goCue_pre'#'feedback'#'goCue_pre'#'QP'
only_include_low_contrasts = 0
low_contrast_threshold = 13
eids, trials_ranges, MouseIDs = find_sessions_by_advanced_criteria(
sessions,
# EID = lambda x: x in ['21861d63-c3be-40f4-961b-421cb5fc3913','b1582929-1117-4e44-862e-c775008ca548','c86f4ece-cb61-4f61-a32b-044cc5a7a83f','58f72a9f-471a-4889-a986-49edf7732fc9'],
# EID = lambda x: x in ['ce616651-aba5-4754-91f3-79d5e929ec70'],
# Mouse_ID = 'SWC_NM_087',
# Mouse_ID = lambda x: x in ['SWC_NM_082', 'SWC_NM_081', 'SWC_NM_057', 'SWC_NM_058', 'SWC_NM_085', 'SWC_NM_086', 'SWC_NM_071', 'SWC_NM_072'],
Mouse_ID = lambda x: x in ['SWC_NM_087', 'SWC_NM_073', 'SWC_NM_065', 'SWC_NM_042', 'SWC_NM_043', 'SWC_NM_038', 'SWC_NM_053'],
# Date = '060324',
Hemisphere = 'both',
# Opsin=lambda x: x in ['GtACR2', 'ChR2'],
# Opsin='GtACR2',
# Stimulation_Params ='zapit',
Stimulation_Params = 'QPRE',
# Stimulation_Params = lambda x: x in ['QPRE', 'QPRE*'],
# Pulse_Params = '50hz',
# Pulse_Params = 'motor_bilateral_mask',
Pulse_Params = lambda x: x in ['50hz', '20hz', 'cont_c'],
# Laser_V = 3,
# Laser_V = lambda x: x in [3, 2],
Genetic_Line = 'D2-Cre',
# Brain_Region = 'motor_bilateral',
Brain_Region = 'VLS',
)
# # Example usage:
# eids_filtered, trials_ranges_filtered = find_sessions_by_advanced_criteria(
# sessions,
# Brain_Region='VLS',
# Hemisphere='both',
# Opsin='GtACR2', #lambda x: x in ['GtACR2', 'ChR2'], # Now it will work as intended
# Pulse_Params='cont',
# Stimulation_Params='QPRE'
# )
# # Displaying the first few results for verification
# print(eids_filtered[:5], trials_ranges_filtered[:5])
# ####need to create filters here
# filtered_sessions_metadata = sessions
# eids = [session['EID'] for session in sessions]
# trials_ranges = [session['Trials_Range'] for session in sessions]
########### OLD OPTIONS
remove_trials_before = 0#140 #346
loop_threshold_for_remove = 100
#list of eids to use
separate_stim_control = 0 # if 1, then stim not controlled by program (ie, no 'opto' parameter)
start_trials_w_block_switch = 0 # if 1, then start with first block switch after stim
remove_trials_after_block_switch = 0 # if 1, then remove x trials after block switch (defined below)
num_trials_to_keep_after_switch = 50
only_keep_later_trials = 0
later_trials_start = 0
only_analyze_trials_x_after_stim = 0 #for removing simply x trials immediately after start of stim
##################### MAIN LOOP ##########################
### for concatenating zapit data; will need to change number for different stims
num_stim_locations = 52
condition_data = {i: [] for i in range(0, num_stim_locations+1)} # 1-52 for laser, 0 for control
bias_vals_LC = {i: [] for i in range(0, num_stim_locations+1)}
Rblock_wheel_movements_by_condition = [[] for _ in range(53)]
Lblock_wheel_movements_by_condition = [[] for _ in range(53)]
num_analyzed_sessions = 0
#for loop with each iteration creating stim / nonstim trials info for that eid (exactly as in manual_plot_script)
#then, that trials info is added to a set of master trials info (one for stim, one for non-stim). might be easiest if this is pre-allocated to correct size before loop
# for lm in range(0,6): #for analyzing each subject individually and using avg bias shift as a single data point
num_unique_mice = 0
previous_mouse_ID = 'NaN'
Rblock_wheel_movements_stim = []
Lblock_wheel_movements_stim = []
Rblock_wheel_movements_nonstim = []
Lblock_wheel_movements_nonstim = []
bias_shift = np.empty([np.size(eids)])
bias_shift[:] = np.NaN
bias_shift_sum_all = np.empty([np.size(eids)])
bias_shift_sum_all[:] = np.NaN
bias_shift_sum_all_LC = np.empty([np.size(eids)])
bias_shift_sum_all_LC[:] = np.NaN
bias_shift_sum_all_LEFT = np.empty([np.size(eids)])
bias_shift_sum_all_LEFT[:] = np.NaN
bias_shift_sum_all_RIGHT = np.empty([np.size(eids)])
bias_shift_sum_all_RIGHT[:] = np.NaN
bias_shift_nonstim = np.empty([np.size(eids)])
bias_shift_nonstim[:] = np.NaN
bias_shift_sum_all_nonstim = np.empty([np.size(eids)])
bias_shift_sum_all_nonstim[:] = np.NaN
bias_shift_sum_all_nonstim_LC = np.empty([np.size(eids)])
bias_shift_sum_all_nonstim_LC[:] = np.NaN
bias_shift_sum_all_nonstim_LEFT = np.empty([np.size(eids)])
bias_shift_sum_all_nonstim_LEFT[:] = np.NaN
bias_shift_sum_all_nonstim_RIGHT = np.empty([np.size(eids)])
bias_shift_sum_all_nonstim_RIGHT[:] = np.NaN
bias_shift0_all_nonstim = np.empty([np.size(eids)])
bias_shift0_all_nonstim[:] = np.NaN
bias_shift0_all_stim = np.empty([np.size(eids)])
bias_shift0_all_stim[:] = np.NaN
stim_zerocontrast_difference = np.empty([np.size(eids)])
stim_zerocontrast_difference[:] = np.NaN
nonstim_zerocontrast_difference = np.empty([np.size(eids)])
nonstim_zerocontrast_difference[:] = np.NaN
stim_sumall_difference = np.empty([np.size(eids)])
stim_sumall_difference[:] = np.NaN
nonstim_sumall_difference = np.empty([np.size(eids)])
nonstim_sumall_difference[:] = np.NaN
for j in range(0,np.size(eids)):
eid = eids[j]
print('starting session, eid = ' + eid)
try:
trials = one.load_object(eid, 'trials')
# laser_intervals = one.load_dataset(eid, '_ibl_laserStimulation.intervals')
except:
if flag_failed_loads == 1:
print('Failed to load eid = ' + eid)
input("Press Enter to continue...")
continue
else:
continue
if is_zapit_session == 0:
try:
dset = '_iblrig_taskData.raw*'
data_behav = one.load_dataset(eid, dataset=dset, collection='raw_behavior_data')
ses_path = one.eid2path(eid)
except:
print('Dataset "_iblrig_taskData.raw*.*" not found for eid = ' + eid + '. Utilizing laser intervals data...')
laser_intervals = one.load_dataset(eid, '_ibl_laserStimulation.intervals')
wheel = one.load_object(eid, 'wheel')
current_mouse_ID = MouseIDs[j]
if is_zapit_session == 0:
reaction_times = np.empty([np.size(trials['contrastLeft'])])
reaction_times[:] = np.NaN
quiescent_period_times = np.empty([np.size(trials['contrastLeft'])])
quiescent_period_times[:] = np.NaN
try:
taskData = load_data(ses_path) ###depricated
except:
print('no task data found...')
for tr in range(len(trials['contrastLeft'])):
react = trials['feedback_times'][tr] - trials['goCueTrigger_times'][tr]
if react > 59.9:
continue
try:
trial_start_time = taskData[tr]['behavior_data']['States timestamps']['trial_start'][0][0]
stimOn_time = taskData[tr]['behavior_data']['States timestamps']['stim_on'][0][0]
except:
trial_start_time = trials.intervals[tr,0]
# stimOn_time = trials.stimOn_times[tr]
stimOn_time = trials.goCueTrigger_times[tr]
# if np.isnan(stimOn_time) == 1:
# stimOn_time = trials.goCue_times[tr]
# if np.isnan(stimOn_time) == 1:
# stimOn_time = trials.goCueTrigger_times[tr]
qp = stimOn_time - trial_start_time
reaction_times[tr] = react
quiescent_period_times[tr] = qp
if num_analyzed_sessions == 0:
stim_trials = trials.copy()
nonstim_trials = trials.copy()
stim_trials_numbers = np.empty(len(trials['contrastLeft']))
stim_trials_numbers[:] = np.NaN
nonstim_trials_numbers = np.empty(len(trials['contrastLeft']))
nonstim_trials_numbers[:] = np.NaN
if trials_ranges[j] == 'ALL':
trials_range = range(0,len(trials['contrastLeft']))
#### use last trial as end of range when end of range set to 9999
elif trials_ranges[j][-1] == 9998:
trials_range = [x for x in trials_ranges[j] if x < np.size(trials.probabilityLeft)]
else:
trials_range = trials_ranges[j]
if remove_trials_before > 0 and j < loop_threshold_for_remove:
trials_range = list(np.array(trials_range)[np.where(np.array(trials_range) > remove_trials_before)[0]])
if len(trials_range) < min_num_trials:
print('Not enough trials in ' + str(eid) + ' , skipping...')
continue
### 2 different ways to extract what trials were laser trials; old versus new
try:
for k in trials_range:
if taskData[k]['opto'] == 1:
react = trials['feedback_times'][k] - trials['goCueTrigger_times'][k]
if react < RT_threshold:
stim_trials_numbers[k] = k
else:
react = trials['feedback_times'][k] - trials['goCueTrigger_times'][k]
if react < RT_threshold:
nonstim_trials_numbers[k] = k
except:
laser_intervals = one.load_dataset(eid, '_ibl_laserStimulation.intervals')
for k in trials_range:#range(0,len(trials.intervals)):
if trials.intervals[k,0] in laser_intervals[:,0]:
react = trials['feedback_times'][k] - trials['goCueTrigger_times'][k]
if react < RT_threshold:
stim_trials_numbers[k] = k
else:
react = trials['feedback_times'][k] - trials['goCueTrigger_times'][k]
if react < RT_threshold:
nonstim_trials_numbers[k] = k
trials_numbers = np.concatenate((nonstim_trials_numbers,stim_trials_numbers))#np.array(trials_range)
trials_numbers = trials_numbers[~np.isnan(trials_numbers)]
stim_trials_numbers = stim_trials_numbers[~np.isnan(stim_trials_numbers)]
nonstim_trials_numbers = nonstim_trials_numbers[~np.isnan(nonstim_trials_numbers)]
stim_trials_numbers = stim_trials_numbers.astype(int)
nonstim_trials_numbers = nonstim_trials_numbers.astype(int)
trials_numbers = trials_numbers.astype(int)
stim_trials_numbers = stim_trials_numbers[stim_trials_numbers>89]
nonstim_trials_numbers = nonstim_trials_numbers[nonstim_trials_numbers>89]
trials_numbers = trials_numbers[trials_numbers>89]
if use_trials_after_stim == 1:
for l in range(len(stim_trials_numbers)):
if l == len(stim_trials_numbers) - 1:
if stim_trials_numbers[l] > nonstim_trials_numbers[len(nonstim_trials_numbers) - 1]:
stim_trials_numbers[l] = 9999
continue
else:
stim_trials_numbers[l] = stim_trials_numbers[l] + 1
else:
if stim_trials_numbers[l+1] - stim_trials_numbers[l] == 1:
stim_trials_numbers[l] = 9999
continue
else:
stim_trials_numbers[l] = stim_trials_numbers[l] + 1
stim_trials_numbers = stim_trials_numbers[stim_trials_numbers!=9999]
rt_stimtrials = reaction_times[stim_trials_numbers]
qp_stimtrials = quiescent_period_times[stim_trials_numbers]
rt_nonstimtrials = reaction_times[nonstim_trials_numbers]
qp_nonstimtrials = quiescent_period_times[nonstim_trials_numbers]
### remove all "stim" trials from nonstim trials
nonstim_trials_numbers = np.setdiff1d(nonstim_trials_numbers, stim_trials_numbers)
#for subsampling, maybe check on each iteration here if # L&R trials in each block is equal
#alternatively, can take randomly equal number of trials from each and pool them together
#ie, make 2 groups each block, RstimRblock, LstimRblock, LstimLblock, and RstimLblock
#and subsample randomly equal amount of each for each block
if subsample_trials_after_stim:
Rblock_inds_stim = stim_trials_numbers[np.where(trials.probabilityLeft[stim_trials_numbers] == 0.2)[0]]
Lblock_inds_stim = stim_trials_numbers[np.where(trials.probabilityLeft[stim_trials_numbers] == 0.8)[0]]
PrevLchoice_inds_stim = stim_trials_numbers[np.where(trials.choice[stim_trials_numbers-1] == -1)[0]]
PrevRchoice_inds_stim = stim_trials_numbers[np.where(trials.choice[stim_trials_numbers-1] == 1)[0]]
ind_Lblock_Lprevchoice_stim = np.intersect1d(Lblock_inds_stim,PrevLchoice_inds_stim)
ind_Lblock_Rprevchoice_stim = np.intersect1d(Lblock_inds_stim,PrevRchoice_inds_stim)
ind_Rblock_Lprevchoice_stim = np.intersect1d(Rblock_inds_stim,PrevLchoice_inds_stim)
ind_Rblock_Rprevchoice_stim = np.intersect1d(Rblock_inds_stim,PrevRchoice_inds_stim)
if len(ind_Lblock_Lprevchoice_stim) > len(ind_Lblock_Rprevchoice_stim):
subsample_indices_toremove_A = random.sample(list(ind_Lblock_Lprevchoice_stim), len(ind_Lblock_Lprevchoice_stim) - len(ind_Lblock_Rprevchoice_stim))
elif len(ind_Lblock_Lprevchoice_stim) < len(ind_Lblock_Rprevchoice_stim):
subsample_indices_toremove_A = random.sample(list(ind_Lblock_Rprevchoice_stim), len(ind_Lblock_Rprevchoice_stim) - len(ind_Lblock_Lprevchoice_stim))
if len(ind_Rblock_Lprevchoice_stim) > len(ind_Rblock_Rprevchoice_stim):
subsample_indices_toremove_B = random.sample(list(ind_Rblock_Lprevchoice_stim), len(ind_Rblock_Lprevchoice_stim) - len(ind_Rblock_Rprevchoice_stim))
elif len(ind_Rblock_Lprevchoice_stim) < len(ind_Rblock_Rprevchoice_stim):
subsample_indices_toremove_B = random.sample(list(ind_Rblock_Rprevchoice_stim), len(ind_Rblock_Rprevchoice_stim) - len(ind_Rblock_Lprevchoice_stim))
subsample_indices_toremove = np.concatenate([subsample_indices_toremove_A,subsample_indices_toremove_B])
# stim_trials_numbers_test = stim_trials_numbers
for k in subsample_indices_toremove:
# stim_trials_numbers_test = np.delete(stim_trials_numbers_test, np.where(stim_trials_numbers_test == k))
stim_trials_numbers = np.delete(stim_trials_numbers, np.where(stim_trials_numbers == k))
###for estimating bias shift
stim_trials_temp = trials.copy()
nonstim_trials_temp = trials.copy()
stim_trials_temp.contrastRight = trials.contrastRight[stim_trials_numbers]
stim_trials_temp.contrastLeft = trials.contrastLeft[stim_trials_numbers]
stim_trials_temp.goCueTrigger_times = trials.goCueTrigger_times[stim_trials_numbers]
stim_trials_temp.feedback_times = trials.feedback_times[stim_trials_numbers]
stim_trials_temp.response_times = trials.response_times[stim_trials_numbers]
stim_trials_temp.feedbackType = trials.feedbackType[stim_trials_numbers]
stim_trials_temp.goCue_times = trials.goCue_times[stim_trials_numbers]
stim_trials_temp.firstMovement_times = trials.firstMovement_times[stim_trials_numbers]
stim_trials_temp.probabilityLeft = trials.probabilityLeft[stim_trials_numbers]
stim_trials_temp.stimOn_times = trials.stimOn_times[stim_trials_numbers]
stim_trials_temp.choice = trials.choice[stim_trials_numbers]
stim_trials_temp.prev_choice = trials.choice[stim_trials_numbers-1]
stim_trials_temp.rewardVolume = trials.rewardVolume[stim_trials_numbers]
stim_trials_temp.intervals = trials.intervals[stim_trials_numbers]
nonstim_trials_temp.contrastRight = trials.contrastRight[nonstim_trials_numbers]
nonstim_trials_temp.contrastLeft = trials.contrastLeft[nonstim_trials_numbers]
nonstim_trials_temp.goCueTrigger_times = trials.goCueTrigger_times[nonstim_trials_numbers]
nonstim_trials_temp.feedback_times = trials.feedback_times[nonstim_trials_numbers]
nonstim_trials_temp.response_times = trials.response_times[nonstim_trials_numbers]
nonstim_trials_temp.feedbackType = trials.feedbackType[nonstim_trials_numbers]
nonstim_trials_temp.goCue_times = trials.goCue_times[nonstim_trials_numbers]
nonstim_trials_temp.firstMovement_times = trials.firstMovement_times[nonstim_trials_numbers]
nonstim_trials_temp.probabilityLeft = trials.probabilityLeft[nonstim_trials_numbers]
nonstim_trials_temp.stimOn_times = trials.stimOn_times[nonstim_trials_numbers]
nonstim_trials_temp.choice = trials.choice[nonstim_trials_numbers]
nonstim_trials_temp.prev_choice = trials.choice[nonstim_trials_numbers-1]
nonstim_trials_temp.rewardVolume = trials.rewardVolume[nonstim_trials_numbers]
nonstim_trials_temp.intervals = trials.intervals[nonstim_trials_numbers]
stim_trials_temp_contrast = signed_contrast(stim_trials_temp)
nonstim_trials_temp_contrast = signed_contrast(nonstim_trials_temp)
nonstim_trialnums_HCR = np.where(nonstim_trials_temp_contrast == 100)[0]
nonstim_trialnums_HCL = np.where(nonstim_trials_temp_contrast == -100)[0]
num_correct_HCR = np.sum(nonstim_trials_temp.rewardVolume[nonstim_trialnums_HCR])/1.5
num_correct_HCL = np.sum(nonstim_trials_temp.rewardVolume[nonstim_trialnums_HCL])/1.5
stim_trialnums_HCR = np.where(stim_trials_temp_contrast == 100)[0]
stim_trialnums_HCL = np.where(stim_trials_temp_contrast == -100)[0]
stim_num_correct_HCR = np.sum(stim_trials_temp.rewardVolume[stim_trialnums_HCR])/1.5
stim_num_correct_HCL = np.sum(stim_trials_temp.rewardVolume[stim_trialnums_HCL])/1.5
all_signed_contrast = signed_contrast(trials)
abs_signed_contrast = abs(all_signed_contrast)
low_contrast_trials_bool_all = abs_signed_contrast < low_contrast_threshold
if num_correct_HCR/np.size(nonstim_trialnums_HCR) < BL_perf_thresh or num_correct_HCL/np.size(nonstim_trialnums_HCL) < BL_perf_thresh:
print(eid + ' below performance threshold, excluding...')
continue
if stim_num_correct_HCR/np.size(stim_trialnums_HCR) < stim_perf_thresh or stim_num_correct_HCL/np.size(stim_trialnums_HCL) < stim_perf_thresh:
print(eid + ' below performance threshold, excluding...')
continue
stim_trials_data = {}
for pL in np.unique(stim_trials_temp.probabilityLeft):
in_block = stim_trials_temp.probabilityLeft == pL
xx, nn = np.unique(stim_trials_temp_contrast[in_block], return_counts=True)
rightward = stim_trials_temp.choice == -1
pp = np.vectorize(lambda x: np.mean(rightward[(x == stim_trials_temp_contrast) & in_block]))(xx)
stim_trials_data[pL] = np.vstack((xx, nn, pp))
nonstim_trials_data = {}
for pL in np.unique(nonstim_trials_temp.probabilityLeft):
in_block = nonstim_trials_temp.probabilityLeft == pL
xx, nn = np.unique(nonstim_trials_temp_contrast[in_block], return_counts=True)
rightward = nonstim_trials_temp.choice == -1
pp = np.vectorize(lambda x: np.mean(rightward[(x == nonstim_trials_temp_contrast) & in_block]))(xx)
nonstim_trials_data[pL] = np.vstack((xx, nn, pp))
kwargs = {
# parmin: The minimum allowable parameter values, in the form
# [bias, threshold, lapse_low, lapse_high]
'parmin': np.array([-25., 10., 0., 0.]),
# parmax: The maximum allowable parameter values
'parmax': np.array([100, 100., 1, 1]),
# Non-zero starting parameters, used to try to avoid local minima
'parstart': np.array([0., 40., .1, .1]),
# nfits: The number of fits to run
'nfits': 50
}
kwargs['parmin'][0] = -50.
kwargs['parmax'][0] = 50.
# For each block type, fit the data separately and plot
for pL, da in nonstim_trials_data.items():
# Fit it
pars, L = psy.mle_fit_psycho(da, 'erf_psycho_2gammas', **kwargs);
if pL == 0.8:
bias_80_value0 = psy.erf_psycho_2gammas(pars, 0)
bias_80_valuen100 = psy.erf_psycho_2gammas(pars, -100)
bias_80_valuen25 = psy.erf_psycho_2gammas(pars, -25)
bias_80_valuen12 = psy.erf_psycho_2gammas(pars, -12)
bias_80_valuen6 = psy.erf_psycho_2gammas(pars, -6)
bias_80_value100 = psy.erf_psycho_2gammas(pars, 100)
bias_80_value25 = psy.erf_psycho_2gammas(pars, 25)
bias_80_value12 = psy.erf_psycho_2gammas(pars, 12)
bias_80_value6 = psy.erf_psycho_2gammas(pars, 6)
# nonstim_zerocontrast_80 = nonstim_trials_data[0.8][2][np.where(nonstim_trials_data[0.8][0] == 0)[0][0]]
# nonstim_n100_80 = nonstim_trials_data[0.8][2][0]
# nonstim_n25_80 = nonstim_trials_data[0.8][2][1]
# nonstim_n12_80 = nonstim_trials_data[0.8][2][2]
# nonstim_n6_80 = nonstim_trials_data[0.8][2][3]
# nonstim_6_80 = nonstim_trials_data[0.8][2][5]
# nonstim_12_80 = nonstim_trials_data[0.8][2][6]
# nonstim_25_80 = nonstim_trials_data[0.8][2][7]
# nonstim_100_80 = nonstim_trials_data[0.8][2][8]
if pL == 0.2:
bias_20_value0 = psy.erf_psycho_2gammas(pars, 0)
bias_20_valuen100 = psy.erf_psycho_2gammas(pars, -100)
bias_20_valuen25 = psy.erf_psycho_2gammas(pars, -25)
bias_20_valuen12 = psy.erf_psycho_2gammas(pars, -12)
bias_20_valuen6 = psy.erf_psycho_2gammas(pars, -6)
bias_20_value100 = psy.erf_psycho_2gammas(pars, 100)
bias_20_value25 = psy.erf_psycho_2gammas(pars, 25)
bias_20_value12 = psy.erf_psycho_2gammas(pars, 12)
bias_20_value6 = psy.erf_psycho_2gammas(pars, 6)
# nonstim_zerocontrast_20 = nonstim_trials_data[0.2][2][np.where(nonstim_trials_data[0.2][0] == 0)[0][0]]
# nonstim_n100_20 = nonstim_trials_data[0.2][2][0]
# nonstim_n25_20 = nonstim_trials_data[0.2][2][1]
# nonstim_n12_20 = nonstim_trials_data[0.2][2][2]
# nonstim_n6_20 = nonstim_trials_data[0.2][2][3]
# nonstim_6_20 = nonstim_trials_data[0.2][2][5]
# nonstim_12_20 = nonstim_trials_data[0.2][2][6]
# nonstim_25_20 = nonstim_trials_data[0.2][2][7]
# nonstim_100_20 = nonstim_trials_data[0.2][2][8]
# bias_shift_nonstim[j] = bias_20_value0 - bias_80_value0
bias_shift0 = bias_20_value0 - bias_80_value0
bias_shiftn100 = bias_20_valuen100 - bias_80_valuen100
bias_shiftn25 = bias_20_valuen25 - bias_80_valuen25
bias_shiftn12 = bias_20_valuen12 - bias_80_valuen12
bias_shiftn6 = bias_20_valuen6 - bias_80_valuen6
bias_shift100 = bias_20_value100 - bias_80_value100
bias_shift25 = bias_20_value25 - bias_80_value25
bias_shift12 = bias_20_value12 - bias_80_value12
bias_shift6 = bias_20_value6 - bias_80_value6
bias_shift_sum_all_temp = sum([bias_shift0,bias_shiftn100,bias_shiftn25,bias_shiftn12,bias_shiftn6,bias_shift100,bias_shift25,bias_shift12,bias_shift6])
if bias_shift_sum_all_temp < min_bias_threshold:
print(eid + ' below minimum baseline bias threshold, excluding...')
continue
bias_shift_sum_all_nonstim[j] = bias_shift_sum_all_temp
bias_shift_sum_all_nonstim_LC[j] = sum([bias_shift0,bias_shiftn12,bias_shiftn6,bias_shift12,bias_shift6])
bias_shift0_all_nonstim[j] = bias_shift0
bias_shift_sum_all_nonstim_LEFT[j] = sum([bias_shift0,bias_shiftn100,bias_shiftn25,bias_shiftn12,bias_shiftn6])
bias_shift_sum_all_nonstim_RIGHT[j] = sum([bias_shift0,bias_shift100,bias_shift25,bias_shift12,bias_shift6])
# nonstim_zerocontrast_difference[j] = nonstim_zerocontrast_20 - nonstim_zerocontrast_80
# difference_0 = nonstim_zerocontrast_20 - nonstim_zerocontrast_80
# difference_n100 = nonstim_n100_20 - nonstim_n100_80
# difference_n25 = nonstim_n25_20 - nonstim_n25_80
# difference_n12 = nonstim_n12_20 - nonstim_n12_80
# difference_n6 = nonstim_n6_20 - nonstim_n6_80
# difference_6 = nonstim_6_20 - nonstim_6_80
# difference_12 = nonstim_12_20 - nonstim_12_80
# difference_25 = nonstim_25_20 - nonstim_25_80
# difference_100 = nonstim_100_20 - nonstim_100_80
# nonstim_sumall_difference[j] = sum([difference_0,difference_n100,difference_n25,difference_n12,difference_n6,difference_6,difference_12,difference_25,difference_100])
for pL, da in stim_trials_data.items():
# Fit it
pars, L = psy.mle_fit_psycho(da, 'erf_psycho_2gammas', **kwargs);
if pL == 0.8:
bias_80_value0 = psy.erf_psycho_2gammas(pars, 0)
bias_80_valuen100 = psy.erf_psycho_2gammas(pars, -100)
bias_80_valuen25 = psy.erf_psycho_2gammas(pars, -25)
bias_80_valuen12 = psy.erf_psycho_2gammas(pars, -12)
bias_80_valuen6 = psy.erf_psycho_2gammas(pars, -6)
bias_80_value100 = psy.erf_psycho_2gammas(pars, 100)
bias_80_value25 = psy.erf_psycho_2gammas(pars, 25)
bias_80_value12 = psy.erf_psycho_2gammas(pars, 12)
bias_80_value6 = psy.erf_psycho_2gammas(pars, 6)
# stim_zerocontrast_80 = stim_trials_data[0.8][2][np.where(stim_trials_data[0.8][0] == 0)[0][0]]
# stim_n100_80 = stim_trials_data[0.8][2][0] ###these will not work as-is. needs something like: np.where(stim_trials_data[0.8][0] == -100)[0][0]
# stim_n25_80 = stim_trials_data[0.8][2][1]
# stim_n12_80 = stim_trials_data[0.8][2][2]
# stim_n6_80 = stim_trials_data[0.8][2][3]
# stim_6_80 = stim_trials_data[0.8][2][5]
# stim_12_80 = stim_trials_data[0.8][2][6]
# stim_25_80 = stim_trials_data[0.8][2][7]
# stim_100_80 = stim_trials_data[0.8][2][8]
if pL == 0.2:
bias_20_value0 = psy.erf_psycho_2gammas(pars, 0)
bias_20_valuen100 = psy.erf_psycho_2gammas(pars, -100)
bias_20_valuen25 = psy.erf_psycho_2gammas(pars, -25)
bias_20_valuen12 = psy.erf_psycho_2gammas(pars, -12)
bias_20_valuen6 = psy.erf_psycho_2gammas(pars, -6)
bias_20_value100 = psy.erf_psycho_2gammas(pars, 100)
bias_20_value25 = psy.erf_psycho_2gammas(pars, 25)
bias_20_value12 = psy.erf_psycho_2gammas(pars, 12)
bias_20_value6 = psy.erf_psycho_2gammas(pars, 6)
# stim_zerocontrast_20 = stim_trials_data[0.2][2][np.where(stim_trials_data[0.2][0] == 0)[0][0]]
# stim_n100_20 = stim_trials_data[0.2][2][0]
# stim_n25_20 = stim_trials_data[0.2][2][1]
# stim_n12_20 = stim_trials_data[0.2][2][2]
# stim_n6_20 = stim_trials_data[0.2][2][3]
# stim_6_20 = stim_trials_data[0.2][2][5]
# stim_12_20 = stim_trials_data[0.2][2][6]
# stim_25_20 = stim_trials_data[0.2][2][7]
# stim_100_20 = stim_trials_data[0.2][2][8]
# # Print pars
# print('prob left = {:.1f}, bias = {:2.0f}, threshold = {:2.0f}, lapse = {:.01f}, {:.01f}'.format(pL, *pars))
# # graphics
# x = np.arange(-100, 100) # The x-axis values for our curve
# ax2.plot(da[0,:], da[2,:], colours[pL] + 'o')
# ax2.plot(x, psy.erf_psycho_2gammas(pars, x), label=f'{int(pL*100)}', color=colours[pL])#, linestyle='dashed')
# bias_shift[j] = bias_20_value0 - bias_80_value0
bias_shift0 = bias_20_value0 - bias_80_value0
bias_shiftn100 = bias_20_valuen100 - bias_80_valuen100
bias_shiftn25 = bias_20_valuen25 - bias_80_valuen25
bias_shiftn12 = bias_20_valuen12 - bias_80_valuen12
bias_shiftn6 = bias_20_valuen6 - bias_80_valuen6
bias_shift100 = bias_20_value100 - bias_80_value100
bias_shift25 = bias_20_value25 - bias_80_value25
bias_shift12 = bias_20_value12 - bias_80_value12
bias_shift6 = bias_20_value6 - bias_80_value6
bias_shift_sum_all[j] = sum([bias_shift0,bias_shiftn100,bias_shiftn25,bias_shiftn12,bias_shiftn6,bias_shift100,bias_shift25,bias_shift12,bias_shift6])
bias_shift_sum_all_LC[j] = sum([bias_shift0,bias_shiftn12,bias_shiftn6,bias_shift12,bias_shift6])
bias_shift0_all_stim[j] = bias_shift0
bias_shift_sum_all_LEFT[j] = sum([bias_shift0,bias_shiftn100,bias_shiftn25,bias_shiftn12,bias_shiftn6])
bias_shift_sum_all_RIGHT[j] = sum([bias_shift0,bias_shift100,bias_shift25,bias_shift12,bias_shift6])
# stim_zerocontrast_difference[j] = stim_zerocontrast_20 - stim_zerocontrast_80
# difference_0 = stim_zerocontrast_20 - stim_zerocontrast_80
# difference_n100 = stim_n100_20 - stim_n100_80
# difference_n25 = stim_n25_20 - stim_n25_80
# difference_n12 = stim_n12_20 - stim_n12_80
# difference_n6 = stim_n6_20 - stim_n6_80
# difference_6 = stim_6_20 - stim_6_80
# difference_12 = stim_12_20 - stim_12_80
# difference_25 = stim_25_20 - stim_25_80
# difference_100 = stim_100_20 - stim_100_80
# stim_sumall_difference[j] = sum([difference_0,difference_n100,difference_n25,difference_n12,difference_n6,difference_6,difference_12,difference_25,difference_100])
#############################################################
##### Load wheel data
if use_trials_after_stim == 0: ##wheel analysis not currently set up for stim+1 condition
whlpos, whlt = wheel.position, wheel.timestamps
for k in trials_numbers:#range(len(trials['contrastLeft'])):
# trialnum = trials_numbers[k]
trialnum = k
if only_include_low_contrasts == 1:
if abs(signed_contrast(trials)[trialnum]) > low_contrast_threshold:
continue
# print(str(trialnum))
# start_time = taskData[trialnum]['behavior_data']['States timestamps']['trial_start'][0][0] - 0.03 #quiescent period - first 30ms step
# start_time = taskData[trialnum]['behavior_data']['States timestamps']['reward'][0][0] - 0.5 #reward/error
# if np.isnan(start_time) == 1:
# start_time = taskData[trialnum]['behavior_data']['States timestamps']['error'][0][0] - 0.5
if align_to == 'goCue':
start_time = trials.goCueTrigger_times[trialnum] #GO CUE
elif align_to == 'goCue_pre':
start_time = trials.goCueTrigger_times[trialnum] - 0.5 #GO CUE - 0.5s
elif align_to == 'QP':
start_time = trials.intervals[trialnum][0] #QP / Laser onset
elif align_to == 'feedback':
start_time = trials.feedback_times[trialnum] - 0.6
wheel_start_index_pre = np.searchsorted(whlt, start_time)
t = start_time
# Check the closest value by comparing the differences between 't' and its neighboring elements
if wheel_start_index_pre == 0:
wheel_start_index = wheel_start_index_pre
elif wheel_start_index_pre == len(whlt):
wheel_start_index = wheel_start_index_pre - 1
else:
left_diff = t - whlt[wheel_start_index_pre - 1]
right_diff = whlt[wheel_start_index_pre] - t
wheel_start_index = wheel_start_index_pre - 1 if left_diff <= right_diff else wheel_start_index_pre
total_wheel_movement = []
for l in range(int(length_of_time_to_analyze_wheel_movement/interval)):
t = (start_time + l*interval)# + interval #ie, steps of 100ms
# wheel_end_index = np.argmin(np.abs(whlt - t))
#norm_wheel_vals = whlpos[wheel_start_index:wheel_end_index]/whlpos[wheel_start_index]
wheel_end_index_pre = np.searchsorted(whlt, t) #ie, steps of 100ms
# Check the closest value by comparing the differences between 't' and its neighboring elements
if wheel_end_index_pre == 0:
wheel_end_index = wheel_end_index_pre
elif wheel_end_index_pre == len(whlt):
wheel_end_index = wheel_end_index_pre - 1
else:
left_diff = t - whlt[wheel_end_index_pre - 1]
right_diff = whlt[wheel_end_index_pre] - t
wheel_end_index = wheel_end_index_pre - 1 if left_diff <= right_diff else wheel_end_index_pre
##only in case where aligning to QP, do not use any wheel movement past goCue
if align_to == 'QP' and trials.goCueTrigger_times[trialnum] < whlt[wheel_end_index]:
total_wheel_movement = np.append(total_wheel_movement,np.NaN)
##only in case where aligning to goCue, do not use any wheel movement past feedback + 0.1
elif align_to == 'goCue' and (trials.feedback_times[trialnum] + interval) < whlt[wheel_end_index]:
total_wheel_movement = np.append(total_wheel_movement,np.NaN)
elif align_to == 'goCue_pre' and (trials.feedback_times[trialnum] + interval) < whlt[wheel_end_index]:
total_wheel_movement = np.append(total_wheel_movement,np.NaN)
else:
total_wheel_movement = np.append(total_wheel_movement,whlpos[wheel_end_index] - whlpos[wheel_start_index])
#determine whether trial is a stim or nonstim trial
#nonstim
if np.isin(trialnum,nonstim_trials_numbers):
if trials.probabilityLeft[trialnum] == 0.2:
if len(Rblock_wheel_movements_nonstim) == 0:
Rblock_wheel_movements_nonstim = total_wheel_movement
else:
Rblock_wheel_movements_nonstim = np.vstack([Rblock_wheel_movements_nonstim,total_wheel_movement])
if trials.probabilityLeft[trialnum] == 0.8:
if len(Lblock_wheel_movements_nonstim) == 0:
Lblock_wheel_movements_nonstim = total_wheel_movement
else:
Lblock_wheel_movements_nonstim = np.vstack([Lblock_wheel_movements_nonstim,total_wheel_movement])
#stim
elif np.isin(trialnum,stim_trials_numbers):
if trials.probabilityLeft[trialnum] == 0.2:
if len(Rblock_wheel_movements_stim) == 0:
Rblock_wheel_movements_stim = total_wheel_movement
else:
Rblock_wheel_movements_stim = np.vstack([Rblock_wheel_movements_stim,total_wheel_movement])
if trials.probabilityLeft[trialnum] == 0.8:
if len(Lblock_wheel_movements_stim) == 0:
Lblock_wheel_movements_stim = total_wheel_movement
else:
Lblock_wheel_movements_stim = np.vstack([Lblock_wheel_movements_stim,total_wheel_movement])
else:
raise Exception('Trials must be either stim or nonstim; something is wrong')
#############################################################
if num_analyzed_sessions == 0:
stim_trials.contrastRight = trials.contrastRight[stim_trials_numbers]
stim_trials.contrastLeft = trials.contrastLeft[stim_trials_numbers]
stim_trials.goCueTrigger_times = trials.goCueTrigger_times[stim_trials_numbers]
stim_trials.feedback_times = trials.feedback_times[stim_trials_numbers]
stim_trials.response_times = trials.response_times[stim_trials_numbers]
stim_trials.feedbackType = trials.feedbackType[stim_trials_numbers]
stim_trials.goCue_times = trials.goCue_times[stim_trials_numbers]
stim_trials.firstMovement_times = trials.firstMovement_times[stim_trials_numbers]
stim_trials.probabilityLeft = trials.probabilityLeft[stim_trials_numbers]
stim_trials.stimOn_times = trials.stimOn_times[stim_trials_numbers]
stim_trials.choice = trials.choice[stim_trials_numbers]
stim_trials.prev_choice = trials.choice[stim_trials_numbers-1]
stim_trials.rewardVolume = trials.rewardVolume[stim_trials_numbers]
stim_trials.intervals = trials.intervals[stim_trials_numbers]
stim_trials.reaction_times = stim_trials.feedback_times - stim_trials.goCueTrigger_times#stim_trials.stimOn_times
nonstim_trials.contrastRight = trials.contrastRight[nonstim_trials_numbers]
nonstim_trials.contrastLeft = trials.contrastLeft[nonstim_trials_numbers]
nonstim_trials.goCueTrigger_times = trials.goCueTrigger_times[nonstim_trials_numbers]
nonstim_trials.feedback_times = trials.feedback_times[nonstim_trials_numbers]
nonstim_trials.response_times = trials.response_times[nonstim_trials_numbers]
nonstim_trials.feedbackType = trials.feedbackType[nonstim_trials_numbers]
nonstim_trials.goCue_times = trials.goCue_times[nonstim_trials_numbers]
nonstim_trials.firstMovement_times = trials.firstMovement_times[nonstim_trials_numbers]
nonstim_trials.probabilityLeft = trials.probabilityLeft[nonstim_trials_numbers]
nonstim_trials.stimOn_times = trials.stimOn_times[nonstim_trials_numbers]
nonstim_trials.choice = trials.choice[nonstim_trials_numbers]
nonstim_trials.prev_choice = trials.choice[nonstim_trials_numbers-1]
nonstim_trials.rewardVolume = trials.rewardVolume[nonstim_trials_numbers]
nonstim_trials.intervals = trials.intervals[nonstim_trials_numbers]
nonstim_trials.reaction_times = nonstim_trials.feedback_times - nonstim_trials.goCueTrigger_times#nonstim_trials.stimOn_times
stim_trials_contrast = signed_contrast(stim_trials)
nonstim_trials_contrast = signed_contrast(nonstim_trials)
rt_stimtrials_all = rt_stimtrials
qp_stimtrials_all = qp_stimtrials
rt_nonstimtrials_all = rt_nonstimtrials
qp_nonstimtrials_all = qp_nonstimtrials
rt_stimtrials_all_persubject = np.nanmean(rt_stimtrials)
qp_stimtrials_all_persubject = np.nanmean(qp_stimtrials)
rt_nonstimtrials_all_persubject = np.nanmean(rt_nonstimtrials)
qp_nonstimtrials_all_persubject = np.nanmean(qp_nonstimtrials)
num_analyzed_sessions = 1
num_unique_mice = 1
previous_mouse_ID = current_mouse_ID
else:
stim_trials.contrastRight = np.append(stim_trials.contrastRight,trials.contrastRight[stim_trials_numbers])
stim_trials.contrastLeft = np.append(stim_trials.contrastLeft,trials.contrastLeft[stim_trials_numbers])
stim_trials.goCueTrigger_times = np.append(stim_trials.goCueTrigger_times,trials.goCueTrigger_times[stim_trials_numbers])
stim_trials.feedback_times = np.append(stim_trials.feedback_times,trials.feedback_times[stim_trials_numbers])
stim_trials.response_times = np.append(stim_trials.response_times,trials.response_times[stim_trials_numbers])
stim_trials.feedbackType = np.append(stim_trials.feedbackType,trials.feedbackType[stim_trials_numbers])
stim_trials.goCue_times = np.append(stim_trials.goCue_times,trials.goCue_times[stim_trials_numbers])
stim_trials.firstMovement_times = np.append(stim_trials.firstMovement_times,trials.firstMovement_times[stim_trials_numbers])
stim_trials.probabilityLeft = np.append(stim_trials.probabilityLeft,trials.probabilityLeft[stim_trials_numbers])
stim_trials.stimOn_times = np.append(stim_trials.stimOn_times,trials.stimOn_times[stim_trials_numbers])
stim_trials.choice = np.append(stim_trials.choice,trials.choice[stim_trials_numbers])
stim_trials.prev_choice = np.append(stim_trials.prev_choice,trials.choice[stim_trials_numbers-1])
stim_trials.rewardVolume = np.append(stim_trials.rewardVolume,trials.rewardVolume[stim_trials_numbers])
stim_trials.intervals = np.append(stim_trials.intervals,trials.intervals[stim_trials_numbers])
stim_trials.reaction_times = np.append(stim_trials.reaction_times,trials.feedback_times[stim_trials_numbers] - trials.goCueTrigger_times[stim_trials_numbers])
nonstim_trials.contrastRight = np.append(nonstim_trials.contrastRight,trials.contrastRight[nonstim_trials_numbers])
nonstim_trials.contrastLeft = np.append(nonstim_trials.contrastLeft,trials.contrastLeft[nonstim_trials_numbers])
nonstim_trials.goCueTrigger_times = np.append(nonstim_trials.goCueTrigger_times,trials.goCueTrigger_times[nonstim_trials_numbers])
nonstim_trials.feedback_times = np.append(nonstim_trials.feedback_times,trials.feedback_times[nonstim_trials_numbers])
nonstim_trials.response_times = np.append(nonstim_trials.response_times,trials.response_times[nonstim_trials_numbers])
nonstim_trials.feedbackType = np.append(nonstim_trials.feedbackType,trials.feedbackType[nonstim_trials_numbers])
nonstim_trials.goCue_times = np.append(nonstim_trials.goCue_times,trials.goCue_times[nonstim_trials_numbers])
nonstim_trials.firstMovement_times = np.append(nonstim_trials.firstMovement_times,trials.firstMovement_times[nonstim_trials_numbers])
nonstim_trials.probabilityLeft = np.append(nonstim_trials.probabilityLeft,trials.probabilityLeft[nonstim_trials_numbers])
nonstim_trials.stimOn_times = np.append(nonstim_trials.stimOn_times,trials.stimOn_times[nonstim_trials_numbers])
nonstim_trials.choice = np.append(nonstim_trials.choice,trials.choice[nonstim_trials_numbers])
nonstim_trials.prev_choice = np.append(nonstim_trials.prev_choice,trials.choice[nonstim_trials_numbers-1])
nonstim_trials.rewardVolume = np.append(nonstim_trials.rewardVolume,trials.rewardVolume[nonstim_trials_numbers])
nonstim_trials.intervals = np.append(nonstim_trials.intervals,trials.intervals[nonstim_trials_numbers])
nonstim_trials.reaction_times = np.append(nonstim_trials.reaction_times,trials.feedback_times[nonstim_trials_numbers] - trials.goCueTrigger_times[nonstim_trials_numbers])
# stim_trials_contrast = np.append(stim_trials_contrast,signed_contrast(stim_trials))
# nonstim_trials_contrast = np.append(nonstim_trials_contrast,signed_contrast(nonstim_trials)) #??? check this
rt_stimtrials_all = np.append(rt_stimtrials_all,rt_stimtrials)
qp_stimtrials_all = np.append(qp_stimtrials_all,qp_stimtrials)
rt_nonstimtrials_all = np.append(rt_nonstimtrials_all,rt_nonstimtrials)
qp_nonstimtrials_all = np.append(qp_nonstimtrials_all,qp_nonstimtrials)
rt_stimtrials_all_persubject = np.append(rt_stimtrials_all_persubject,np.nanmean(rt_stimtrials))
qp_stimtrials_all_persubject = np.append(qp_stimtrials_all_persubject,np.nanmean(qp_stimtrials))
rt_nonstimtrials_all_persubject = np.append(rt_nonstimtrials_all_persubject,np.nanmean(rt_nonstimtrials))
qp_nonstimtrials_all_persubject = np.append(qp_nonstimtrials_all_persubject,np.nanmean(qp_nonstimtrials))
num_analyzed_sessions = num_analyzed_sessions + 1
if previous_mouse_ID != current_mouse_ID:
num_unique_mice = num_unique_mice + 1
previous_mouse_ID = current_mouse_ID
############################################ the following is analysis for zapit sessions
########################################################################################
else:
laser_intervals = one.load_dataset(eid, '_ibl_laserStimulation.intervals')
if trials_ranges[j] == 'ALL':
trials_range = range(0,len(trials['contrastLeft']))
#### use last trial as end of range when end of range set to 9999
elif trials_ranges[j][-1] == 9998:
trials_range = [x for x in trials_ranges[j] if x < np.size(trials.probabilityLeft)]
else:
trials_range = trials_ranges[j]
# if remove_trials_before > 0 and j < loop_threshold_for_remove:
# trials_range = list(np.array(trials_range)[np.where(np.array(trials_range) > remove_trials_before)[0]])
# if len(trials_range) < min_num_trials:
# print('Not enough trials in ' + str(eid) + ' , skipping...')
# continue
############################## zapit stim locations log
file_path = '/Users/natemiska/python/bias_coding/zapit_trials.yml'
details = one.get_details(eid)
exp_start_time_str = details['start_time']
if eid == '21d33b44-f75f-4711-a2c7-0bdfe8eec386': #strange issue with logged stims in this session
exp_start_time_str = '2024-03-29T18:07:38.0'
# Convert session start to datetime object
session_start = datetime.strptime(exp_start_time_str[0:19], '%Y-%m-%dT%H:%M:%S')
event_num = 0
with open(file_path, 'r') as file:
# Skip the first line
next(file)
# List to hold events that occur during or after the session start
relevant_events = []
for line in file:
# Extract the timestamp part from the line and convert it to a datetime object
# Assuming the format is always "YYYY-MM-DD HH:MM:SS", which corresponds to the first 19 characters
event_timestamp_str = line[:19]
if len(event_timestamp_str) < 19:
print('error in correctly reading timestamp string for one line - not sure why this happens?')
continue
event_timestamp = datetime.strptime(event_timestamp_str, '%Y-%m-%d %H:%M:%S')
# Check if the event timestamp is equal to or later than the session start
if event_timestamp >= session_start:
relevant_events.append(line.strip()) # Add event line to the list, stripping newline characters
event_num = event_num + 1
# # Now, relevant_events contains all the lines for events during or after the session start
# for event in relevant_events:
# print(event)
######################### end zapit log load
### Loop that extracts trial number and stim location for each laser stim
stimtrial_location_dict = {}
previous_logged_timestamp = datetime.strptime(relevant_events[0][:19], '%Y-%m-%d %H:%M:%S')
previous_laser_interval = laser_intervals[0,0]
for k in range(0,len(laser_intervals[:,0]) - 2): #loop is num of laser stim for session
if k == 0:
continue
#1st stim can be before 1st trial?
elif eid == '21d33b44-f75f-4711-a2c7-0bdfe8eec386' and k < 10: #strange issue with logged stims in this session
continue
else:
trialnum = np.where(laser_intervals[k,0]==trials.intervals[:,0])[0][0]
stim_location = relevant_events[k][20:22]
cleaned_stim_location = int(re.sub(r'\D', '', stim_location))
stimtrial_location_dict[trialnum] = cleaned_stim_location
logged_time = relevant_events[k][0:19]
if eid == '5a41494f-25b9-48d4-8159-527141bd4742': #strange exception where logged events off by 1 starting ~trial 11
logged_time = relevant_events[k-1][0:19]
logged_timestamp = event_timestamp = datetime.strptime(logged_time, '%Y-%m-%d %H:%M:%S')
# print('trial number = ' + str(trialnum))
# print('laser interval = ' + str(laser_intervals[k,0]))
# print('logged time = ' + logged_time)
delta = logged_timestamp - previous_logged_timestamp
delta_log = delta.total_seconds()
# print('delta log = ' + str(delta_log))
delta_interval = laser_intervals[k,0] - previous_laser_interval
# print('delta interval = ' + str(delta_interval))
# if abs(delta_log - delta_interval) > 1:
# print('Warning, laser log may be incorrect for trial ' + str(trialnum))
# ui = input("Press Enter to continue, e to exit...")
# if ui == 'e':
# raise Exception('Script terminated by user')
previous_laser_interval = laser_intervals[k,0]
previous_logged_timestamp = logged_timestamp
stimtrial_location_dict_all = {k: 0 for k in trials_range}
stimtrial_location_dict_all.update(stimtrial_location_dict)
### make new dict that simply adds 1 to each key
if use_trials_after_stim == 1:
stimtrial_location_dict_OG = stimtrial_location_dict_all
stimtrial_location_dict_all = {key + 1: value for key, value in stimtrial_location_dict_all.items() if np.min(trials_range) <= key < np.max(trials_range)}
####################################################################################
### for removing whole session if it does not meet behavioral criteria
session_data_nonstim = {i: [] for i in range(0, 1)}
if use_trials_after_stim == 1:
trials_with_condition_zero = [trial for trial, condition in stimtrial_location_dict_OG.items() if condition == 0] ###need to make sure this propogates
else:
trials_with_condition_zero = [trial for trial, condition in stimtrial_location_dict_all.items() if condition == 0]
for trial_number in trials_with_condition_zero:
reaction_time = trials.feedback_times[trial_number] - trials.goCueTrigger_times[trial_number]
if np.isnan(reaction_time) == 1:
reaction_time = trials.feedback_times[trial_number] - trials.goCueTrigger_times[trial_number] ###reaction time definitions may be unreliable - any other ways to define?
trials_data = {
'choice': trials.choice[trial_number],
'reaction_times': reaction_time,
'qp_times': trials.goCueTrigger_times[trial_number] - trials.intervals[trial_number][0],
'contrast': signed_contrast(trials)[trial_number],
'feedbackType': trials.feedbackType[trial_number],
'probabilityLeft': trials.probabilityLeft[trial_number],
# 'prev_choice': trials.choice[trial_number-1]
}
session_data_nonstim[0].append(trials_data)
nonstim_feedback = [trial['feedbackType'] for trial in session_data_nonstim[0] if trial['contrast'] in (-100, -25, 25, 100)]
correct_rate_nonstim = np.sum(np.array(nonstim_feedback) == 1) / len(nonstim_feedback)
print('Accuracy at high contrasts = ' + str(correct_rate_nonstim))
if correct_rate_nonstim < BL_perf_thresh:
print('Session eid = ' + eid + ' is below minimum performance threshold, skipping...')
continue
# create criteria for minimum bias session
choices_L100_Lblock = [trial['choice'] for trial in session_data_nonstim[0] if trial['contrast'] == -100 and trial['probabilityLeft'] == 0.8]
choices_L25_Lblock = [trial['choice'] for trial in session_data_nonstim[0] if trial['contrast'] == -25 and trial['probabilityLeft'] == 0.8]
choices_L12_Lblock = [trial['choice'] for trial in session_data_nonstim[0] if trial['contrast'] == -12.5 and trial['probabilityLeft'] == 0.8]
choices_L6_Lblock = [trial['choice'] for trial in session_data_nonstim[0] if trial['contrast'] == -6.25 and trial['probabilityLeft'] == 0.8]
choices_0_Lblock = [trial['choice'] for trial in session_data_nonstim[0] if trial['contrast'] == 0 and trial['probabilityLeft'] == 0.8]
choices_R6_Lblock = [trial['choice'] for trial in session_data_nonstim[0] if trial['contrast'] == 6.25 and trial['probabilityLeft'] == 0.8]
choices_R12_Lblock = [trial['choice'] for trial in session_data_nonstim[0] if trial['contrast'] == 12.5 and trial['probabilityLeft'] == 0.8]
choices_R25_Lblock = [trial['choice'] for trial in session_data_nonstim[0] if trial['contrast'] == 25 and trial['probabilityLeft'] == 0.8]
choices_R100_Lblock = [trial['choice'] for trial in session_data_nonstim[0] if trial['contrast'] == 100 and trial['probabilityLeft'] == 0.8]
choices_L100_Rblock = [trial['choice'] for trial in session_data_nonstim[0] if trial['contrast'] == -100 and trial['probabilityLeft'] == 0.2]
choices_L25_Rblock = [trial['choice'] for trial in session_data_nonstim[0] if trial['contrast'] == -25 and trial['probabilityLeft'] == 0.2]
choices_L12_Rblock = [trial['choice'] for trial in session_data_nonstim[0] if trial['contrast'] == -12.5 and trial['probabilityLeft'] == 0.2]
choices_L6_Rblock = [trial['choice'] for trial in session_data_nonstim[0] if trial['contrast'] == -6.25 and trial['probabilityLeft'] == 0.2]
choices_0_Rblock = [trial['choice'] for trial in session_data_nonstim[0] if trial['contrast'] == 0 and trial['probabilityLeft'] == 0.2]
choices_R6_Rblock = [trial['choice'] for trial in session_data_nonstim[0] if trial['contrast'] == 6.25 and trial['probabilityLeft'] == 0.2]
choices_R12_Rblock = [trial['choice'] for trial in session_data_nonstim[0] if trial['contrast'] == 12.5 and trial['probabilityLeft'] == 0.2]
choices_R25_Rblock = [trial['choice'] for trial in session_data_nonstim[0] if trial['contrast'] == 25 and trial['probabilityLeft'] == 0.2]
choices_R100_Rblock = [trial['choice'] for trial in session_data_nonstim[0] if trial['contrast'] == 100 and trial['probabilityLeft'] == 0.2]
biasshift_L100 = np.sum(np.array(choices_L100_Lblock) == 1)/len(choices_L100_Lblock) - np.sum(np.array(choices_L100_Rblock) == 1)/len(choices_L100_Rblock)
if np.isnan(biasshift_L100) == 1:
biasshift_L100 = 0