-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAP_operant_learning_figures_published.m
3000 lines (2410 loc) · 109 KB
/
AP_operant_learning_figures_published.m
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
% Generate figures for operant learning paper
% (data is prepared in AP_operant_learning_preprocessing)
%
% Code blocks with symbols:
% load data first: run code block at top with same symbol
%
% v6: submission 2
%% ------- LOAD DATA ---------------------------
%% >> Load task data
% Load data
trial_data_path = 'C:\Users\Andrew\OneDrive for Business\Documents\CarandiniHarrisLab\analysis\operant_learning\data';
data_fn = 'trial_activity_task_teto';
AP_load_trials_operant;
min_n = 4; % (minimum n to plot data)
% Load behavior, exclude animals not in dataset, get learned day
data_path = 'C:\Users\Andrew\OneDrive for Business\Documents\CarandiniHarrisLab\analysis\operant_learning\data';
bhv_fn = [data_path filesep 'bhv_teto'];
load(bhv_fn);
bhv = bhv(ismember({bhv.animal},animals));
learned_day = cellfun(@(x) find(x,1),{bhv.learned_days})';
learned_day_animal = cellfun(@(ld,n) [1:n]'-(ld), ...
num2cell(learned_day),num2cell(cellfun(@length,trial_info_all)), ...
'uni',false);
% Get animal and day index for each trial
trial_animal = cell2mat(arrayfun(@(x) ...
x*ones(size(vertcat(wheel_all{x}{:}),1),1), ...
[1:length(wheel_all)]','uni',false));
trial_day = cell2mat(cellfun(@(x) cell2mat(cellfun(@(curr_day,x) ...
curr_day*ones(size(x,1),1),num2cell(1:length(x))',x,'uni',false)), ...
wheel_all,'uni',false));
trial_learned_day = trial_day - learned_day(trial_animal);
learned_day_unique = unique(trial_learned_day)';
[~,trial_learned_day_id] = ismember(trial_learned_day,learned_day_unique);
% Get number of trials by animal/recording
trials_allcat = size(wheel_allcat,1);
trials_animal = arrayfun(@(x) size(vertcat(wheel_all{x}{:}),1),1:size(wheel_all));
trials_recording = cellfun(@(x) size(x,1),vertcat(wheel_all{:}));
% Get movement hemisphere ratio (from rewardable no-stim movements)
% (average movement activity across days for each mouse and get hemiratio)
% (by ROI)
fluor_move_nostim_roi = cellfun(@(x) ...
AP_svd_roi(U_master(:,:,1:n_vs), ...
permute(nanmean(cell2mat(x),1),[3,2,1]),[],[],cat(3,wf_roi.mask)), ...
fluor_move_nostim_rewardable_all,'uni',false);
roi_hemiflip = circshift(1:n_rois,n_rois/2);
fluor_move_nostim_roi_hemiratio = cellfun(@(x) ...
arrayfun(@(roi) ...
x(roi_hemiflip(roi),:)'\x(roi,:)',1:n_rois), ...
fluor_move_nostim_roi,'uni',false);
trial_move_hemiratio = cell2mat(cellfun(@(x,tr) ...
permute(repmat(x,tr,1),[1,3,2]), ...
fluor_move_nostim_roi_hemiratio,num2cell(trials_animal)','uni',false));
% (by pixel)
fluor_move_nostim_rewardable_animalavg_px = ...
cellfun(@(x) AP_svdFrameReconstruct(U_master(:,:,1:n_vs), ...
permute(nanmean(cell2mat(x),1),[3,2,1])), ...
fluor_move_nostim_rewardable_all,'uni',false);
% scaling as cov(v1,v2)/var(v2)
fluor_move_nostim_rewardable_animalavg_px_hemiratio = ...
cellfun(@(x,x_flip) ...
reshape(sum(reshape(x-nanmean(x,3),[],size(x,3)).* ...
reshape(x_flip-nanmean(x_flip,3),[],size(x,3)),2) ./ ...
sum(reshape(x_flip-nanmean(x_flip,3),[],size(x,3)).* ...
reshape(x_flip-nanmean(x_flip,3),[],size(x,3)),2), ...
size(x,1),size(x,2)), ...
fluor_move_nostim_rewardable_animalavg_px, ...
cellfun(@AP_reflect_widefield,fluor_move_nostim_rewardable_animalavg_px,'uni',false), ...
'uni',false);
%% ++ Load passive data
% Load data
trial_data_path = 'C:\Users\Andrew\OneDrive for Business\Documents\CarandiniHarrisLab\analysis\operant_learning\data';
data_fn = 'trial_activity_passive_teto';
AP_load_trials_operant;
n_naive = 3; % (number of naive passive-only days, just hard-coding)
min_n = 4; % (minimum n to plot data)
% Load behavior, exclude animals not in dataset, get learned day
data_path = 'C:\Users\Andrew\OneDrive for Business\Documents\CarandiniHarrisLab\analysis\operant_learning\data';
bhv_fn = [data_path filesep 'bhv_teto'];
load(bhv_fn);
bhv = bhv(ismember({bhv.animal},animals));
learned_day = cellfun(@(x) find(x,1),{bhv.learned_days})';
% Get animal and day index for each trial
trial_animal = cell2mat(arrayfun(@(x) ...
x*ones(size(vertcat(wheel_all{x}{:}),1),1), ...
[1:length(wheel_all)]','uni',false));
trial_day = cell2mat(cellfun(@(x) cell2mat(cellfun(@(curr_day,x) ...
curr_day*ones(size(x,1),1),num2cell(1:length(x))',x,'uni',false)), ...
wheel_all,'uni',false));
trials_recording = cellfun(@(x) size(x,1),vertcat(wheel_all{:}));
% Get "learned day" for each trial
trial_learned_day = cell2mat(cellfun(@(x,ld) cell2mat(cellfun(@(curr_day,x) ...
curr_day*ones(size(x,1),1),num2cell([1:length(x)]-ld)',x,'uni',false)), ...
wheel_all,num2cell(learned_day + n_naive),'uni',false));
% Define learning stages
% (learning stages: day 1-3 passive-only, then pre/post learning)
trial_stage = 1*(trial_day <= 3) + ...
2*(trial_day > 3 & trial_learned_day < 0) + ...
3*(trial_learned_day >= 0);
n_stages = length(unique(trial_stage));
% Get trials with movement during stim to exclude
quiescent_trials = ~any(abs(wheel_allcat(:,t >= 0 & t <= 0.5)) > 0,2);
% (print total fraction of quiescent trials)
q_exp = mat2cell(quiescent_trials,cellfun(@(x) size(x,1),vertcat(wheel_all{:})),1);
s_exp = mat2cell(trial_stim_allcat,cellfun(@(x) size(x,1),vertcat(wheel_all{:})),1);
q_exp_frac = cell2mat(cellfun(@(q,s) grpstats(q,s),q_exp,s_exp,'uni',false)');
fprintf('Quiescent trial frac: \n%.2f+-%.2f (left),%.2f+-%.2f (center),%.2f+-%.2f (right)\n', ...
reshape([nanmean(q_exp_frac,2),nanstd(q_exp_frac,[],2)]',[],1))
% Turn values into IDs for grouping
stim_unique = unique(trial_stim_allcat);
[~,trial_stim_id] = ismember(trial_stim_allcat,stim_unique);
learned_day_unique = unique(trial_learned_day);
[~,trial_learned_day_id] = ismember(trial_learned_day,learned_day_unique);
% Get average fluorescence by animal/day/stim
stim_v_avg = cell(length(animals),1);
stim_roi_avg = cell(length(animals),1);
for curr_animal = 1:length(animals)
for curr_day = 1:max(trial_day(trial_animal == curr_animal))
for curr_stim_idx = 1:length(stim_unique)
use_trials = quiescent_trials & ...
trial_animal == curr_animal & ...
trial_day == curr_day & ...
trial_stim_allcat == stim_unique(curr_stim_idx);
stim_v_avg{curr_animal}(:,:,curr_day,curr_stim_idx) = ...
permute(nanmean(fluor_allcat_deconv(use_trials,:,:),1),[3,2,1]);
stim_roi_avg{curr_animal}(:,:,curr_day,curr_stim_idx) = ...
permute(nanmean(fluor_roi_deconv(use_trials,:,:),1),[3,2,1]);
end
end
end
%% ------- GENERATE FIGS -----------------------
%% [FIG 1B]: example performance
animal = 'AP106';
protocol = 'AP_stimWheelRight';
experiments = AP_find_experiments(animal,protocol);
plot_days = [1,3,7];
figure;
h = tiledlayout(length(plot_days),1);
for curr_day = plot_days
day = experiments(curr_day).day;
experiment = experiments(curr_day).experiment;
load_parts.imaging = false;
AP_load_experiment;
t = Timeline.rawDAQTimestamps;
% Convert wheel velocity from clicks/s to mm/s
% (mm in clicks from +hw.DaqRotaryEncoder, Lilrig encoder = 100)
wheel_click2mm = 0.4869;
wheel_velocity_mm = wheel_velocity*wheel_click2mm;
% (minimum ITI: new trial + trial quiescence)
min_iti_t = signals_events.newTrialTimes + ...
signals_events.trialQuiescenceValues;
plot_t = [100,150];
plot_t_idx = t > plot_t(1) & t < plot_t(2);
plot_stim_idx = find(stimOn_times > plot_t(1) & stimOn_times < plot_t(2))';
plot_min_iti_t_idx = find(min_iti_t > plot_t(1) & min_iti_t < plot_t(2));
plot_reward_idx = find(reward_t_timeline > plot_t(1) & reward_t_timeline < plot_t(2));
nexttile; hold on;
% Plot stim and rewards
yyaxis left; hold on;
area(t(plot_t_idx),stimOn_epochs(plot_t_idx), ...
'EdgeColor','none','FaceColor',[1,1,0.8])
for i = plot_reward_idx
line(repmat(reward_t_timeline(i),2,1), ...
[0,1],'color','b','linewidth',2);
end
% Plot wheel velocity
yyaxis right;
plot(t(plot_t_idx),wheel_velocity_mm(plot_t_idx),'k');
axis off;
title(sprintf('Day %d',curr_day));
end
h_ax = flipud(allchild(h));
linkaxes(h_ax,'y');
% Draw scalebars
t_scale = 5;
vel_scale = 100;
AP_scalebar(t_scale,vel_scale);
%% [FIG 1C-G, FIG 3C, FIG S1]: behavior
% Load behavior
data_path = 'C:\Users\Andrew\OneDrive for Business\Documents\CarandiniHarrisLab\analysis\operant_learning\data';
bhv_fn = [data_path filesep 'bhv_teto'];
load(bhv_fn);
animals = {bhv.animal};
% Grab learned day
learned_day = cellfun(@(x) find(x,1),{bhv.learned_days})';
% Load muscimol injection info
data_path = 'C:\Users\Andrew\OneDrive for Business\Documents\CarandiniHarrisLab\analysis\operant_learning\data';
muscimol_fn = [data_path filesep 'muscimol.mat'];
load(muscimol_fn);
% Use days before muscimol
use_days = cell(size(bhv));
for curr_animal = 1:length(bhv)
muscimol_animal_idx = ismember({muscimol.animal},bhv(curr_animal).animal);
if ~any(muscimol_animal_idx)
use_days{curr_animal} = true(length(bhv(curr_animal).day),1);
continue
end
muscimol_day_idx = datenum(bhv(curr_animal).day) >= ...
datenum(muscimol(muscimol_animal_idx).day(1));
use_days{curr_animal} = ~muscimol_day_idx;
end
% Set max days (for padding) and plot days (minimum n)
max_days = max(cellfun(@sum,use_days));
min_n = 4;
plot_days = find(accumarray(cell2mat(cellfun(@find,use_days,'uni',false)'),1) >= min_n);
% Get reaction/resampled alt reaction times for all regular days
% (exclude trials without alts: rare, from wheel click issues)
use_rxn = cellfun(@(x) cellfun(@(x) cellfun(@(x) ...
~isempty(x),x),x,'uni',false),{bhv.alt_stim_move_t},'uni',false);
rxn_measured = cellfun(@(rxn,use_days,use_trials) ...
cellfun(@(rxn,use_trials) rxn(use_trials),rxn(use_days),use_trials(use_days),'uni',false), ...
{bhv.stim_move_t},use_days,use_rxn,'uni',false)';
n_rxn_altsample = 1000;
rxn_alt = cellfun(@(rxn,use_days,use_trials) ...
cellfun(@(rxn,use_trials) ...
cell2mat(cellfun(@(x) datasample(x,n_rxn_altsample)',rxn(use_trials),'uni',false)), ...
rxn(use_days),use_trials(use_days),'uni',false), ...
{bhv.alt_stim_move_t},use_days,use_rxn,'uni',false)';
% Concatenate and get indicies
rxn_measured_allcat = cell2mat(cellfun(@cell2mat,rxn_measured,'uni',false));
rxn_alt_allcat = cell2mat(cellfun(@cell2mat,rxn_alt,'uni',false));
animal_idx = cell2mat(cellfun(@(x,animal) repmat(animal,length(cell2mat(x)),1), ...
rxn_measured,num2cell(1:length(bhv))','uni',false));
day_idx = cell2mat(cellfun(@(x) cell2mat(cellfun(@(x,day) ...
repmat(day,length(x),1),x,num2cell(1:length(x))','uni',false)), ...
rxn_measured,'uni',false));
% Set bins for reaction time histograms
rxn_bins = [0:0.01:0.5];
rxn_bin_centers = rxn_bins(1:end-1) + diff(rxn_bins)./2;
% Get rxn histograms by animal/day and plot heatmap
animal_rxn = nan(max_days,length(rxn_bin_centers),length(animals));
for curr_animal = 1:length(bhv)
for curr_day = find(use_days{curr_animal})'
animal_rxn(curr_day,:,curr_animal,:) = ...
histcounts(bhv(curr_animal).stim_move_t{curr_day}, ...
rxn_bins,'normalization','probability');
end
end
figure;
imagesc([],rxn_bin_centers,nanmean(animal_rxn(plot_days,:,:),3)');
colormap(1-gray);
h = colorbar;ylabel(h,'Probability');
xlabel('Day');
ylabel('Reaction time');
caxis([0,0.12]);
% Get histogram of reaction times in day groups (across animals)
day_grps = [1,3,5,7,Inf];
day_grp = discretize(day_idx,day_grps);
figure;
h = tiledlayout(length(day_grps)-1,1);
for curr_day_grp = 1:length(day_grps)-1
animal_rxn_measured_cathist = cell2mat(arrayfun(@(x) ...
histcounts(rxn_measured_allcat( ...
animal_idx == x & ...
day_grp == curr_day_grp), ...
rxn_bins,'normalization','probability')',1:length(bhv),'uni',false));
animal_rxn_alt_cathist = cell2mat(permute( ...
arrayfun(@(rep) cell2mat(arrayfun(@(x) ...
histcounts(rxn_alt_allcat( ...
animal_idx == x & ...
day_grp == curr_day_grp,rep), ...
rxn_bins,'normalization','probability')',1:length(bhv),'uni',false)), ...
1:n_rxn_altsample,'uni',false),[1,3,2]));
animal_rxn_alt_cathist_ci = ...
squeeze(prctile(nanmean(animal_rxn_alt_cathist,2),[5,95],3));
nexttile; hold on;
AP_errorfill(rxn_bin_centers,nanmean(nanmean(animal_rxn_alt_cathist,2),3), ...
animal_rxn_alt_cathist_ci,[0.5,0.5,0.5],[],false);
plot(rxn_bin_centers,nanmean(animal_rxn_measured_cathist,2),'k','linewidth',2);
xlabel('Reaction time');
ylabel('Frequency');
title(sprintf('Day %d-%d',day_grps(curr_day_grp),day_grps(curr_day_grp+1)-1));
xlim([0,0.5]);
end
linkaxes(allchild(h),'xy');
% Reaction time median: whole day
% (exclude too-fast rxn < 0.1)
rxn_measured_med = accumarray([day_idx,animal_idx], ...
rxn_measured_allcat.*AP_nanout(rxn_measured_allcat < 0.1), ...
[max_days,length(bhv)],@(x) nanmedian(x),NaN);
rxn_alt_med = cell2mat(permute(arrayfun(@(x) ...
accumarray([day_idx,animal_idx], ...
rxn_alt_allcat(:,x).*AP_nanout(rxn_alt_allcat(:,x) < 0.1), ...
[max_days,length(bhv)],@(x) nanmedian(x),NaN), ...
1:n_rxn_altsample,'uni',false),[1,3,2]));
% (plot mice separately)
figure; h = tiledlayout('flow','TileSpacing','tight','padding','tight');
for curr_animal = 1:length(animals)
nexttile; hold on; set(gca,'YScale','log');
plot(rxn_measured_med(:,curr_animal),'k','linewidth',2);
AP_errorfill([],[],prctile(rxn_alt_med(:,curr_animal,:),[5,95],3),[0.5,0.5,0.5]);
xline(learned_day(curr_animal),'color','r');
set(gca,'children',circshift(get(gca,'children'),-1))
title(sprintf('Mouse %d',curr_animal));
ylim([0,2]);
set(gca,'YTick',[0,0.2,2,20]);
if curr_animal == 1
ylabel('Reaction time');
xlabel('Training session');
end
end
linkaxes(allchild(h),'xy');
% (plot median across mice)
figure;
subplot(1,2,1,'YScale','log');hold on
rxn_alt_med_ci = squeeze(prctile(nanmedian(rxn_alt_med,2),[5,95],3));
AP_errorfill([],[],rxn_alt_med_ci(plot_days,:),[0.5,0.5,0.5],[],false);
errorbar(nanmedian(rxn_measured_med(plot_days,:),2), ...
mad(rxn_measured_med(plot_days,:),1,2),'k','CapSize',0,'linewidth',2)
xlabel('Training day');
ylabel('Median reaction time (s)');
axis tight;
ylim([0,3]);
set(gca,'YTick',[0,0.25,0.5,1,2]);
xlim(xlim + [-0.5,0.5]);
ytickformat('%.2f')
subplot(1,2,2);hold on
rxn_measured_med_altdiff = rxn_measured_med - nanmedian(rxn_alt_med,3);
rxn_alt_med_altdiff = rxn_alt_med - nanmedian(rxn_alt_med,3);
rxn_alt_med_altdiff_ci = squeeze(prctile(nanmedian(rxn_alt_med_altdiff,2),[5,95],3));
AP_errorfill([],[],rxn_alt_med_altdiff_ci(plot_days,:),[0.5,0.5,0.5],[],false);
errorbar(nanmedian(rxn_measured_med_altdiff(plot_days,:),2), ...
mad(rxn_measured_med_altdiff(plot_days,:),1,2),'k','CapSize',0,'linewidth',2)
xlabel('Training day');
ylabel('Median reaction time (meas-null) (s)');
axis tight;
xlim(xlim + [-0.5,0.5]);
% Reaction time median: daysplit
% (exclude too-fast rxn < 0.1)
n_daysplit = 3;
daysplit_idx = cell2mat(cellfun(@(x) ...
min(floor(linspace(1,n_daysplit+1,length(x))),n_daysplit)', ...
cat(1,rxn_measured{:}),'uni',false));
rxn_measured_med_daysplit = accumarray([daysplit_idx,day_idx,animal_idx], ...
rxn_measured_allcat.*AP_nanout(rxn_measured_allcat < 0.1), ...
[n_daysplit,max_days,length(bhv)],@(x) nanmedian(x),NaN);
rxn_alt_med_daysplit = cell2mat(permute(arrayfun(@(x) ...
accumarray([daysplit_idx,day_idx,animal_idx], ...
rxn_alt_allcat(:,x).*AP_nanout(rxn_alt_allcat(:,x) < 0.1), ...
[n_daysplit,max_days,length(bhv)],@(x) nanmedian(x),NaN), ...
1:n_rxn_altsample,'uni',false),[1,3,4,2]));
% Put NaNs between days to plot with gaps
rxn_measured_med_long = reshape(padarray(rxn_measured_med_daysplit,[1,0,0],NaN,'post'),[],length(animals));
rxn_alt_med_long = reshape(padarray(rxn_alt_med_daysplit,[1,0,0],NaN,'post'),[],length(animals),n_rxn_altsample);
% Plot relative to learned day (daysplit)
learned_day_x = [1:max_days]'-learned_day';
learned_daysplit_x = cell2mat(cellfun(@(x) x+(0:n_daysplit)'/(n_daysplit+1), ...
num2cell(learned_day_x),'uni',false));
[rxn_learn_med_daysplit,rxn_learn_mad_daysplit,learned_day_grp_daysplit,learned_day_n_daysplit] = ...
grpstats(rxn_measured_med_long(:),learned_daysplit_x(:), ...
{'nanmedian',@(x) mad(x,1),'gname','numel'});
rxn_alt_learn_med_daysplit = ...
grpstats(reshape(rxn_alt_med_long,[],n_rxn_altsample),learned_daysplit_x(:), ...
{'nanmedian'});
learned_day_grp_daysplit = cellfun(@str2num,learned_day_grp_daysplit);
plot_learned = learned_day_n_daysplit >= min_n | isnan(rxn_learn_med_daysplit);
figure; hold on;set(gca,'YScale','log');
rxn_alt_learn_ci = prctile(rxn_alt_learn_med_daysplit,[1,99],2);
p1 = AP_errorfill(learned_day_grp_daysplit(plot_learned), ...
nanmean(rxn_alt_learn_med_daysplit(plot_learned,:),2), ...
rxn_alt_learn_ci(plot_learned,:),[0.5,0.5,0.5],[],false);
p2 = errorbar(learned_day_grp_daysplit(plot_learned),rxn_learn_med_daysplit(plot_learned), ...
rxn_learn_mad_daysplit(plot_learned),'k','linewidth',2,'CapSize',0);
ylabel('Median reaction time')
xlabel('Learned day');
axis tight;
line([0,0],ylim,'color','k','linestyle','--');
legend([p1(1),p2(1)],{'Null','Measured'});
set(gca,'YTick',[0,0.25,0.5,1,2]);
xlim(xlim + [-0.5,0.5]);
ylim([0,5]);
ytickformat('%.2f')
% Task performance index (rxn,alt-rxn diff/sum) by learned day (daysplit)
rxn_idx_long = (nanmean(rxn_alt_med_long,3) - rxn_measured_med_long)./ ...
(nanmean(rxn_alt_med_long,3) + rxn_measured_med_long);
[rxn_idx_learn_med_daysplit,rxn_idx_learn_mad_daysplit] = ...
grpstats(rxn_idx_long(:),learned_daysplit_x(:), ...
{'nanmedian',@(x) mad(x,1)});
figure; hold on;
errorbar(learned_day_grp_daysplit(plot_learned),rxn_idx_learn_med_daysplit(plot_learned), ...
rxn_idx_learn_mad_daysplit(plot_learned),'k','linewidth',2,'CapSize',0);
xline(0);yline(0);
xlabel('Learned day');
ylabel('Task performance index');
% (stats: just within/across learning day -1 to 0)
rxn_idx_daysplit = ...
(nanmean(rxn_alt_med_daysplit,4) - rxn_measured_med_daysplit)./ ...
(nanmean(rxn_alt_med_daysplit,4) + rxn_measured_med_daysplit);
rxn_idx_within_prelearn_day_p = ...
signrank(arrayfun(@(x) rxn_idx_daysplit(1,learned_day(x)-1,x),1:length(animals)), ...
arrayfun(@(x) rxn_idx_daysplit(end,learned_day(x)-1,x),1:length(animals)));
rxn_idx_across_prepostlearn_day_p = ...
signrank(arrayfun(@(x) rxn_idx_daysplit(end,learned_day(x)-1,x),1:length(animals)), ...
arrayfun(@(x) rxn_idx_daysplit(1,learned_day(x),x),1:length(animals)));
fprintf('Reaction index within prelearn day, signrank = %.2g\n',rxn_idx_within_prelearn_day_p);
fprintf('Reaction index across pre/post learn day, signrank = %.2g\n',rxn_idx_across_prepostlearn_day_p);
% Plot histogram of learned days
figure;histogram(learned_day,[1;plot_days]-0.5,'EdgeColor','none','FaceColor','k')
xlabel('Learned day');
ylabel('Number of mice');
xlim([0.5,max(plot_days)+0.5]);
% Plot frequency of non-response/response movements
nonresponse_move_rate = AP_padcatcell(cellfun(@(x,use_days) x(use_days), ...
{bhv.nonresponse_move_rate},use_days,'uni',false));
trial_rate = AP_padcatcell(cellfun(@(n_trials,duration,use_days) ...
n_trials(use_days)./(duration(use_days)*60), ...
{bhv.n_trials},{bhv.session_duration},use_days,'uni',false));
figure; hold on
errorbar(nanmean(nonresponse_move_rate(plot_days,:),2), ...
AP_sem(nonresponse_move_rate(plot_days,:),2),'k','linewidth',2,'CapSize',0);
errorbar(nanmean(trial_rate(plot_days,:),2), ...
AP_sem(trial_rate(plot_days,:),2),'b','linewidth',2,'CapSize',0);
legend({'Task-irrelevant move rate','Task-relevant move rate'})
xlabel('Training day');
ylabel('Rate (number/sec)')
p = anova1(nonresponse_move_rate(plot_days,:)',[],'off');
fprintf('Task-irrelevant move rate, 1-way anova = %.2d\n',p);
p = anova1(trial_rate(plot_days,:)',[],'off');
fprintf('Task-relevant move rate, 1-way anova = %.2d\n',p);
%% [FIG 1H-I, FIG S2A-B]: muscimol behavior and retinotopy
% Set animal to use
% (only use tetO mice with successful injections evidenced by retinotopic
% map loss - manually set)
muscimol_v1_animals = {'AP100','AP105','AP106','AP107','AP108'};
% Load behavior
data_path = 'C:\Users\Andrew\OneDrive for Business\Documents\CarandiniHarrisLab\analysis\operant_learning\data';
bhv_fn = [data_path filesep 'bhv_teto'];
bhv_all = load(bhv_fn);
animals_all = {bhv_all.bhv.animal};
use_animals = ismember(animals_all,muscimol_v1_animals);
bhv = bhv_all.bhv(use_animals);
% Load muscimol injection info
data_path = 'C:\Users\Andrew\OneDrive for Business\Documents\CarandiniHarrisLab\analysis\operant_learning\data';
muscimol_fn = [data_path filesep 'muscimol.mat'];
load(muscimol_fn);
% Grab day index of [last pre-muscimol, V1 muscimol, washout] and data to plot
n_conditions = 3;
condition_labels = {'Pre-muscimol','V1 muscimol','Washout'};
muscimol_v1_days = nan(length(bhv),n_conditions);
muscimol_v1_retinotopy = cell(size(muscimol_v1_days));
muscimol_v1_stim_surround_wheel = cell(size(muscimol_v1_days));
muscimol_v1_wheel_mm = nan(size(muscimol_v1_days));
muscimol_v1_nonresponse_move_rate = nan(size(muscimol_v1_days));
muscimol_v1_trial_rate = nan(size(muscimol_v1_days));
for curr_animal = 1:length(bhv)
muscimol_animal_idx = ismember({muscimol.animal},bhv(curr_animal).animal);
if ~any(muscimol_animal_idx)
continue
end
% (find last day before muscimol)
curr_premuscimol_dayidx = find(datenum(bhv(curr_animal).day) < ...
datenum(muscimol(muscimol_animal_idx).day{1}),1,'last');
% (find last V1 muscimol day)
curr_v1_muscimol = find(strcmp(lower( ...
muscimol(muscimol_animal_idx).area),'v1'),1,'last');
curr_v1_muscimol_dayidx = find(strcmp(bhv(curr_animal).day, ...
muscimol(muscimol_animal_idx).day(curr_v1_muscimol)));
% (find first washout after V1 muscimol)
curr_v1_washout = curr_v1_muscimol + ...
find(strcmp(lower( ...
muscimol(muscimol_animal_idx).area(curr_v1_muscimol+1:end)), ...
'washout'),1,'first');
curr_v1_washout_dayidx = find(strcmp(bhv(curr_animal).day, ...
muscimol(muscimol_animal_idx).day(curr_v1_washout)));
% (combine conditions)
condition_dayidx = [curr_premuscimol_dayidx,curr_v1_muscimol_dayidx,curr_v1_washout_dayidx];
% Grab days
muscimol_v1_days(curr_animal,:) = condition_dayidx;
% Grab retinotopy
% (pre-muscimol)
animal = muscimol(muscimol_animal_idx).animal;
retinotopy_path = 'C:\Users\Andrew\OneDrive for Business\Documents\CarandiniHarrisLab\analysis\widefield_alignment\retinotopy';
load([retinotopy_path filesep animal '_retinotopy'])
curr_premuscimol_vfs_dayidx = find(datenum({retinotopy.day}) < ...
datenum(muscimol(muscimol_animal_idx).day{1}),1,'last');
curr_premuscimol_vfs = AP_align_widefield( ...
retinotopy(curr_premuscimol_vfs_dayidx).vfs,animal, ...
retinotopy(curr_premuscimol_vfs_dayidx).day);
% (add post-muscimol)
muscimol_v1_retinotopy(curr_animal,:) = ...
[{curr_premuscimol_vfs} , ...
muscimol(muscimol_animal_idx).vfs([curr_v1_muscimol,curr_v1_washout])];
% Grab stim-aligned movement
% (NaN-out times during quiescence)
stim_surround_t = bhv(1).stim_surround_t;
curr_stim_surround_wheel = ...
bhv(curr_animal).stim_surround_wheel(condition_dayidx);
curr_quiescence_t = ...
bhv(curr_animal).quiescence_t(condition_dayidx);
for curr_cond = 1:2
for curr_trial = 1:size(curr_stim_surround_wheel{curr_cond},1)
q_time = stim_surround_t >= -curr_quiescence_t{curr_cond}(curr_trial) & ...
stim_surround_t <= 0;
curr_stim_surround_wheel{curr_cond}(curr_trial,q_time) = NaN;
end
end
muscimol_v1_stim_surround_wheel(curr_animal,:) = curr_stim_surround_wheel;
% Grab wheel travel/time
muscimol_v1_wheel_mm(curr_animal,:) = ...
bhv(curr_animal).wheel_mm(condition_dayidx)./ ...
bhv(curr_animal).session_duration(condition_dayidx);
% Get response/non-response movement rate
muscimol_v1_nonresponse_move_rate(curr_animal,:) = ...
bhv(curr_animal).nonresponse_move_rate(condition_dayidx);
muscimol_v1_trial_rate(curr_animal,:) = ...
bhv(curr_animal).n_trials(condition_dayidx)./ ...
(bhv(curr_animal).session_duration(condition_dayidx)*60);
end
% Plot retinotopy difference
figure;
h = tiledlayout(1,n_conditions,'TileSpacing','compact','padding','compact');
for curr_cond = 1:n_conditions
nexttile;
imagesc(nanmean(cat(3,muscimol_v1_retinotopy{:,curr_cond}),3));
axis image off;
caxis([-1,1]);
AP_reference_outline('ccf_aligned',[0.5,0.5,0.5]);
title(condition_labels{curr_cond})
end
colormap(brewermap([],'*RdBu'));
% (set 'use_days' to copy code from above)
use_days = mat2cell(muscimol_v1_days,ones(length(muscimol_v1_animals),1),n_conditions)';
% Get reaction/resampled alt reaction times for all regular days
% (exclude trials without alts: rare, from wheel click issues)
use_rxn = cellfun(@(x) cellfun(@(x) cellfun(@(x) ...
~isempty(x),x),x,'uni',false),{bhv.alt_stim_move_t},'uni',false);
rxn_measured = cellfun(@(rxn,use_days,use_trials) ...
cellfun(@(rxn,use_trials) rxn(use_trials),rxn(use_days),use_trials(use_days),'uni',false), ...
{bhv.stim_move_t},use_days,use_rxn,'uni',false)';
n_rxn_altsample = 1000;
rxn_alt = cellfun(@(rxn,use_days,use_trials) ...
cellfun(@(rxn,use_trials) ...
cell2mat(cellfun(@(x) datasample(x,n_rxn_altsample)',rxn(use_trials),'uni',false)), ...
rxn(use_days),use_trials(use_days),'uni',false), ...
{bhv.alt_stim_move_t},use_days,use_rxn,'uni',false)';
% Concat muscimol/washout
rxn_measured_cat = cat(2,rxn_measured{:});
rxn_alt_cat = cat(2,rxn_alt{:});
% Set bins for reaction time histograms
rxn_bins = [0:0.02:0.5];
rxn_bin_centers = rxn_bins(1:end-1) + diff(rxn_bins)./2;
% Plot reaction time histogram for pre/post muscimol
rxn_measured_hist = cellfun(@(x) ...
histcounts(x,rxn_bins,'normalization','probability'), ...
rxn_measured_cat,'uni',false);
rxn_alt_hist = cellfun(@(x) cell2mat(arrayfun(@(rep)...
histcounts(x(:,rep),rxn_bins,'normalization','probability'), ...
1:n_rxn_altsample,'uni',false)'),rxn_alt_cat,'uni',false);
rxn_alt_hist_ci = ...
arrayfun(@(cond) prctile(nanmean(cat(3,rxn_alt_hist{cond,:}),3), ...
[5,95],1),1:n_conditions,'uni',false);
figure;
h = tiledlayout(1,n_conditions,'TileSpacing','compact','padding','compact');
for curr_cond = 1:n_conditions
nexttile; hold on
p1 = AP_errorfill(rxn_bin_centers,[], ...
rxn_alt_hist_ci{curr_cond}',[0.5,0.5,0.5],[],false);
p2 = plot(rxn_bin_centers, ...
nanmean(cat(1,rxn_measured_hist{curr_cond,:}),1)','k','linewidth',2);
legend({'Null','Measured'});
xlabel('Reaction time');
ylabel('Probability')
title(condition_labels{curr_cond});
end
linkaxes(allchild(h),'xy');
% Plot total velocity
figure; hold on;
errorbar(nanmean(muscimol_v1_wheel_mm,1), ...
AP_sem(muscimol_v1_wheel_mm,1),'k','linewidth',2,'capsize',0);
xlim(xlim+[-0.5,0.5]);
ylim([0,max(ylim)])
set(gca,'XTick',1:n_conditions,'XTickLabel',condition_labels);
ylabel('Wheel mm/min');
p = anova1(muscimol_v1_wheel_mm,[],'off');
fprintf('Muscimol wheel travel, 1-way anova = %.2d\n',p);
% Plot response and non-response movement rate
figure; hold on;
errorbar(nanmean(muscimol_v1_nonresponse_move_rate,1), ...
AP_sem(muscimol_v1_nonresponse_move_rate,1), ...
'k','linewidth',2,'capsize',0);
errorbar(nanmean(muscimol_v1_trial_rate,1), ...
AP_sem(muscimol_v1_trial_rate,1), ...
'b','linewidth',2,'capsize',0);
xlim(xlim+[-0.5,0.5]);
ylim([0,max(ylim)])
ylabel('Rate (number/sec)')
set(gca,'XTick',1:n_conditions,'XTickLabel',condition_labels);
legend({'Task-irrelevant move rate','Task-relevant move rate'})
p = anova1(muscimol_v1_nonresponse_move_rate,[],'off');
fprintf('Muscimol task-irrelevant move rate, 1-way anova = %.2f\n',p);
p = anova1(muscimol_v1_trial_rate,[],'off');
fprintf('Muscimol task-relevant move rate, 1-way anova = %.2f\n',p);
% Get reaction times median (exclude too-fast <0.1)
rxn_measured_med = cellfun(@(x) nanmedian(x.*AP_nanout(x < 0.1),1),rxn_measured_cat);
rxn_alt_med = cell2mat(cellfun(@(x) ...
reshape(nanmedian(x.*AP_nanout(x < 0.1),1),1,1,[]),rxn_alt_cat,'uni',false));
rxn_measured_med_altdiff = rxn_measured_med - nanmean(rxn_alt_med,3);
rxn_alt_med_altdiff = rxn_alt_med - nanmean(rxn_alt_med,3);
figure;
subplot(1,2,1,'YScale','log'); hold on;
rxn_alt_med_ci = permute(prctile(nanmean(rxn_alt_med,2),[5,95],3),[1,3,2]);
AP_errorfill([],nanmean(rxn_alt_med_ci,2),rxn_alt_med_ci,[0.5,0.5,0.5],[],false);
errorbar(nanmean(rxn_measured_med,2),AP_sem(rxn_measured_med,2),'k','linewidth',2,'capsize',0);
xlim([0,n_conditions] + 0.5);
set(gca,'XTick',1:n_conditions,'XTickLabel',condition_labels);
ylabel('Median reaction time (s)');
set(gca,'YTick',[0,0.25,0.5,1,2]);
xlim(xlim + [-0.5,0.5]);
ylim([0,3]);
ytickformat('%.2f')
p = anova1(rxn_measured_med',[],'off');
fprintf('Muscimol reaction time, 1-way anova = %.2d\n',p);
subplot(1,2,2); hold on
rxn_alt_med_altdiff_ci = permute(prctile(nanmean(rxn_alt_med_altdiff,2),[5,95],3),[1,3,2]);
AP_errorfill([],nanmean(rxn_alt_med_altdiff_ci,2),rxn_alt_med_altdiff_ci,[0.5,0.5,0.5],[],false);
errorbar(nanmean(rxn_measured_med_altdiff,2),AP_sem(rxn_measured_med_altdiff,2),'k','linewidth',2,'capsize',0);
xlim([0,n_conditions] + 0.5);
set(gca,'XTick',1:n_conditions,'XTickLabel',condition_labels);
ylabel('Median reaction time (meas-null,s)');
%% >> [FIG 2A]: task pixels stim/move aligned by novice/learned
% Set trials to use
learned_day_grp_edges = [-Inf,0,Inf];
trial_learned_day_grp = discretize(trial_learned_day,learned_day_grp_edges);
n_learn_grps = length(learned_day_grp_edges)-1;
% Set timepoints post stim/move
plot_t = {0.1,0};
align_labels = {'Stim','Move'};
% Get interpolated time points aligned to stim and move
align_v = cell(2,1);
for curr_align = 1:2
switch curr_align
case 1
curr_v_align = fluor_allcat_deconv;
case 2
curr_v_align = fluor_move_allcat_deconv;
end
curr_v_align_avg = nan(n_vs,length(t),n_learn_grps, ...
length(animals),class(curr_v_align));
for curr_animal = 1:length(animals)
for curr_learned_grp = 1:n_learn_grps
curr_trials = trial_animal == curr_animal & ...
trial_learned_day_grp == curr_learned_grp & ...
trial_outcome_allcat == 1;
curr_v_align_avg(:,:,curr_learned_grp,curr_animal) = ...
permute(nanmean(curr_v_align(curr_trials,:,:),1),[3,2,1]);
end
end
% (get time point and store)
curr_v_align_t = permute( ...
interp1(t,permute(curr_v_align_avg,[2,1,3,4]),plot_t{curr_align}), ...
[2,1,3,4]);
align_v{curr_align} = curr_v_align_t;
end
% Get average pixels across animals
align_px_avg = cellfun(@(x) ...
nanmean(AP_svdFrameReconstruct(U_master(:,:,1:n_vs),x),5), ...
align_v,'uni',false);
% Plot pixels
c = [0,0.007];
figure;
h = tiledlayout(n_learn_grps,length(cell2mat(plot_t)), ...
'TileSpacing','compact','padding','compact');
for curr_learn_grp = 1:n_learn_grps
for curr_align = 1:2
for curr_plot_t = 1:length(plot_t{curr_align})
curr_px = align_px_avg{curr_align}(:,:,curr_plot_t,curr_learn_grp);
nexttile
imagesc(curr_px);
AP_reference_outline('ccf_aligned',[0.5,0.5,0.5]);
AP_reference_outline('bregma_aligned','k');
axis image off;
colormap(gca,AP_colormap('WG',[],1.5));
caxis(c);
title([align_labels{curr_align} ': ' num2str(plot_t{curr_align}(curr_plot_t)) ' sec']);
end
end
end
AP_reference_outline('scalebar','m');
linkaxes(allchild(h),'xy');
colorbar;
%% >> [FIG 2B]: task pixels hemidiff stim window by novice/learned
% Set trials to use
learned_day_grp_edges = [-Inf,0,Inf];
trial_learned_day_grp = discretize(trial_learned_day,learned_day_grp_edges);
n_learn_grps = length(learned_day_grp_edges)-1;
fluor_learning_animal = nan(n_vs,length(t),n_learn_grps, ...
length(animals),class(fluor_allcat_deconv));
for curr_animal = 1:length(animals)
for curr_learned_grp = 1:n_learn_grps
curr_trials = trial_animal == curr_animal & ...
trial_learned_day_grp == curr_learned_grp & ...
trial_outcome_allcat == 1;
fluor_learning_animal(:,:,curr_learned_grp,curr_animal) = ...
permute(nanmean(fluor_allcat_deconv(curr_trials,:,:),1),[3,2,1]);
end
end
fluor_learning_animal_px = AP_svdFrameReconstruct(U_master(:,:,1:n_vs),fluor_learning_animal);
fluor_learning_animal_px_avg = nanmean(fluor_learning_animal_px,5);
fluor_learning_animal_px_hemidiff_avg = nanmean(fluor_learning_animal_px - ...
cat(5,fluor_move_nostim_rewardable_animalavg_px_hemiratio{:}).* ...
AP_reflect_widefield(fluor_learning_animal_px),5);
% (white-out non-imaged pixels)
fluor_learning_animal_px_hemidiff_avg(isnan(fluor_learning_animal_px_hemidiff_avg)) = 0;
% Plot movies (for presentations)
AP_imscroll(fluor_learning_animal_px_avg,t)
caxis(max(abs(caxis))*[-1,1]);
colormap(AP_colormap('KWG',[],1.5));
axis image off;
AP_reference_outline('ccf_aligned',[0.5,0.5,0.5]);
AP_imscroll(fluor_learning_animal_px_hemidiff_avg(:,1:size(U_master,2)/2,:,:),t)
caxis(max(abs(caxis))*[-1,1]);
colormap(AP_colormap('KWP',[],1.5));
axis image off;
AP_reference_outline('ccf_aligned_lefthemi',[0.5,0.5,0.5]);
% Get time window fluorescence
use_t = t >= 0 & t <= 0.2;
figure; tiledlayout(2,2);
c = [0,0.007];
c_hemi = [0,0.002];
for curr_learn = 1:n_learn_grps
nexttile;
imagesc(max(fluor_learning_animal_px_avg(:,:,use_t,curr_learn),[],3));
colormap(gca,AP_colormap('WG',[],1.5)); caxis(c);
axis image off;
AP_reference_outline('ccf_aligned',[0.5,0.5,0.5]);
AP_reference_outline('bregma_aligned','k');
colorbar
nexttile;
imagesc(max(fluor_learning_animal_px_hemidiff_avg(:,1:size(U_master,2)/2,use_t,curr_learn),[],3));
colormap(gca,AP_colormap('WP',[],1.5)); caxis(c_hemi);
axis image off;
AP_reference_outline('ccf_aligned_lefthemi',[0.5,0.5,0.5]);
AP_reference_outline('bregma_aligned','k');
colorbar
end
AP_reference_outline('scalebar','m');
%% >> [FIG 2C]: ROI stim-aligned sorted trials
plot_rois = [1,7,6];
trial_learned_stage = discretize(trial_learned_day,[-Inf,0,Inf]);
n_trial_smooth = 200;
% Set activity
roi_hemiflip = circshift(1:n_rois,n_rois/2);
curr_act = fluor_roi_deconv;
% Plot trial activity
figure;
h = tiledlayout(2,length(plot_rois));
for curr_stage = 1:max(trial_learned_stage)
for curr_roi = plot_rois
use_trials = find(trial_learned_stage == curr_stage);
[~,sort_idx] = sort(move_t(use_trials));
curr_data_sort = curr_act(use_trials(sort_idx),:,curr_roi);
curr_data_sort_smooth = convn(curr_data_sort, ...
ones(n_trial_smooth,1)./n_trial_smooth,'same');
nexttile;
imagesc(t,[],curr_data_sort_smooth);hold on;
caxis(0.007.*[-1,1])
colormap(AP_colormap('KWG',[],1));
xline(0,'color',[0.8,0,0],'linewidth',2);
plot(move_t(use_trials(sort_idx)),1:length(use_trials),'color','k','linewidth',2);
xlabel('Time from stim (s)');
ylabel('Trial (rxn-time sorted)');
title(sprintf('%s, stage %d',wf_roi(curr_roi).area,curr_stage));
end
end
linkaxes(allchild(h),'xy');
xlim([-0.2,1]);
ax = reshape(flipud(allchild(h)),[],2)';
x_scale = 0.2;
y_scale = 2000;
axes(ax(1,end)); AP_scalebar(x_scale,y_scale);
axes(ax(2,end)); AP_scalebar(x_scale,y_scale);
colorbar;
%% >> [FIG 2D]: task average hemidiff ROI timecourse (stim/move align, novice/learned)
plot_rois = [1,7,6];
trial_learned_stage = discretize(trial_learned_day,[-Inf,0,Inf]);
% Set activity
roi_hemiflip = circshift(1:n_rois,n_rois/2);
curr_act = fluor_roi_deconv - ...
trial_move_hemiratio.*fluor_roi_deconv(:,:,roi_hemiflip);
curr_act_move = fluor_move_roi_deconv - ...
trial_move_hemiratio.*fluor_move_roi_deconv(:,:,roi_hemiflip);
% Get indicies for averaging (learned stage x t x roi x animal)
[learned_day_idx,t_idx,roi_idx] = ...
ndgrid(trial_learned_day_id,1:length(t),1:n_rois);
[learned_stage_idx,~] = ndgrid(trial_learned_stage,1:length(t),1:n_rois);
[animal_idx,~,~] = ...
ndgrid(trial_animal,1:length(t),1:n_rois);
accum_stage_idx = cat(4,learned_stage_idx,t_idx,roi_idx,animal_idx);
% (roi activity avg: learned stage x t x roi x animal)
roi_stim_learn_avg = accumarray( ...
reshape(accum_stage_idx,[],size(accum_stage_idx,4)), ...
curr_act(:), ...
[max(trial_learned_stage),length(t),n_rois,length(animals)], ...
@nanmean,NaN('single'));
roi_move_learn_avg = accumarray( ...
reshape(accum_stage_idx,[],size(accum_stage_idx,4)), ...
curr_act_move(:), ...
[max(trial_learned_stage),length(t),n_rois,length(animals)], ...
@nanmean,NaN('single'));
% Plot L-R stim/move, learning overlaid
median_move_t = median(move_t(trial_learned_day>0));
x_limit = [-0.1,median_move_t];
figure;
h = tiledlayout(1,length(plot_rois)*2);
stage_col = min(1,AP_colormap('WP',1) + [0.5;0]);
for curr_roi = plot_rois
curr_data_stim = permute(roi_stim_learn_avg(:,:,curr_roi,:),[2,1,4,3]);
curr_data_move = permute(roi_move_learn_avg(:,:,curr_roi,:),[2,1,4,3]);
nexttile; hold on;
AP_errorfill(t,nanmean(curr_data_stim,3),AP_sem(curr_data_stim,3),stage_col);
xlabel('Stim');
ylabel(wf_roi(curr_roi).area(1:end-2));
xline(0);yline(0);set(gca,'children',circshift(get(gca,'children'),-2))