-
Notifications
You must be signed in to change notification settings - Fork 1
/
AP_ctx_str_figures_published.m
6282 lines (5016 loc) · 249 KB
/
AP_ctx_str_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 ctx-str paper
% (data is prepared in AP_ctx_str_trial_preprocessing)
%
% Code blocks with preceeding symbols: run code block at top with
% corresponding symbol to load data
%
% If no symbol: code is loaded within code block
%% ~~~~~~~~~~~~~ Load data associated with each symbol
%% ++ Depth-aligned striatum
data_fn = 'trial_activity_choiceworld_16strdepth'; % Depth-aligned striatum
AP_load_concat_normalize_ctx_str;
% Choose split for data
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{:}));
use_split = trials_recording;
split_idx = cell2mat(arrayfun(@(exp,trials) repmat(exp,trials,1), ...
[1:length(use_split)]',reshape(use_split,[],1),'uni',false));
%% ** Task (combined: original,ctxephys,pre-muscimol)
data_fn = { ...
'trial_activity_choiceworld'...
'trial_activity_vanillaChoiceworld_ctxstrephys_str'...
'trial_activity_vanillaChoiceworldNoRepeats_pre_muscimol'};
AP_load_concat_normalize_ctx_str;
% Choose split for data
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{:}));
use_split = trials_recording;
split_idx = cell2mat(arrayfun(@(exp,trials) repmat(exp,trials,1), ...
[1:length(use_split)]',reshape(use_split,[],1),'uni',false));
%% @@ Task single unit/celltypes (combined: original,ctxephys,pre-muscimol)
data_fn = { ...
'trial_activity_choiceworld_sua.mat', ... % original
'trial_activity_ctx_task_sua.mat', ... % + cortex ephys
'trial_activity_muscimol_task_sua.mat'}; % muscimol group
% (turn on warnings)
warning on;
% Load data (saved as structure trial_data_all)
trial_data_path = 'C:\Users\Andrew\OneDrive for Business\Documents\CarandiniHarrisLab\analysis\wf_ephys_choiceworld\paper\data';
if ischar(data_fn)
% Single dataset
disp(['Loading ' data_fn '...']);
load([trial_data_path filesep data_fn]);
elseif iscell(data_fn)
% Multiple datasets to merge (this is really dirty)
preload_vars = who;
% (load in all datasets)
clear temp_data
for curr_load_data = 1:length(data_fn)
disp(['Loading ' data_fn{curr_load_data} '...']);
temp_data{curr_load_data} = load([trial_data_path filesep data_fn{curr_load_data}],'trial_data_all');
% trial_data_all_split(curr_data) = temp_data.trial_data_all;
end
% (find shared fields - need to iterate intersect if > 2 datasets)
split_fieldnames = cellfun(@(x) fieldnames(x.trial_data_all),temp_data,'uni',false);
intersect_fieldnames = intersect(split_fieldnames{1},split_fieldnames{2});
if length(data_fn) > 2
for curr_intersect = 3:length(data_fn)
intersect_fieldnames = intersect(intersect_fieldnames,split_fieldnames{curr_intersect});
end
end
% (initialize combined structure)
trial_data_all = cell2struct(cell(size(intersect_fieldnames)),intersect_fieldnames);
data_animals = arrayfun(@(x) temp_data{x}.trial_data_all.animals,1:length(data_fn),'uni',false);
trial_data_all.animals = horzcat(data_animals{:});
% (concatenate experiment fields)
experiment_fields = cellfun(@(curr_field) ...
length(temp_data{1}.trial_data_all.(curr_field)) == ...
length(temp_data{1}.trial_data_all.animals) && ...
iscell(temp_data{1}.trial_data_all.(curr_field)) && ...
any(cellfun(@(x) iscell(x),temp_data{1}.trial_data_all.(curr_field))),intersect_fieldnames);
for curr_field = intersect_fieldnames(experiment_fields)'
for curr_load_data = 1:length(data_fn)
trial_data_all.(curr_field{:}) = ...
cat(1,trial_data_all.(curr_field{:}), ...
reshape(temp_data{curr_load_data}.trial_data_all.(curr_field{:}),[],1));
end
end
% (grab non-experiment fields from the first dataset)
% (NOTE: this assumes they're the same)
for curr_field = intersect_fieldnames(~experiment_fields & ...
~strcmp(intersect_fieldnames,'animals'))'
trial_data_all.(curr_field{:}) = ...
temp_data{1}.trial_data_all.(curr_field{:});
end
% (if mixing protocols: ensure stimIDs convered into contrast*side)
for curr_animal = 1:length(trial_data_all.trial_info_all)
for curr_day = 1:length(trial_data_all.trial_info_all{curr_animal})
curr_stim = trial_data_all.trial_info_all{curr_animal}{curr_day}.stimulus;
if length(unique(curr_stim)) == 3 && all(unique(curr_stim) == [1;2;3])
% Stim [1,2,3] are coded stim IDs
curr_stim_recode = curr_stim;
% For both mpep and signals, ID is 1 = left, 2 = center, 3 = right
curr_stim_recode(curr_stim == 1) = -1;
curr_stim_recode(curr_stim == 2) = 0;
curr_stim_recode(curr_stim == 3) = 1;
trial_data_all.trial_info_all{curr_animal}{curr_day}.stimulus = ...
curr_stim_recode;
end
end
end
% clear temp variables
clearvars('-except',preload_vars{:},'data_fn','trial_data_all')
else
error('Unrecognized data_fn type')
end
% Julie's bugfixes
% (combines 2 TAN categories, integrates old 'other' with UINs, puts short
% waveforms that look like TANs into new 'other')
removeMissingSpikesUnits = true;
for iAnimal = 1:size(trial_data_all.goodUnits, 1)
for iRecording = 1:size(trial_data_all.goodUnits{iAnimal}, 1)
% 1. if flag remove spikes missing, add these to the goodUnits
if removeMissingSpikesUnits
trial_data_all.goodUnits{iAnimal}{iRecording} = trial_data_all.goodUnits{iAnimal}{iRecording} ...
& nanmin(trial_data_all.percent_missing_ndtr{iAnimal}{iRecording}(2:end, :)) < 30;
end
% 2. re-classify to: add noise guys to uins, remove large post spike suppression FSI and UINs, and short waveform guys from TANs.
if ~isempty(trial_data_all.acg{iAnimal}{iRecording})
for iCell = 1:size(trial_data_all.acg{iAnimal}{iRecording}, 1)
pss_allcat2temp = find(trial_data_all.acg{iAnimal}{iRecording}(iCell, 500:1000) >= nanmean(trial_data_all.acg{iAnimal}{iRecording}(iCell, 600:900)));
pss_allcat2(iCell) = pss_allcat2temp(1);
end
allDepths = zeros(size(trial_data_all.allGroups{iAnimal}{iRecording},2),1);
allDepths(ismember(trial_data_all.allGroups{iAnimal}{iRecording}, [1,4,7,10,13,16]))=1;
allDepths(ismember(trial_data_all.allGroups{iAnimal}{iRecording}, [2,5,8,11,14,17]))=2;
allDepths(ismember(trial_data_all.allGroups{iAnimal}{iRecording}, [3,6,9,12,15,18]))=3;
largePssShorties = find(trial_data_all.templateDuration{iAnimal}{iRecording} < 400 & pss_allcat2' > 40);
fsi = trial_data_all.templateDuration{iAnimal}{iRecording} <= 400 & pss_allcat2 < 40 & trial_data_all.prop_long_isi{iAnimal}{iRecording} <= 0.1;
uin = trial_data_all.templateDuration{iAnimal}{iRecording} <= 400 & pss_allcat2 < 40 & trial_data_all.prop_long_isi{iAnimal}{iRecording} > 0.1;
tan = trial_data_all.templateDuration{iAnimal}{iRecording} > 400 & pss_allcat2 >= 40;
msn = trial_data_all.templateDuration{iAnimal}{iRecording} > 400 & pss_allcat2 < 40;
shortDurLongPss = trial_data_all.templateDuration{iAnimal}{iRecording} <= 400 & pss_allcat2 >= 40;
trial_data_all.allGroups{iAnimal}{iRecording}(msn) = allDepths(msn);
trial_data_all.allGroups{iAnimal}{iRecording}(fsi) = allDepths(fsi) + 3;
trial_data_all.allGroups{iAnimal}{iRecording}(tan) = allDepths(tan) + 6;
trial_data_all.allGroups{iAnimal}{iRecording}(uin) = allDepths(uin) + 9;
trial_data_all.allGroups{iAnimal}{iRecording}(shortDurLongPss) = allDepths(shortDurLongPss) + 12;
clearvars pss_allcat2
end
end
end
% Find fields with experiment data (cell arrays with length animals)
data_struct_fieldnames = fieldnames(trial_data_all);
experiment_fields = cellfun(@(curr_field) ...
length(trial_data_all.(curr_field)) == length(trial_data_all.animals) && ...
iscell(trial_data_all.(curr_field)) && ...
any(cellfun(@(x) iscell(x),trial_data_all.(curr_field))),data_struct_fieldnames);
% Load pre-marked experiments to exclude and cut out bad ones
if exist('exclude_data','var') && exclude_data
exclude_path = 'C:\Users\Andrew\OneDrive for Business\Documents\CarandiniHarrisLab\analysis\wf_ephys_choiceworld\experiment_exclusion';
exclude_fn = 'bhv_use_experiments';
load([exclude_path filesep exclude_fn]);
% Pull out used experiments for the animals loaded
use_experiments_animals = ismember(trial_data_all.animals,{bhv_use_experiments.animals});
use_experiments = {bhv_use_experiments(use_experiments_animals).use_experiments}';
% (old, when multiple kinds of exclusions
% exclude_fn{1} = 'bhv_use_experiments';
% % exclude_fn{2} = 'expl_var_use_experiments';
% use_experiments_all = {};
% for curr_exclude = 1:length(exclude_fn)
% curr_use_experiments = load([exclude_path filesep exclude_fn{curr_exclude}]);
% use_experiments_all = [use_experiments_all;curr_use_experiments.use_experiments];
% end
% use_experiments = arrayfun(@(x) all(vertcat(use_experiments_all{:,x}),1), ...
% 1:size(use_experiments_all,2),'uni',false)';
% Cut out bad experiments for any experiment data fields
if ~isempty(use_experiments)
for curr_field = data_struct_fieldnames(experiment_fields)'
trial_data_all.(cell2mat(curr_field)) = cellfun(@(x,expts) ...
x(expts),trial_data_all.(cell2mat(curr_field)), ...
use_experiments,'uni',false);
end
end
end
% If any animals don't have any data - throw away
nodata_animals = cellfun(@(x) isempty(x),trial_data_all.trial_info_all);
trial_data_all.animals(nodata_animals) = [];
for curr_field = data_struct_fieldnames(experiment_fields)'
trial_data_all.(cell2mat(curr_field))(nodata_animals) = [];
end
% Unpack data structure into workspace then throw away
arrayfun(@(x) assignin('base',cell2mat(x),trial_data_all.(cell2mat(x))),data_struct_fieldnames);
clear trial_data_all
% Get sample rate and set "baseline" time
sample_rate = 1/mean(diff(t));
t_baseline = t < 0;
% Get if this is a task dataset
task_dataset = exist('outcome_all','var');
% Concatenate trial info data
trial_info_fields = fieldnames(trial_info_all{end}{end});
trial_info_allcat = cell2struct(arrayfun(@(curr_field) ...
cell2mat(cellfun(@(x) x(curr_field), ...
cellfun(@struct2cell,vertcat(trial_info_all{:}),'uni',false))), ...
1:length(trial_info_fields),'uni',false),trial_info_fields,2);
% Concatenate wheel
wheel_allcat = cell2mat(vertcat(wheel_all{:}));
% % (movement from mousecam if exists: normalize and concatenate)
% if exist('movement_all','var')
% movement_all_norm = cellfun(@(x) cellfun(@(x) x./nanstd(x(:)), ...
% x,'uni',false),movement_all,'uni',false);
% movement_allcat = cell2mat(vertcat(movement_all_norm{:}));
% end
%%% Get task/stim-relevant
if task_dataset
% Get trial information
trial_stim_allcat = trial_info_allcat.stimulus; % old: diff(trial_info_allcat.stimulus,[],2);
trial_choice_allcat = -(trial_info_allcat.response-1.5)*2;
trial_outcome_allcat = trial_info_allcat.outcome;
% Get reaction time and t index for movement onset
move_t = trial_info_allcat.stim_to_move;
[~,move_idx] = min(abs(move_t - t),[],2);
% Get outcome time
outcome_allcat = cell2mat(vertcat(outcome_all{:}));
[~,outcome_idx] = max(any(outcome_allcat,3),[],2);
outcome_t = t(outcome_idx)';
% Get wheel velocity
wheel_velocity_allcat = wheel_allcat;
[max_speed,max_vel_idx] = max(abs(wheel_velocity_allcat(:,:,1).* ...
(bsxfun(@times,wheel_velocity_allcat,trial_choice_allcat) > 0)),[],2);
max_vel = max_speed.*trial_choice_allcat;
wheel_velocity_allcat_move = wheel_velocity_allcat;
t_leeway = -t(1);
leeway_samples = round(t_leeway*(sample_rate));
for i = 1:size(wheel_velocity_allcat,1)
wheel_velocity_allcat_move(i,:,:) = circshift(wheel_velocity_allcat_move(i,:,:),-move_idx(i)+leeway_samples,2);
end
elseif isfield(trial_info_allcat,'stimulus')
if length(unique(trial_info_allcat.stimulus)) == 3 && ...
all(unique(trial_info_allcat.stimulus) == [1;2;3])
% Use stim IDs
trial_stim_allcat = trial_info_allcat.stimulus;
% For both mpep and signals, ID is 1 = left, 2 = center, 3 = right
trial_stim_allcat(trial_stim_allcat == 1) = -1;
trial_stim_allcat(trial_stim_allcat == 2) = 0;
trial_stim_allcat(trial_stim_allcat == 3) = 1;
else
% Passive choiceworld uses stimID = side*contrast
trial_stim_allcat = trial_info_allcat.stimulus;
end
end
% Choose split for data
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{:}));
use_split = trials_recording;
split_idx = cell2mat(arrayfun(@(exp,trials) repmat(exp,trials,1), ...
[1:length(use_split)]',reshape(use_split,[],1),'uni',false));
% Concatenate depths
depth_allcat = cell2mat(cellfun(@(x) x(~isnan(x)), ...
vertcat(allDepths{:}),'uni',false));
% Concatenate groups and make logical vectors
groups_allcat = cell2mat(cellfun(@(x) x(~isnan(x)), ...
vertcat(allGroups{:}),'uni',false));
% Concatenate good units
good_units_exp = cellfun(@transpose,vertcat(goodUnits{:}),'uni',false);
good_units_allcat = cell2mat(vertcat(goodUnits{:})')';
% (groups are cell type * depth: msn, fsi, tan, uin, narrow tan-like)
n_aligned_depths = 3; % hardcoded: I think not stored
n_celltypes = max(groups_allcat)./n_aligned_depths;
if n_celltypes ~= 5
error('Incorrect number of celltypes')
end
celltype_allcat = ceil(groups_allcat./n_aligned_depths);
celltype_labels = {'MSN','FSI','TAN','UIN','Short bursty TAN-like'};
domain_allcat = mod(groups_allcat,n_aligned_depths) + ...
n_aligned_depths*(mod(groups_allcat,n_aligned_depths) == 0);
% Get maps for all cells
% (load master U)
load('C:\Users\Andrew\OneDrive for Business\Documents\CarandiniHarrisLab\analysis\wf_ephys_choiceworld\wf_processing\wf_alignment\U_master');
% (use t = 0 kernels for all cells, hardcoded at the moment)
use_k_frame = 5;
ctx_str_k_frame = cell2mat(cellfun(@(x) reshape(x(:,use_k_frame,:),100,[]), ...
vertcat(ctx_str_k_all{:})','uni',false));
ctx_str_k_px = svdFrameReconstruct(U_master(:,:,1:100),ctx_str_k_frame(:,good_units_allcat));
% Deconvolve fluorescence and get kernel ROIs
fluor_deconv_allcat_exp = cellfun(@(x) AP_deconv_wf(x),vertcat(fluor_all{:}),'uni',false);
n_vs = size(fluor_all{end}{end},3);
kernel_roi_fn = 'C:\Users\Andrew\OneDrive for Business\Documents\CarandiniHarrisLab\analysis\wf_ephys_choiceworld\wf_processing\wf_rois\kernel_roi';
load(kernel_roi_fn);
fluor_kernelroi_deconv_exp = cellfun(@(x) ...
permute(AP_deconv_wf(AP_svd_roi(U_master(:,:,1:n_vs), ...
permute(x-nanmean(x(:,t < 0,:),2),[3,2,1]),[],[],kernel_roi.bw)),[3,2,1]), ...
vertcat(fluor_all{:}),'uni',false);
% Get animals/days/cell number
% (note this includes cortical cells, which are NaNs in allGroups)
animals_allcat = cell2mat(cellfun(@(x,grp) x(~isnan(grp)), ...
vertcat(allAnimals{:}),vertcat(allGroups{:}),'uni',false));
days_allcat = cell2mat(cellfun(@(x,grp) x(~isnan(grp)), ...
vertcat(allDays{:}),vertcat(allGroups{:}),'uni',false));
neurons_allcat = cell2mat(cellfun(@(x,grp) x(~isnan(grp))', ...
vertcat(allNeurons{:}),vertcat(allGroups{:}),'uni',false));
recordings_allcat = cell2mat(cellfun(@(x,grp) x*ones(sum(~isnan(grp)),1), ...
num2cell((1:length(vertcat(allDays{:})))'),vertcat(allGroups{:}),'uni',false));
%%% Align by relative depth
ephys_align_path = 'C:\Users\Andrew\OneDrive for Business\Documents\CarandiniHarrisLab\analysis\wf_ephys_choiceworld\ephys_processing';
ephys_align_fn = ['ephys_depth_align.mat'];
load([ephys_align_path filesep ephys_align_fn]);
% Pull out relative depths for each cell
depth_aligned = cell(size(mua_all));
for curr_animal = 1:length(mua_all)
curr_animal_idx = strcmp(animals{curr_animal},{ephys_depth_align.animal});
for curr_day = 1:length(mua_all{curr_animal})
% (relative to end)
depth_aligned{curr_animal}{curr_day} = ...
allDepths{curr_animal}{curr_day}(~isnan(allDepths{curr_animal}{curr_day})) - ...
ephys_depth_align(curr_animal_idx).str_depth(curr_day,2);
% % (relative to start:end)
% depth_aligned{curr_animal}{curr_day} = ...
% (allDepths{curr_animal}{curr_day}(~isnan(allDepths{curr_animal}{curr_day})) - ...
% ephys_depth_align(curr_animal_idx).str_depth(curr_day,1))./ ...
% diff(ephys_depth_align(curr_animal_idx).str_depth(curr_day,:));
end
end
depth_aligned_allcat = cell2mat(horzcat(depth_aligned{:})');
%%% Align by domain
% Load domain alignment
n_aligned_depths = 3;
ephys_kernel_align_path = 'C:\Users\Andrew\OneDrive for Business\Documents\CarandiniHarrisLab\analysis\wf_ephys_choiceworld\ephys_processing';
ephys_kernel_align_fn = ['ephys_kernel_align_' num2str(n_aligned_depths) '_depths.mat'];
load([ephys_kernel_align_path filesep ephys_kernel_align_fn]);
% Loop through cells, pull out domains
domain_aligned = cell(size(mua_all));
for curr_animal = 1:length(mua_all)
depth_curr_animal_idx = strcmp(animals{curr_animal},{ephys_depth_align.animal});
kernel_curr_animal_idx = strcmp(animals{curr_animal},{ephys_kernel_align.animal});
for curr_day = 1:length(mua_all{curr_animal})
str_depth = ephys_depth_align(depth_curr_animal_idx).str_depth(curr_day,:);
kernel_match = ephys_kernel_align(kernel_curr_animal_idx).kernel_match{curr_day};
% Get depth groups
n_depths = round(diff(str_depth)/200);
depth_group_edges = round(linspace(str_depth(1),str_depth(2),n_depths+1));
% Get domain depth boundaries
kernel_match_boundary_idx = unique([1;find(diff(kernel_match) ~= 0)+1;n_depths+1]);
kernel_match_depth_edges = depth_group_edges(kernel_match_boundary_idx);
% (extend first and last forever - sometimes cells a little past
% the border but classified as str probably because changed border
% calculation slightly)
kernel_match_depth_edges(1) = -Inf;
kernel_match_depth_edges(end) = Inf;
kernel_match_idx = kernel_match(kernel_match_boundary_idx(1:end-1));
% Assign neurons to domains
domain_aligned{curr_animal}{curr_day} = ...
discretize(allDepths{curr_animal}{curr_day}(~isnan(allDepths{curr_animal}{curr_day})), ...
kernel_match_depth_edges,kernel_match_idx);
end
end
domain_aligned_allcat = cell2mat(horzcat(domain_aligned{:})');
disp('Finished.')
%% ~~~~~~~~~~~~~ Main figures (some EDF included)
%% Fig 1a-d: Example recording
animal = 'AP025';
day = '2017-10-01';
experiment = 1;
str_align = 'none';
verbose = true;
AP_load_experiment;
%%% Plot example data
% Align U's, deconvolve widefield
use_components = 1:200;
aUdf = AP_align_widefield(Udf,animal,day);
fVdf_deconv = AP_deconv_wf(fVdf);
% Set time to plot
plot_t = [15,45];
raster_fig = figure;
% (wheel velocity)
wheel_axes = subplot(6,1,6);
plot_wheel_idx = Timeline.rawDAQTimestamps >= plot_t(1) & ...
Timeline.rawDAQTimestamps <= plot_t(2);
plot(wheel_axes,Timeline.rawDAQTimestamps(plot_wheel_idx), ...
wheel_velocity(plot_wheel_idx),'k','linewidth',2);
ylabel('Wheel velocity');
axis off
% (stimuli)
stim_col = colormap_BlueWhiteRed(5);
[~,trial_contrast_idx] = ...
ismember(trial_conditions(:,1).*trial_conditions(:,2),unique(contrasts'.*sides),'rows');
stim_lines = arrayfun(@(x) line(wheel_axes,repmat(stimOn_times(x),1,2),ylim(wheel_axes),'color', ...
stim_col(trial_contrast_idx(x),:),'linewidth',2), ...
find(stimOn_times >= plot_t(1) & stimOn_times <= plot_t(2)));
% (movement starts)
move_col = [0.6,0,0.6;0,0.6,0];
[~,trial_choice_idx] = ismember(trial_conditions(:,3),[-1;1],'rows');
move_lines = arrayfun(@(x) line(wheel_axes,repmat(wheel_move_time(x),1,2),ylim(wheel_axes),'color', ...
move_col(trial_choice_idx(x),:),'linewidth',2), ...
find(wheel_move_time >= plot_t(1) & wheel_move_time <= plot_t(2)));
% (go cues)
go_col = [0.8,0.8,0.2];
go_cue_times = signals_events.interactiveOnTimes(1:n_trials);
go_cue_lines = arrayfun(@(x) line(wheel_axes,repmat(go_cue_times(x),1,2),ylim(wheel_axes),'color', ...
go_col,'linewidth',2), ...
find(go_cue_times >= plot_t(1) & go_cue_times <= plot_t(2)));
% (outcomes)
outcome_col = [0,0,0.8;0.5,0.5,0.5];
reward_lines = arrayfun(@(x) line(wheel_axes,repmat(reward_t_timeline(x),1,2),ylim(wheel_axes),'color', ...
outcome_col(1,:),'linewidth',2), ...
find(reward_t_timeline >= plot_t(1) & reward_t_timeline <= plot_t(2)));
punish_times = signals_events.responseTimes(trial_outcome == -1);
punish_lines = arrayfun(@(x) line(wheel_axes,repmat(punish_times(x),1,2),ylim(wheel_axes),'color', ...
outcome_col(2,:),'linewidth',2), ...
find(punish_times >= plot_t(1) & punish_times <= plot_t(2)));
% (striatum raster)
raster_axes = subplot(6,1,3:5,'YDir','reverse'); hold on;
plot_spikes = spike_times_timeline >= plot_t(1) & ...
spike_times_timeline <= plot_t(2) & ...
spike_depths >= str_depth(1) & spike_depths <= str_depth(2);
plot(raster_axes,spike_times_timeline(plot_spikes),spike_depths(plot_spikes),'.k');
ylabel('Depth (\mum)');
xlabel('Time (s)');
depth_scale = 1000;
line(repmat(min(xlim),2,1),[min(ylim),min(ylim) + depth_scale],'color','k','linewidth',3);
axis off
% (fluorescence from select ROIs)
wf_roi_fn = 'C:\Users\Andrew\OneDrive for Business\Documents\CarandiniHarrisLab\analysis\wf_ephys_choiceworld\wf_processing\wf_rois\wf_roi';
load(wf_roi_fn);
roi_trace = AP_svd_roi(aUdf(:,:,use_components),fVdf_deconv(use_components,:),[],[],cat(3,wf_roi.mask));
plot_rois = [1,11,7,17,9,19,10,20];
fluor_spacing = []; % (use default)
fluor_axes = subplot(6,1,1:2); hold on;
plot_fluor_idx = frame_t >= plot_t(1) & frame_t <= plot_t(2);
AP_stackplot(roi_trace(plot_rois,plot_fluor_idx)', ...
frame_t(plot_fluor_idx),fluor_spacing,[],[0,0.7,0],{wf_roi(plot_rois).area});
y_scale = 0.02;
t_scale = 2;
line([min(xlim),min(xlim) + t_scale],repmat(min(ylim),2,1),'color','k','linewidth',3);
line(repmat(min(xlim),2,1),[min(ylim),min(ylim) + y_scale],'color','k','linewidth',3);
axis off
linkaxes([wheel_axes,raster_axes,fluor_axes],'x');
% % Write legend
% [~,unique_contrasts_h] = unique(trial_contrast_idx);
% [~,unique_move_h] = unique(trial_choice_idx(trial_choice_idx > 0));
% legend([stim_lines(unique_contrasts_h),move_lines(unique_move_h), ...
% go_cue_lines(1),reward_lines(1),punish_lines(1)], ...
% [cellfun(@(x) ['Stim ' num2str(x)],num2cell(unique(contrasts'.*sides)),'uni',false); ...
% {'Move L';'Move R';'Go cue';'Reward';'Punish'}]);
% Plot ROIs
figure; hold on
set(gca,'YDir','reverse');
AP_reference_outline('ccf_aligned','k');
for curr_roi = plot_rois
curr_roi_boundary = cell2mat(bwboundaries(wf_roi(curr_roi).mask()));
patch(curr_roi_boundary(:,2),curr_roi_boundary(:,1),[0,0.8,0]);
text(nanmean(curr_roi_boundary(:,2)),nanmean(curr_roi_boundary(:,1)), ...
wf_roi(curr_roi).area,'FontSize',12,'HorizontalAlignment','center')
end
axis image off;
%% ** Fig 1e: Average cortical fluorescence during trial
% Get average stim-aligned fluorescence
plot_trials = move_t < 0.5 & trial_stim_allcat > 0 & trial_choice_allcat == -1;
plot_trials_exp = mat2cell(plot_trials,use_split,1);
fluor_allcat_deconv_exp = mat2cell(fluor_allcat_deconv,use_split,length(t),n_vs);
% Set alignment shifts
t_leeway = -t(1);
leeway_samples = round(t_leeway*(sample_rate));
stim_align = zeros(size(trial_stim_allcat));
move_align = -move_idx + leeway_samples;
outcome_align = -outcome_idx + leeway_samples;
% Set windows to average activity
use_align_labels = {'Stim','Move onset','Outcome'};
use_align = {stim_align,move_align,outcome_align};
plot_t = {[0,0.1],[0,0.1],[0,0.1]};
figure;
p = tight_subplot(1,length(cell2mat(plot_t)));
curr_plot_idx = 0;
for curr_align = 1:length(use_align)
% (re-align activity)
curr_ctx_act = cellfun(@(act,trials,shift) cell2mat(arrayfun(@(trial) ...
circshift(act(trial,:,:),shift(trial),2), ...
find(trials),'uni',false)), ...
fluor_allcat_deconv_exp,plot_trials_exp, ...
mat2cell(use_align{curr_align},use_split,1),'uni',false);
curr_ctx_act_mean = ...
permute(nanmean(cell2mat(cellfun(@(x) nanmean(x,1), ...
curr_ctx_act,'uni',false)),1),[3,2,1]);
curr_ctx_act_mean_t = interp1(t,curr_ctx_act_mean',plot_t{curr_align})';
curr_ctx_act_mean_t_px = svdFrameReconstruct(U_master(:,:,1:n_vs), ...
curr_ctx_act_mean_t);
for curr_plot_t = 1:length(plot_t{curr_align})
curr_plot_idx = curr_plot_idx+1;
axes(p(curr_plot_idx));
imagesc(curr_ctx_act_mean_t_px(:,:,curr_plot_t));
AP_reference_outline('ccf_aligned',[0.5,0.5,0.5]);
axis image off;
colormap(brewermap([],'Greens'));
caxis([0,0.01]);
title([use_align_labels{curr_align} ': ' num2str(plot_t{curr_align}(curr_plot_t)) ' sec']);
colorbar
end
end
% Matteo-requested: darken colormap to see visual activity better
brighten(-0.75);
%% ++ Fig 1f: Striatum multiunit by depth
% Plot depths present in > 50% of recordings
frac_depths = nanmean(cell2mat(cellfun(@(x) ...
nanmean(~squeeze(all(all(isnan(x),1),2)),2), ...
vertcat(mua_all{:})','uni',false)),2);
use_depths = frac_depths > 0.5;
% Plot average stimulus-aligned activity in striatum
plot_trials = move_t < 0.5 & trial_stim_allcat > 0 & trial_choice_allcat == -1;
plot_trials_exp = mat2cell(plot_trials,use_split,1);
% Set alignment shifts
t_leeway = -t(1);
leeway_samples = round(t_leeway*(sample_rate));
stim_align = zeros(size(trial_stim_allcat));
move_align = -move_idx + leeway_samples;
outcome_align = -outcome_idx + leeway_samples;
% Get average activity across alignments
use_align_labels = {'Stim','Move onset','Outcome'};
use_align = {stim_align,move_align,outcome_align};
act_align_avg = nan(n_depths,length(t),length(use_align));
for curr_align = 1:length(use_align)
curr_act_align = cell2mat(arrayfun(@(trial) circshift(mua_allcat(trial,:,:), ...
use_align{curr_align}(trial),2),transpose(1:size(mua_allcat,1)),'uni',false));
act_align_avg(:,:,curr_align) = ....
permute(nanmean(cell2mat(cellfun(@(act,trials) ...
nanmean(act(trials,:,:),1), ...
mat2cell(curr_act_align,use_split,length(t),n_depths), ...
plot_trials_exp,'uni',false)),1),[3,2,1]);
end
% Plot aligned_activity
align_col = [1,0,0;0.8,0,0.8;0,0,0.8];
% (split the alignment halfway between median alignment points)
align_median = cellfun(@(x) -nanmedian(x(plot_trials))/sample_rate,use_align);
align_break = align_median(1:end-1) + diff(align_median*0.8);
align_t = {[-0.05,align_break(1)],[align_break(1:2)],[align_break(2),1]};
figure; hold on; set(gca,'YDir','reverse');
for curr_align = 1:length(use_align)
curr_t_offset = -nanmedian(use_align{curr_align}(plot_trials))/sample_rate;
curr_t = t + curr_t_offset;
curr_t_plot = curr_t >= align_t{curr_align}(1) & ...
curr_t <= align_t{curr_align}(2);
curr_act_norm = act_align_avg(:,:,curr_align)./ ...
max(max(act_align_avg,[],2),[],3);
plot_t = curr_t > align_t{curr_align}(1) & curr_t <= align_t{curr_align}(2);
imagesc(curr_t(plot_t),[],curr_act_norm(use_depths,plot_t));
line(repmat(curr_t_offset,2,1),[0.5,sum(use_depths)+0.5],'color',align_col(curr_align,:));
colormap(gca,brewermap([],'Greys'));
end
xlabel('~Time from stim');
ylabel('Striatum depth');
axis tight;
%% Fig 2a,b,c: Cortex > striatum kernels by depth
% Load kernels by depths
kernel_path = 'C:\Users\Andrew\OneDrive for Business\Documents\CarandiniHarrisLab\analysis\wf_ephys_choiceworld\ephys_processing';
kernel_fn = ['ephys_kernel_depth'];
load([kernel_path filesep kernel_fn])
% (use only trained animals)
naive_animals = {'AP032','AP033','AP034','AP035','AP036'};
use_animals = ~ismember({ephys_kernel_depth.animal},naive_animals);
k_px_cat = horzcat(ephys_kernel_depth(use_animals).k_px)';
% Load, concatenate, mean STA
data_path = 'C:\Users\Andrew\OneDrive for Business\Documents\CarandiniHarrisLab\analysis\wf_ephys_choiceworld\paper\data';
k_fn = [data_path filesep 'ctx_str_kernels_vanillaChoiceworld_16strdepths'];
load(k_fn);
ctx_str_sta_mean = nanmean(cell2mat(permute(horzcat(ctx_str_sta{:}),[1,3,4,2])),4);
ctx_str_sta_mean_norm = ctx_str_sta_mean./max(max(ctx_str_sta_mean,[],1),[],2);
% Pad and concatenate kernels
max_depths = max(cellfun(@(x) size(x,3),k_px_cat));
k_px_cat_pad = cell2mat(permute(cellfun(@(x) padarray(x, ...
[0,0,max_depths-size(x,3)],NaN,'pre'),k_px_cat,'uni',false),[2,3,4,1]));
k_px_cat_pad_mean = nanmean(k_px_cat_pad,4);
k_px_cat_pad_mean_norm = k_px_cat_pad_mean./max(max(k_px_cat_pad_mean,[],1),[],2);
frac_depths = squeeze(nanmean(all(all(~isnan(k_px_cat_pad),1),2),4));
use_depths = frac_depths > 0.5;
% Plot STA and kernels
if size(k_px_cat_pad_mean_norm,3) ~= size(ctx_str_sta_mean,3)
error('Different n depths');
end
figure;
subplot(2,1,1);
imagesc(reshape(ctx_str_sta_mean_norm(:,:,use_depths),size(ctx_str_sta_mean_norm,1),[]));
caxis([-1,1]);
colormap(brewermap([],'PRGn'));
axis image off;
subplot(2,1,2);
imagesc(reshape(k_px_cat_pad_mean_norm(:,:,use_depths),size(k_px_cat_pad,1),[]));
caxis([-1,1]);
colormap(brewermap([],'PRGn'));
axis image off;
% Plot STA and kernels (rainbow colormap)
if size(k_px_cat_pad_mean_norm,3) ~= size(ctx_str_sta_mean,3)
error('Different n depths');
end
use_colormap = flipud(min(jet(sum(use_depths))-0.2,1));
sta_colored = 1-reshape(repmat(ctx_str_sta_mean_norm(:,:,use_depths),1,1,1,3).* ...
(1-permute(use_colormap,[3,4,1,2])),size(ctx_str_sta_mean_norm,1),[],3);
k_px_colored = 1-reshape(repmat(k_px_cat_pad_mean_norm(:,:,use_depths),1,1,1,3).* ...
(1-permute(use_colormap,[3,4,1,2])),size(k_px_cat_pad_mean_norm,1),[],3);
figure;
subplot(2,1,1);
image(sta_colored);
caxis([-1,1]);
colormap(brewermap([],'PRGn'));
axis image off;
subplot(2,1,2);
imagesc(k_px_colored);
caxis([-1,1]);
colormap(brewermap([],'PRGn'));
axis image off;
% Plot center-of-mass color
n_aligned_depths = sum(use_depths);
k_px_norm = k_px_cat_pad_mean_norm(:,:,use_depths);
k_px_com = sum(k_px_norm.*permute(1:n_aligned_depths,[1,3,2]),3)./sum(k_px_norm,3);
use_colormap = flipud(min(jet(255)-0.2,1));
k_px_com_colored = ...
ind2rgb(round(mat2gray(k_px_com,...
[1,n_aligned_depths])*size(use_colormap,1)),use_colormap);
figure;
p = image(k_px_com_colored);
set(p,'AlphaData',mat2gray(max(k_px_norm,[],3),[0,1]));
axis image off;
AP_reference_outline('ccf_aligned',[0.5,0.5,0.5]);
%% Fig 2d: Ternary plot for map-template correlations
% Load kernel templates for overlay
n_aligned_depths = 3;
kernel_template_fn = ['C:\Users\Andrew\OneDrive for Business\Documents\CarandiniHarrisLab\analysis\wf_ephys_choiceworld\ephys_processing\kernel_template_' num2str(n_aligned_depths) '_depths.mat'];
load(kernel_template_fn);
% Load the kernel template matches
n_aligned_depths = 3;
kernel_match_path = 'C:\Users\Andrew\OneDrive for Business\Documents\CarandiniHarrisLab\analysis\wf_ephys_choiceworld\ephys_processing';
kernel_match_fn = ['ephys_kernel_align_' num2str(n_aligned_depths) '_depths.mat'];
load([kernel_match_path filesep kernel_match_fn]);
% (naive animals not included in this plot)
naive_animals = {'AP032','AP033','AP034','AP035','AP036'};
use_animals = ~ismember({ephys_kernel_align.animal},naive_animals);
kernel_corr_cat = cell2mat([ephys_kernel_align(use_animals).kernel_corr]');
kernel_match_cat = cell2mat(horzcat(ephys_kernel_align(use_animals).kernel_match)');
% Get ternary coordinates of map correlations
kernel_corr_cat_offset = kernel_corr_cat+1;
kernel_corr_cat_norm = kernel_corr_cat_offset./sum(kernel_corr_cat_offset,2) - ...
(kernel_corr_cat_offset./sum(kernel_corr_cat_offset,2))./3;
ternary_tform = [0,1;sqrt(3/4),-0.5;-sqrt(3/4),-0.5];
ternary_limits = (ternary_tform\(eye(3)*max(max(kernel_corr_cat_norm,[],1))))';
kernel_corr_ternary = (ternary_tform\kernel_corr_cat_norm')';
% Plot ternary correlation coorinates and templates
figure;
subplot(n_aligned_depths+1,1,1); hold on;
use_depths = ~isnan(kernel_match_cat);
str_col = max(hsv(n_aligned_depths)-0.2,0);
patch(ternary_limits(:,1),ternary_limits(:,2),'w','linewidth',1);
scatter(kernel_corr_ternary(use_depths,1), ...
kernel_corr_ternary(use_depths,2), ...
5,str_col(kernel_match_cat(use_depths),:),'filled');
axis image off;
for curr_template = 1:n_aligned_depths
subplot(n_aligned_depths+1,1,curr_template+1);
imagesc(kernel_template(:,:,curr_template));
AP_reference_outline('ccf_aligned',[0.5,0.5,0.5]);
axis image off;
colormap(brewermap([],'PRGn'));
caxis([-max(abs(caxis)),max(abs(caxis))]);
end
%% Fig 2e,h: Striatum domain locations and corticostriatal projections
% Set striatum domain colors
str_col = max(hsv(n_aligned_depths)-0.2,0);
% Load the kernel template matches
n_aligned_depths = 3;
kernel_match_path = 'C:\Users\Andrew\OneDrive for Business\Documents\CarandiniHarrisLab\analysis\wf_ephys_choiceworld\ephys_processing';
kernel_match_fn = ['ephys_kernel_align_' num2str(n_aligned_depths) '_depths.mat'];
load([kernel_match_path filesep kernel_match_fn]);
% Pad and concatenate kernel matches
max_n_kernel_match = max(cell2mat(cellfun(@(x) ...
cellfun(@length,x),{ephys_kernel_align.kernel_match},'uni',false)));
kernel_match_all = cellfun(@(x) cell2mat(cellfun(@(x) ...
padarray(x,max_n_kernel_match-length(x),NaN,'pre'),x,'uni',false)), ...
{ephys_kernel_align.kernel_match},'uni',false);
kernel_match_cat = cell2mat(kernel_match_all);
% (use only depths in at least x% of recordings)
frac_depths = nanmean(~isnan(kernel_match_cat),2);
use_depths = frac_depths > 0.5;
kernel_match_cat_use = kernel_match_cat(use_depths,:);
% Get fraction of each domain for each depth
kernel_match_frac = nan(sum(use_depths),n_aligned_depths);
for curr_depth = 1:n_aligned_depths
curr_kernel_match = +(kernel_match_cat_use == curr_depth);
curr_kernel_match(isnan(kernel_match_cat_use)) = NaN;
kernel_match_frac(:,curr_depth) = nanmean(curr_kernel_match,2);
end
% Get center-of-mass for each domain
kernel_match_com = nan(n_aligned_depths,1);
for curr_depth = 1:n_aligned_depths
curr_kernel_match = +(kernel_match_cat_use == curr_depth);
curr_kernel_match(isnan(kernel_match_cat_use)) = NaN;
kernel_match_com(curr_depth) = ...
nansum(nanmean(curr_kernel_match,2).*(1:sum(use_depths))') ...
./nansum(nanmean(curr_kernel_match,2));
end
% Get relative domain COM along trajectory and plot in CCF
kernel_match_com_relative = kernel_match_com./sum(use_depths);
% Define the probe vector manually according to the targeted trajectory
probe_vector_ccf = [520,240,510;520,511,239];
% Load in the annotated Allen volume and names
allen_path = 'C:\Users\Andrew\OneDrive for Business\Documents\Atlases\AllenCCF';
av = readNPY([allen_path filesep 'annotation_volume_10um_by_index.npy']);
st = loadStructureTree([allen_path filesep 'structure_tree_safe_2017.csv']); % a table of what all the labels mean
% Get probe location per micron
probe_size = pdist2(probe_vector_ccf(1,:),probe_vector_ccf(2,:))*10;
probe_depths = ...
round([linspace(probe_vector_ccf(1,1)',probe_vector_ccf(2,1)',probe_size); ...
linspace(probe_vector_ccf(1,2)',probe_vector_ccf(2,2)',probe_size); ...
linspace(probe_vector_ccf(1,3)',probe_vector_ccf(2,3)',probe_size)]');
% Eliminiate trajectory points that are off the atlas
eliminate_depths = ...
probe_depths(:,1) < 1 | probe_depths(:,1) > size(av,1) | ...
probe_depths(:,2) < 1 | probe_depths(:,2) > size(av,2) | ...
probe_depths(:,3) < 1 | probe_depths(:,3) > size(av,3);
probe_depths(eliminate_depths,:) = [];
% Convert probe depths subscripts to indicies
probe_depths_ind = sub2ind(size(av),probe_depths(:,1),probe_depths(:,2),probe_depths(:,3));
% Get structures that the probe is in
probe_structures = av(probe_depths_ind);
% Get target relative depths through striatum
str_id = find(strcmp(st.safe_name,'Caudoputamen'));
probe_structures_str = probe_structures == str_id;
probe_str = [probe_depths(find(probe_structures_str,1,'first'),:); ...
probe_depths(find(probe_structures_str,1,'last'),:)];
kernel_depth_ccf = interp1([0,1],probe_str,kernel_match_com_relative);
% Plot brain to overlay probes
% (note the CCF is rotated to allow for dim 1 = x)
h = figure; ccf_axes = axes; hold on
slice_spacing = 10;
target_volume = permute(av(1:slice_spacing:end,1:slice_spacing:end,1:slice_spacing:end) > 1,[2,1,3]);
structure_patch = isosurface(target_volume,0);
structure_wire = reducepatch(structure_patch.faces,structure_patch.vertices,0.01);
target_structure_color = [0.7,0.7,0.7];
brain_outline = patch('Vertices',structure_wire.vertices*slice_spacing, ...
'Faces',structure_wire.faces, ...
'FaceColor','none','EdgeColor',target_structure_color);
str_id = find(strcmp(st.safe_name,'Caudoputamen'));
target_volume = permute(av(1:slice_spacing:end,1:slice_spacing:end,1:slice_spacing:end) == str_id,[2,1,3]);
structure_patch = isosurface(target_volume,0);
structure_wire = reducepatch(structure_patch.faces,structure_patch.vertices,0.01);
target_structure_color = [0.7,0,0.7];
striatum_outline = patch('Vertices',structure_wire.vertices*slice_spacing, ...
'Faces',structure_wire.faces, ...
'FaceColor','none','EdgeColor',target_structure_color);
axis image vis3d off;
view([-30,25]);
cameratoolbar(h,'SetCoordSys','y');
cameratoolbar(h,'SetMode','orbit');
scatter3(kernel_depth_ccf(:,1),kernel_depth_ccf(:,2),kernel_depth_ccf(:,3), ...
100,str_col,'filled');
% Plot brain area outlines at slice
callosum_id = find(strcmp(st.safe_name,'corpus callosum body'));
ventricle_id = find(strcmp(st.safe_name,'lateral ventricle'));
av_slice = permute(av(probe_vector_ccf(1),:,:),[2,3,1]);
slice_brain_outline = bwboundaries(av_slice > 1,'noholes');
slice_str_outline = bwboundaries(av_slice == str_id,'noholes');
slice_callosum_outline = bwboundaries(av_slice == callosum_id,'noholes');
slice_ventricle_outline = bwboundaries(av_slice == ventricle_id,'noholes');
% Plot mean domain CCF locations
figure;
subplot(1,2,1);
hold on; axis image on; box on; grid on; set(gca,'YDir','reverse');
plot(slice_brain_outline{1}(:,2),slice_brain_outline{1}(:,1),'k','linewidth',2);
cellfun(@(x) plot(x(:,2),x(:,1),'b','linewidth',2),slice_str_outline);
cellfun(@(x) fill(x(:,2),x(:,1),'k','linewidth',2),slice_callosum_outline);
cellfun(@(x) fill(x(:,2),x(:,1),'k','linewidth',2),slice_ventricle_outline);
line(probe_vector_ccf(:,3),probe_vector_ccf(:,2),'linewidth',2,'color','r');
scatter(kernel_depth_ccf(:,3),kernel_depth_ccf(:,2), ...
100,str_col,'filled');
% Plot fraction domains by depth
subplot(1,2,2); hold on;
colormap(str_col);
area(kernel_match_frac,'FaceColor','flat');
for curr_depth = 1:n_aligned_depths
line(repmat(kernel_match_com(curr_depth),2,1),ylim, ...
'color',min(str_col(curr_depth,:)+0.2,1),'linewidth',3);
end
axis tight;
xlabel('Estimated depth');
ylabel('Fraction domain match');
% Mirror all of the locations across the midline and get projections from
% both (because the cortical injections in the database aren't evenly
% distributed, so this is more comprehensive)
kernel_depth_um = round(kernel_depth_ccf*10);
bregma_um = allenCCFbregma*10;
ccf_midline = bregma_um(3);
hemisphere = sign(kernel_depth_um(1,3) - ccf_midline);
str_depths_mirror = [kernel_depth_um(:,1:2),ccf_midline - hemisphere*abs(kernel_depth_um(:,3)-ccf_midline)];
str_depths_query = [kernel_depth_um;str_depths_mirror];
injection_parameters = get_allen_projection(str_depths_query);
injection_coordinates = {injection_parameters.coordinates};
% Standardize injection coordinates by hemisphere (left = contra, right =
% ipsi)
injection_coordinates_standardized = injection_coordinates;
for curr_coord = 1:length(injection_coordinates)
target_hemisphere = sign(ccf_midline - str_depths_query(curr_coord,3));
injection_coords_ml_offset = abs(injection_coordinates{curr_coord}(:,3) - ccf_midline);
injection_coordinates_hemisphere = sign(injection_coordinates{curr_coord}(:,3) - ccf_midline);
injection_coords_ipsi = injection_coordinates_hemisphere == target_hemisphere;
injection_coords_contra = injection_coordinates_hemisphere == -target_hemisphere;
injection_coordinates_standardized{curr_coord}(injection_coords_ipsi,3) = ...