-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.m
1404 lines (1207 loc) · 46.5 KB
/
main.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
%% Quadratic-regularized least-squares on real data
tic % starts timer
%% Initialize
clear all
close all
if ~ismac
fprintf('\n')
fprintf('Setting MaxNumCompThreads to 5')
fprintf('\n')
maxNumCompThreads(4)
end
addpath redblue
addpath DrosteEffect-BrewerMap-5b84f95/
addpath bluewhitered/
set(0,'DefaultAxesColorOrder',brewermap(NaN,'Set1'))
% Make plots tabs in figure window
set(0,'DefaultFigureWindowStyle','docked')
%% User Parameters
overall_data_folder = 'data_folder';
sub_data_folder = 'raw_data';
n = 500; % length of filter for breathing
s = 4000; % length of filter for stimulus
trial_select = '3CHO'; % scalar or vector of trial(s); or, odorant name
% Trials just below are the full set of odorant/stimulus trials
%trial_select = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,40,41,42,43,44,45];
%trial_select = [3];
lambda_breathing = [1 (10.^(1:6))]; % lambda for breathing in optimization
lambda_stimulus = [(1e-10) (10.^(1:6))]; % lambda for stimulus in optimization
dff_flag = 1; % Flag to indicate whether to do deltaF/F
roi_glo_filtering_flag = 1; % this will be calibrated for n/s longer, both for stim & non-stim
roi_glo_zscore_flag = 1;
filter_stimulus_flag = 0; % 0-no filter, 1-gaussian, 2-triangular
num_ROIs_to_use = 20;
stim_extend_flag = 3; % 1-extend by 2sec, 2-shorten to just one sample (2ms),
% 3-same as 2, but moved to peak of breath
% after onset of stim
trial_blacklist = [1 5 9 10 15 20 40 41 42 43 44 45]; % Blacklist of trials to exclude if odorant
% name is used for
if dff_flag==0
fprintf('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
fprintf('\n')
fprintf('Not performing deltaF/F0 processing')
fprintf('\n')
fprintf('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
fprintf('\n')
end
if roi_glo_filtering_flag==0
fprintf('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
fprintf('\n')
fprintf('Not performing FILTERING ON ROI/GLO')
fprintf('\n')
fprintf('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
fprintf('\n')
end
if roi_glo_zscore_flag==0
fprintf('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
fprintf('\n')
fprintf('Not performing ZSCORE ON ROI/GLO')
fprintf('\n')
fprintf('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
fprintf('\n')
end
if filter_stimulus_flag~=0
fprintf('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
fprintf('\n')
fprintf('Stimulus is being filtered')
fprintf('\n')
fprintf('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
fprintf('\n')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%
% Parameters for filtering
%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Breathing
fc = 10; %Hz
fs = 500; %Hz
%%%% ROIs/Glomeruli
filter_select = 'Lowpass'; % 'Lowpass' or 'Bandpass', filtering for data (not breathing)
fl = 1.5;
fh = 70; % will act as cutoff frequency if 'Lowpass' selected
% fl = 0.5; % Usual settings
% fh = 20;
dff_stim_mean_start_t = 1500; % 3sec -> this will be calibrated for n/s longer
dff_stim_mean_end_t = 2000; % 4sec
%%%% Stimulus
gausswin_alpha_stim = 5;
gausswin_N_stim = 4000;
% Plotting parameters
time_range_to_plot = [40 43]; % in seconds
colorbar_m = [];
%c_axis = [-1 1];
c_axis = []; % If c_axis unspecified/empty, normalize c_axis for trial
plot_glo_flag = 0; % Plot glo traces
ignore_raw_for_c_normalization = 1; % Set to 1 if not including raw in normalization of corr
% For graphs with nodes/edges
weight_threshold = 0.04; % Determines which weights to care about
%weight_threshold = 0;
%% Load Data
% Load trial stimulus information
data_excel_doc = readtable('2017-10-27_GAD2-cre-tdTomato+AAV1.Syn.GCaMP6f.xlsx','Format','auto', 'ReadVariableNames',false);
data_excel_doc(:,[1 3:6 8:10]) = [];
trial_stim_label = data_excel_doc(contains(data_excel_doc.Var2,'roi_1027_0'),:);
[stim_label,~,stim_index] = unique(trial_stim_label.Var7);
% Check that user has defined trial_select - if not, ask user for trial_select
if ~exist('trial_select','var')
trial_select = input('Please define trial_select: ','s');
end
% If trial_select is a string, then select trials that have that odorant
if isstr(trial_select)
odorant_name = trial_select;
trial_select = find(strcmp(trial_stim_label.Var7,trial_select));
for ii=1:length(trial_blacklist)
if ~isempty(find(trial_blacklist(ii)==trial_select))
fprintf('Removing trial %i\n', trial_blacklist(ii))
trial_select(find(trial_blacklist(ii)==trial_select))=[];
end
end
else
odorant_name = num2str(trial_select);
end
% Plot stimulus information
figure('NumberTitle', 'off', 'Name','Stim Dist')
h_hist = histogram(stim_index);
xticks(1:max(stim_index))
xticklabels(stim_label)
set(gca,'FontSize',16)
xlabel('Stimulus','FontWeight','bold')
ylabel('# Trials','FontWeight','bold')
title('Distribution of Stimuli Among Trials','FontWeight','bold','FontSize', 20)
box off
h_hist.FaceAlpha = 1;
% Trial-specific data
% Initialize cells so shape is specified
num_trials = length(trial_select);
trial_str = cell(num_trials,1);
T = cell(num_trials,1);
% Determine starting index for regression (i.e. when observations start,
% y_i)
b_starting_index = max([n,s])+1;
% Loop through trials
for ii=1:num_trials
trial_str{ii} = strcat(overall_data_folder,'/',...
sub_data_folder,'/roi_1027_', ...
num2str(trial_select(ii), '%03.f'), '.csv');
T{ii} = readtable(trial_str{ii});
if (b_starting_index>2000) % If b_starting>4sec
num_timepoints_to_pad = b_starting_index-2000; % How many zeros to add
T{ii}((num_timepoints_to_pad+1):(end+num_timepoints_to_pad),:) = ...
T{ii}; % Shift real values
T{ii}{1:num_timepoints_to_pad,:} = 0; % Preprend zeros
else
num_timepoints_to_pad = 0;
end
original_number_of_ROIs = length(find(cellfun(@(x) ...
contains(x,'roi'),T{ii}.Properties.VariableNames))')
T{ii}(:,1+((1+num_ROIs_to_use):original_number_of_ROIs)) = [];
end
%% Show Stimuli for Selected Trials
figure('NumberTitle', 'off', 'Name','Stim for Trials')
%ylim([min(trial_select)-0.5 max(trial_select)+0.5])
for tt=1:num_trials
text(0.03,trial_select(tt),trial_stim_label.Var7{trial_select(tt)},...
'FontSize',20)
end
set(gca,'FontSize',20)
xticks([])
save_yticks = yticks;
yticks(min(trial_select):max(trial_select))
set(gca,'YDir','reverse')
%% Extract Waveforms
% Initialize cells so shape is specified
breathing = cell(num_trials,1);
stimulus = cell(num_trials,1);
T_roi_indices = cell(num_trials,1);
roi_names = cell(num_trials,1);
raw_roi_data = cell(num_trials,1);
raw_glo_data = cell(num_trials,1);
% Loop through trials
for ii=1:num_trials
% Breathing/stim
breathing{ii} = T{ii}.breath;
stimulus{ii} = double(T{ii}.stim>0.2);
% ROIs
T_roi_indices{ii} = find(cellfun(@(x) contains(x,'roi'),T{ii}.Properties.VariableNames))';
roi_names{ii} = T{ii}.Properties.VariableNames(T_roi_indices{ii})';
raw_roi_data{ii} = nan(length(roi_names{ii}),length(breathing{ii}));
for jj = 1:length(roi_names{ii}) % ROIs
current_roi = str2double(roi_names{ii}{jj}(4:5));
raw_roi_data{ii}(current_roi,:) = T{ii}.(roi_names{ii}{jj});
end
% Glomeruli
raw_glo_data{ii} = nan(length(roi_names{ii})/2,length(breathing{ii}));
for jj = 1:2:length(roi_names{ii}) % Glomeruli
raw_glo_data{ii}(round(jj/2),:) = mean(raw_roi_data{ii}(jj:(jj+1),:),1);
end
% 1: Extend stim length
if stim_extend_flag==1
stim_nonzero_indices = find(stimulus{ii}>0);
final_stim_nonzero_index = max(stim_nonzero_indices);
stimulus{ii}(final_stim_nonzero_index:(final_stim_nonzero_index+1000)) = 1;
% 2: Set it so stim only has 1 point
elseif stim_extend_flag==2
stim_nonzero_indices = find(stimulus{ii}>0);
stimulus{ii}(stim_nonzero_indices(2:end))=0;
% 3: Set it so stim only has 1 point at peak of breathing waveform
elseif stim_extend_flag==3
stim_nonzero_indices = find(stimulus{ii}>0);
stimulus{ii}(stim_nonzero_indices(2:end))=0;
[PKS,LOCS] = findpeaks(...
breathing{ii}(stim_nonzero_indices(1):(stim_nonzero_indices+500)),...
'MinPeakDistance',125,'MinPeakHeight',0.005);
LOCS(LOCS<50) = [];
if trial_select(ii)==13 % Trial 13: Have to choose next peak
br_pk_LOC = LOCS(2)-1+stim_nonzero_indices(1);
elseif trial_select(ii)==14 % Trial 14: Have to choose next peak
br_pk_LOC = LOCS(2)-1+stim_nonzero_indices(1);
else
br_pk_LOC = LOCS(1)-1+stim_nonzero_indices(1);
end
figure('NumberTitle', 'off', 'Name',sprintf('Trial %i', ii))
plot(raw_glo_data{ii}')
hold on
plot(stimulus{ii},'LineWidth',3)
plot(0.22*zscore(breathing{ii})-0.8,'LineWidth',3)
line([br_pk_LOC br_pk_LOC],[-1.5 1.5],...
'LineWidth',3)
hold off
title(sprintf('Trial %i', ii))
set(gca,'FontSize',16)
xlim([8000 10000])
% Set stimulus location to peak breathing
stimulus{ii}(stim_nonzero_indices(1))=0; % remove old marker
stimulus{ii}(br_pk_LOC)=1; % set new marker to pk
% Add to plot
hold on
plot(stimulus{ii}-1.1,'LineWidth',3)
hold off
end
end
%% Time
time_generic = 0.002:0.002:10000;
% Initialize cells so shape is specified
time = cell(num_trials,1);
breathing_filter_time = cell(num_trials,1);
stimulus_filter_time = cell(num_trials,1);
later_time = cell(num_trials,1);
% Loop through trials
for ii=1:num_trials
time{ii} = time_generic(1:length(breathing{ii}));
breathing_filter_time{ii} = time{ii}(1:n);
stimulus_filter_time{ii} = time{ii}(1:s);
% later_time - corresponds to b, A*beta, & S*alpha
later_time{ii} = time{ii}(max([n,s])+1:end);
end
%% DeltaF/F0
% Initialize cells so shape is specified
dff_glo_data = cell(num_trials,1);
% Loop through trials
for tt=1:num_trials
% Glomeruli
dff_glo_data{tt} = nan(size(raw_glo_data{tt}));
for ii=1:size(raw_glo_data{tt},1)
if dff_flag==1
if isempty(find(stimulus{tt}>0)) % No stimulus
fprintf('Trial %i: No Stimulus\n',trial_select(tt))
dff_glo_data{tt}(ii,:) = (raw_glo_data{tt}(ii,:)/...
mean(raw_glo_data{tt}(ii,(num_timepoints_to_pad+1):end)))-1;
else % Stimulus
fprintf('Trial %i: Stimulus\n',trial_select(tt))
dff_glo_data{tt}(ii,:) = (raw_glo_data{tt}(ii,:)/...
mean(raw_glo_data{tt}(ii,num_timepoints_to_pad+...
(dff_stim_mean_start_t:dff_stim_mean_end_t))))-1;
end
else
dff_glo_data{tt}(ii,:) = raw_glo_data{tt}(ii,:);
end
end
end
%% Low Pass Filter Breathing + Z-score
[b_filt,a_filt] = butter(4,fc/(fs/2));
for tt=1:num_trials
breathing{tt} = filtfilt(b_filt, a_filt, breathing{tt});
breathing{tt} = zscore(breathing{tt}); % zscore
end
% Plot filter
% Uncomment below to plot breathing filter
% lpf_fv = fvtool(b_filt, a_filt);
% set(lpf_fv, 'MagnitudeDisplay', 'Magnitude squared')
% lpf_fv.Fs = fs;
% set(gca,'FontSize',16)
% xlim([0 50])
% objects = findall(gca);
% objects(2).LineWidth = 3;
%% Low Pass Filter Stimulus
% First plot stimulus
h_stimulus = figure('NumberTitle', 'off', 'Name','Stimulus');
for tt=1:num_trials
plot(time{tt},stimulus{tt},'LineWidth',3)
hold on
end
hold off
xlabel('Time (s)')
ylabel('Stimulus State')
set(gca, 'FontSize', 16)
% Filter
if (filter_stimulus_flag~=0)
if filter_stimulus_flag==1
% Apply gaussian window to stimulus
stim_gausswin = gausswin(gausswin_N_stim,gausswin_alpha_stim);
for tt=1:num_trials
stimulus{tt} = conv(stimulus{tt}, stim_gausswin, 'same');
if ~isempty(find(stimulus{tt}>0)) % If stimulus
stimulus{tt} = stimulus{tt}/max(stimulus{tt});
end
end
elseif filter_stimulus_flag==2
% Apply triangular window to stimulus
for tt=1:num_trials
if ~isempty(find(stimulus{tt}>0)) % If stimulus
stimulus{tt}(find(stimulus{tt}>0)) = triang(length(find(stimulus{tt}>0)));
end
end
end
% Plot smoothed stimulus over raw stimulus
figure(h_stimulus)
hold on
set(gca,'ColorOrderIndex',1)
for tt=1:num_trials
plot(time{tt},stimulus{tt},'LineWidth',3)
end
hold off
end
%% Band Pass Filter Glomeruli + Z-score
if strcmp(filter_select,'Bandpass')
[b_bp, a_bp] = butter(4,[fl fh]/(fs/2));
elseif strcmp(filter_select,'Lowpass')
[b_bp, a_bp] = butter(4,fh/(fs/2));
end
% Initialize variables
fil_glo_data = cell(num_trials,1);
% Loop through trials
for tt=1:num_trials
% GLOMERULI
fil_glo_data{tt} = nan(size(raw_glo_data{tt}));
for ii=1:size(raw_glo_data{tt},1)
if roi_glo_filtering_flag
fil_glo_data{tt}(ii,:) = ...
filtfilt(b_bp, a_bp, dff_glo_data{tt}(ii,:));
else
fil_glo_data{tt}(ii,:) = dff_glo_data{tt}(ii,:);
end
end
if roi_glo_zscore_flag
fil_glo_data{tt} = zscore(fil_glo_data{tt}')'; % zscore
end
end
%% Check out correlations between Glomeruli
%% ALL TRIALS TOGETHER: Plot correlations between Glomeruli across trials
% Compute correlations
RHO_all_raw_glo_data = corr(cell2mat(raw_glo_data')');
RHO_all_fil_glo_data = corr(cell2mat(fil_glo_data')');
% RAW GLOMERULI:
subplot(3,2,2)
imagesc(RHO_all_raw_glo_data)
title('RHO for all raw glo data')
h_bar = colorbar;
ylabel(h_bar,'RHO')
set(gca, 'FontSize', 24)
xlabel('glomerulus')
ylabel('glomerulus')
if isempty(c_axis) % If c_axis unspecified/empty, normalize c_axis for trial
c_limits_glo_all_trial(1,:) = caxis;
c_max = max(max(RHO_all_raw_glo_data-diag(diag(RHO_all_raw_glo_data))));
c_limits_glo_all_trial(1,2) = c_max;
else % Use c_axis if given, e.g. c_axis = [-1 1]
caxis(c_axis)
end
if isempty(colorbar_m)
colormap(redblue())
else
colormap(redblue(colorbar_m))
end
axis image
% FIL GLOMERULI:
subplot(3,2,4)
imagesc(RHO_all_fil_glo_data)
title('RHO for all fil glo data')
h_bar = colorbar;
ylabel(h_bar,'RHO')
set(gca, 'FontSize', 24)
xlabel('glomerulus')
ylabel('glomerulus')
if isempty(c_axis) % If c_axis unspecified/empty, normalize c_axis for trial
c_limits_glo_all_trial(2,:) = caxis;
c_max = max(max(RHO_all_fil_glo_data-diag(diag(RHO_all_fil_glo_data))));
c_limits_glo_all_trial(2,2) = c_max;
else % Use c_axis if given, e.g. c_axis = [-1 1]
caxis(c_axis)
end
if isempty(colorbar_m)
colormap(redblue())
else
colormap(redblue(colorbar_m))
end
axis image
%% Data Parameters & Selection
% Loop through trials
for tt=1:num_trials
m(tt) = min([length(breathing{tt})-n, ...
length(breathing{tt})-s]); % m - number of examples
% Initialize for loop
A{tt} = nan(m(tt),n); % Breathing
S{tt} = nan(m(tt),s); % Stimulus
window_end_index = b_starting_index-1; % End of window preceding b start
% Loop through windows
for ii = 1:m(tt)
A{tt}(ii,:) = breathing{tt}((window_end_index-(n-1)):...
window_end_index); % Breathing signal - m x n
S{tt}(ii,:) = stimulus{tt}((window_end_index-(s-1)):...
window_end_index); % Stimulus signal - m x s
window_end_index = window_end_index+1; % Increment window_end_index
end
end
%% Get delta matrix for smoothness
% quad-smoothness
omega_breathing = sparse(toeplitz([2, -1, zeros(1, n-2)]));
omega_breathing_square = omega_breathing*omega_breathing;
omega_stimulus = sparse(toeplitz([2, -1, zeros(1, s-2)]));
omega_stimulus_square = omega_stimulus*omega_stimulus;
% create matrix for smoothness penalty & lambda learning
if (length(lambda_breathing)>1) || (length(lambda_stimulus)>1)
delta = nan(n+s,n+s,length(lambda_breathing),length(lambda_stimulus));
for ii=1:length(lambda_breathing)
for jj=1:length(lambda_stimulus)
delta(:,:,ii,jj) = [(lambda_breathing(ii)*omega_breathing_square)...
zeros(n,s);...
zeros(s,n)...
(lambda_stimulus(jj)*omega_stimulus_square)];
end
end
else
delta = [(lambda_breathing*omega_breathing_square) zeros(n,s);
zeros(s,n) (lambda_stimulus*omega_stimulus_square)];
end
%% Solve problem for ALL data across selected trials
A_all = cell2mat(A');
S_all = cell2mat(S');
X = [A_all S_all];
% Glomeruli
for ii=1:size(fil_glo_data{1},1) % Glomeruli
fprintf('Glomerulus %i\n',ii)
for tt=1:num_trials
b_all_pre_cat{tt} = fil_glo_data{tt}(ii,b_starting_index:end);
end
b_all = cell2mat(b_all_pre_cat); % concatenate trials
[x_quad_all, glo_ii(ii), glo_jj(ii)] = gcv_solver( X, delta, b_all,...
lambda_breathing,...
lambda_stimulus );
%x_quad_all = X_term*(b_all');
glo_quad_beta_all(ii,:) = x_quad_all(1:n); % Breathing filter
glo_quad_alpha_all(ii,:) = x_quad_all((n+1):end); % Stimulus filter
for tt=1:num_trials
% Filter
glo_filtered_breathing_quad_all{tt}(ii,:) = A{tt}*(glo_quad_beta_all(ii,:)');
glo_filtered_stimulus_quad_all{tt}(ii,:) = S{tt}*(glo_quad_alpha_all(ii,:)');
end
end
%% SAVE INTERMEDIATE FILE
toc % prints time
save([odorant_name '_all_INTERMEDIATE.mat'])
%% ALL TRIALS: Plot filters learned across all trials
% Glomeruli
% Breathing
figure('NumberTitle', 'off', 'Name','All GLO Filters');
subplot(2,1,1)
%plot(breathing_filter_time{1}, zeros(size(breathing_filter_time{1})),'--')
% Create string for legend
% Plot synthetic filters also if simulation
leg_index = 1;
if contains(sub_data_folder, 'simulated')
load([overall_data_folder '/parameters/' sub_data_folder '.mat'])
plot(breathing_filter_time{1}, breathing_fil_weights',...
'LineWidth',3)
hold on
set(gca,'ColorOrderIndex',1)
for ii=1:size(glo_quad_beta_all,1)
glom_leg_str{ii} = sprintf('G%i True',ii);
leg_index = leg_index+1;
end
end
% Plot filters
for ii=1:size(glo_quad_beta_all,1) % Loop through glomeruli
%plot(breathing_filter_time{1},flip(glo_quad_beta_all(ii,:)),'--', ...
% 'LineWidth', 3)
if ismac
plot(breathing_filter_time{1},flip(glo_quad_beta_all(ii,:)),'--', ...
'LineWidth', 3)
else
plot(breathing_filter_time{1},flip(glo_quad_beta_all(ii,:)), ...
'LineWidth', 3)
end
hold on
glom_leg_str{leg_index} = sprintf('G%i Estimated',ii);
leg_index = leg_index+1;
end
hold off
xlim([min(breathing_filter_time{1}) max(breathing_filter_time{1})])
title('Breathing Filters for Glomeruli')
xlabel('Reverse time (sec)')
set(gca, 'FontSize', 16)
legend(glom_leg_str)
% Stimulus
subplot(2,1,2)
%plot(stimulus_filter_time{1}, zeros(size(stimulus_filter_time{1})),'--')
% Plot synthetic filters also if simulation
if contains(sub_data_folder, 'simulated')
plot(stimulus_filter_time{1}, stimulus_fil_weights',...
'LineWidth',3)
hold on
set(gca,'ColorOrderIndex',1)
end
% Plot filters
for ii=1:size(glo_quad_alpha_all,1) % Loop through glomeruli
%plot(stimulus_filter_time{1},flip(glo_quad_alpha_all(ii,:)),'--', ...
% 'LineWidth', 3)
plot(stimulus_filter_time{1},flip(glo_quad_alpha_all(ii,:)), ...
'LineWidth', 3)
hold on
end
hold off
xlim([min(stimulus_filter_time{1}) max(stimulus_filter_time{1})])
title('Stimulus Filters for Glomeruli')
xlabel('Reverse time (sec)')
set(gca, 'FontSize', 16)
legend(glom_leg_str)
%% PLOT ALL FILTERS LEARNED ACROSS ALL TRIALS AS SEPARATE LINES
figure('NumberTitle', 'off', 'Name','All GLO Filters (lines)');
for ii=1:size(glo_quad_alpha_all,1) % Loop through glomeruli
plot(stimulus_filter_time{1},(flip(glo_quad_alpha_all(ii,:))/...
max(glo_quad_alpha_all(ii,:)))+ii, ...
'LineWidth', 3)
hold on
end
hold off
% Plot settings
xlim([min(stimulus_filter_time{1}) max(stimulus_filter_time{1})])
title('Stimulus Filters for Glomeruli')
xlabel('Reverse time (sec)')
set(gca, 'FontSize', 16)
legend(glom_leg_str)
ylabel('Glomerulus')
box off
yticks(1:size(glo_quad_alpha_all,1))
%% ALL: BREATHING & STIMULUS ADJUSTED GLOMERULI
for tt=1:num_trials
% Glomeruli
for ii=1:size(fil_glo_data{tt},1) % Loop through glomeruli
glo_breathing_adjusted_all{tt}(ii,:) = fil_glo_data{tt}(ii,b_starting_index:end) ...
- glo_filtered_breathing_quad_all{tt}(ii,:);
glo_stimulus_adjusted_all{tt}(ii,:) = fil_glo_data{tt}(ii,b_starting_index:end) ...
- glo_filtered_stimulus_quad_all{tt}(ii,:);
glo_both_adjusted_all{tt}(ii,:) = fil_glo_data{tt}(ii,b_starting_index:end) ...
- glo_filtered_stimulus_quad_all{tt}(ii,:)...
- glo_filtered_breathing_quad_all{tt}(ii,:);
end
end
%% COMPUTE FVU
for tt=1:num_trials
% Glomeruli
% Total variance
var_glo_total{tt} = var(fil_glo_data{tt}(:,b_starting_index:end),[],2);
end
%% ALL: COMPUTE FVU
for tt=1:num_trials
% Glomeruli
% Variances
var_glo_breathing_adj_all{tt} = var(glo_breathing_adjusted_all{tt},[],2);
var_glo_stimulus_adj_all{tt} = var(glo_stimulus_adjusted_all{tt},[],2);
var_glo_both_adj_all{tt} = var(glo_both_adjusted_all{tt},[],2);
% FVUs
fvu_glo_breathing_adj_all{tt} = var_glo_breathing_adj_all{tt}./var_glo_total{tt};
fvu_glo_stimulus_adj_all{tt} = var_glo_stimulus_adj_all{tt}./var_glo_total{tt};
fvu_glo_both_adj_all{tt} = var_glo_both_adj_all{tt}./var_glo_total{tt};
end
% Glomeruli
% Extract relevant fil_glo_data values
for tt=1:num_trials
fil_glo_data_b_start{tt} = fil_glo_data{tt}(:,b_starting_index:end);
end
% Concatenate trials
fil_glo_data_b_start_cat = cell2mat(fil_glo_data_b_start);
glo_breathing_adjusted_all_cat = cell2mat(glo_breathing_adjusted_all);
glo_stimulus_adjusted_all_cat = cell2mat(glo_stimulus_adjusted_all);
glo_both_adjusted_all_cat = cell2mat(glo_both_adjusted_all);
% Variances
var_glo_total_all_gen = var(fil_glo_data_b_start_cat,[],2);
var_glo_breathing_adj_all_gen = var(glo_breathing_adjusted_all_cat,[],2);
var_glo_stimulus_adj_all_gen = var(glo_stimulus_adjusted_all_cat,[],2);
var_glo_both_adj_all_gen = var(glo_both_adjusted_all_cat,[],2);
% FVUs
fvu_glo_breathing_adj_all_gen = var_glo_breathing_adj_all_gen./var_glo_total_all_gen;
fvu_glo_stimulus_adj_all_gen = var_glo_stimulus_adj_all_gen./var_glo_total_all_gen;
fvu_glo_both_adj_all_gen = var_glo_both_adj_all_gen./var_glo_total_all_gen;
%% ALL: PLOT FVUs
% Colors
color_order = get(gca, 'ColorOrder');
col_to_use = color_order(1,:);
for tt=1:num_trials
% Create figure
figure('NumberTitle', 'off', 'Name', ...
sprintf('All FVU: Breathing - Trial %i',trial_select(tt)));
% Glomeruli
subplot(2,1,2)
bar(fvu_glo_breathing_adj_all{tt}, 'FaceColor', col_to_use)
title(sprintf('FVUs for Breathing-Adjusted Glomeruli - Trial %i',...
trial_select(tt)))
xlabel('Glomerulus')
ylabel('FVU')
set(gca,'FontSize', 16)
box off
xlim([0.5 size(fil_glo_data{tt},1)+0.5])
end
%% ALL ACROSS TRIALS: PLOT FVUs ACROSS TRIALS FOR BREATHING
% Colors
color_order = get(gca, 'ColorOrder');
col_to_use = color_order(1,:);
% Create figure
figure('NumberTitle', 'off', 'Name','All ACROSS FVU: Breathing');
% Glomeruli
subplot(2,1,2)
bar(fvu_glo_breathing_adj_all_gen, 'FaceColor', col_to_use)
title('FVUs for Breathing-Adjusted Glomeruli (Across All Trials)')
xlabel('Glomerulus')
ylabel('FVU')
set(gca,'FontSize', 16)
box off
xlim([0.5 size(fil_glo_data{1},1)+0.5])
%% ALL ACROSS TRIALS: PLOT FVUs ACROSS TRIALS FOR STIMULUS
% Colors
color_order = get(gca, 'ColorOrder');
col_to_use = color_order(1,:);
% Create figure
figure('NumberTitle', 'off', 'Name','All ACROSS FVU: Stimulus');
% Glomeruli
subplot(2,1,2)
bar(fvu_glo_stimulus_adj_all_gen, 'FaceColor', col_to_use)
title('FVUs for Stimulus-Adjusted Glomeruli (Across All Trials)')
xlabel('Glomerulus')
ylabel('FVU')
set(gca,'FontSize', 16)
box off
xlim([0.5 size(fil_glo_data{1},1)+0.5])
%% PLOT FIL, FIL BREATHING/STIMULUS/BOTH, & ADJUSTED
line_width = 3;
% Glomeruli
% Breathing
if plot_glo_flag==1
for tt=1:num_trials
for ii=1:size(fil_glo_data{tt},1)
figure('NumberTitle', 'off', 'Name', sprintf('Trial %i - G%i',...
trial_select(tt),ii));
if ~contains(version, '2016')
h_sup = suptitle(sprintf('Glomerulus %i',ii));
end
ax1 = subplot(3,1,1);
color_order = get(gca, 'ColorOrder');
col_to_use = color_order(9,:);
plot(time{tt}(b_starting_index:end), zeros(size(time{tt}(b_starting_index:end))),...
'--','Color',col_to_use,'LineWidth',2,'HandleVisibility','off')
hold on
set(gca,'ColorOrderIndex',1)
plot(time{tt}(b_starting_index:end), fil_glo_data{tt}(ii,b_starting_index:end),...
'DisplayName', sprintf('Filtered Glomerulus %i',ii), ...
'LineWidth', line_width)
plot(time{tt}(b_starting_index:end), glo_filtered_breathing_quad{tt}(ii,:),...
'DisplayName', 'Filtered Breathing', 'LineWidth', line_width)
hold off
legend show
xlim(time_range_to_plot)
xlabel('Time (s)')
set(gca,'FontSize', 16)
ylabel('\Delta F/F')
%grid on
text(mean(xlim),max(ylim)+(0.35*max(ylim)),...
sprintf('Glomerulus %i',ii),...
'FontSize', 30, 'FontWeight', 'bold', 'HorizontalAlignment', 'center')
ax2 = subplot(3,1,2);
color_order = get(gca, 'ColorOrder');
col_to_use = color_order(9,:);
plot(time{tt}(b_starting_index:end), zeros(size(time{tt}(b_starting_index:end))),...
'--','Color',col_to_use,'LineWidth',2,'HandleVisibility','off')
hold on
set(gca,'ColorOrderIndex',1)
plot(time{tt}(b_starting_index:end), fil_glo_data{tt}(ii,b_starting_index:end),...
'DisplayName', sprintf('Filtered Glomerulus %i',ii), ...
'LineWidth', line_width)
color_order = get(gca, 'ColorOrder');
col_to_use = color_order(3,:);
plot(time{tt}(b_starting_index:end), glo_breathing_adjusted{tt}(ii,:),...
'DisplayName', sprintf('Adjusted Glomerulus %i',ii),...
'Color', col_to_use, 'LineWidth', line_width)
hold off
xlabel('Time (s)')
set(gca,'FontSize', 16)
xlim(time_range_to_plot)
title(sprintf('FVU: %0.2f', fvu_glo_breathing_adj{tt}(ii)))
legend show
ylabel('\Delta F/F')
%grid on
ax3 = subplot(3,1,3);
color_order = get(gca, 'ColorOrder');
col_to_use = color_order(9,:);
plot(time{tt}(b_starting_index:end), zeros(size(time{tt}(b_starting_index:end))),...
'--','Color',col_to_use,'LineWidth',2)
hold on
set(gca,'ColorOrderIndex',1)
color_order = get(gca, 'ColorOrder');
col_to_use = color_order(3,:);
plot(time{tt}(b_starting_index:end), glo_breathing_adjusted{tt}(ii,:),...
'DisplayName', sprintf('Adjusted Glomerulus %i',ii),...
'Color', col_to_use, 'LineWidth', line_width)
hold off
xlabel('Time (s)')
set(gca,'FontSize', 16)
xlim(time_range_to_plot)
title(sprintf('FVU: %0.2f', fvu_glo_breathing_adj{tt}(ii)))
legend
ylabel('\Delta F/F')
%grid on
linkaxes([ax1 ax2 ax3],'xy')
end
end
end
%% ALL: Check out correlations between Glomeruli after breathing removal
all_corr_fig_hdl = figure('NumberTitle', 'off', 'Name','All Corr: Br Adj');
figure(all_corr_fig_hdl)
% FIL Glomeruli with breathing adjusted
RHO_all_glo_breathing_adjusted = corr(glo_breathing_adjusted_all_cat');
subplot(3,2,6)
imagesc(RHO_all_glo_breathing_adjusted)
title('RHO for all filtered glomeruli data with breathing adjusted')
h_bar = colorbar;
ylabel(h_bar,'RHO')
set(gca, 'FontSize', 24)
xlabel('glomerulus')
ylabel('glomerulus')
if isempty(c_axis) % If c_axis unspecified/empty, normalize c_axis for trial
c_limits_glo_all_trial(3,:) = caxis;
c_max = max(max(RHO_all_glo_breathing_adjusted-...
diag(diag(RHO_all_glo_breathing_adjusted))));
c_limits_glo_all_trial(3,2) = c_max;
else % Use c_axis if given, e.g. c_axis = [-1 1]
caxis(c_axis)
end
if isempty(colorbar_m)
colormap(redblue())
else
colormap(redblue(colorbar_m))
end
axis image
% Set caxis across all plots if caxis empty
for ii =1:6
if (ignore_raw_for_c_normalization==1)&&(ii<3)
else
subplot(3,2,ii)
if rem(ii, 2) == 0 % even->glo, might need to fix later (plotting every other)
if ignore_raw_for_c_normalization==1
c_limits_glo_all_trial(1,:) = 0;
end
lim_to_use = max([max(c_limits_glo_all_trial(:)) ...
abs(min(c_limits_glo_all_trial(:)))]);
caxis([-lim_to_use lim_to_use])
end
end
end
%% ALL: Check out correlations between Glomeruli after breathing+stim
% NEW FIG 6
% fil_glo_data_b_start
% glo_breathing_adjusted_all
% glo_stimulus_adjusted_all
% glo_both_adjusted_all
fil_glo_data_b_start_WINDOWED = cell(1, 4);
glo_breathing_adjusted_WINDOWED = cell(1, 4);
glo_stimulus_adjusted_WINDOWED = cell(1, 4);
glo_both_adjusted_WINDOWED = cell(1, 4);
for tt=1:num_trials
[br_pk_LOC, br_pk_MAX] = max(stimulus{tt});
fil_glo_data_b_start_WINDOWED{tt} = fil_glo_data_b_start{tt}(:, br_pk_LOC:br_pk_LOC+3999);
glo_breathing_adjusted_WINDOWED{tt} = glo_breathing_adjusted_all{tt}(:, br_pk_LOC:br_pk_LOC+3999);
glo_stimulus_adjusted_WINDOWED{tt} = glo_stimulus_adjusted_all{tt}(:, br_pk_LOC:br_pk_LOC+3999);
glo_both_adjusted_WINDOWED{tt} = glo_both_adjusted_all{tt}(:, br_pk_LOC:br_pk_LOC+3999);
end
% removal
all_corr_fig_br_stim_windowed = figure('NumberTitle', 'off', 'Name','CorrelationGrids');
figure(all_corr_fig_br_stim_windowed)
glo_unadjusted_truncated = cell2mat(fil_glo_data_b_start);
RHO_all_unadjusted_truncated = corr(glo_unadjusted_truncated');
% Unadjusted and windowed
subplot(2,2,1)
imagesc(RHO_all_unadjusted_truncated)
title('Before Adjustment')
h_bar = colorbar;
ylabel(h_bar,'\rho')
set(gca, 'FontSize', 24)
xlabel('Glomerulus')
ylabel('Glomerulus')
if isempty(c_axis) % If c_axis unspecified/empty, normalize c_axis for trial
c_limits_glo_all_trial_br_stim(1,:) = caxis;
c_max = max(max(RHO_all_fil_glo_data-diag(diag(RHO_all_fil_glo_data))));
c_limits_glo_all_trial_br_stim(1,2) = c_max;
else % Use c_axis if given, e.g. c_axis = [-1 1]
caxis(c_axis)
end
if isempty(colorbar_m)
colormap(redblue())
else
colormap(redblue(colorbar_m))
end
axis image
% FIL Glomeruli with breathing adjusted
glo_breathing_adjusted_truncated = cell2mat(glo_breathing_adjusted_WINDOWED);
RHO_all_glo_breathing_adjusted = corr(glo_breathing_adjusted_truncated');
subplot(2,2,2)
imagesc(RHO_all_glo_breathing_adjusted)
title('Adjusted for Breathing')
h_bar = colorbar;
ylabel(h_bar,'\rho')
set(gca, 'FontSize', 24)
xlabel('Glomerulus')
ylabel('Glomerulus')
if isempty(c_axis) % If c_axis unspecified/empty, normalize c_axis for trial
c_limits_glo_all_trial_br_stim(2,:) = caxis;
c_max = max(max(RHO_all_glo_breathing_adjusted-...
diag(diag(RHO_all_glo_breathing_adjusted))));
c_limits_glo_all_trial_br_stim(2,2) = c_max;
else % Use c_axis if given, e.g. c_axis = [-1 1]
caxis(c_axis)
end
if isempty(colorbar_m)
colormap(redblue())
else
colormap(redblue(colorbar_m))
end
axis image
% FIL Glomeruli with stimulus adjusted
glo_stimulus_adjusted_truncated = cell2mat(glo_stimulus_adjusted_WINDOWED);
RHO_all_glo_stimulus_adjusted = corr(glo_stimulus_adjusted_truncated');
subplot(2,2,3)
imagesc(RHO_all_glo_stimulus_adjusted)
title('Adjusted for Stimulus')
h_bar = colorbar;
ylabel(h_bar,'\rho')
set(gca, 'FontSize', 24)
xlabel('Glomerulus')
ylabel('Glomerulus')
if isempty(c_axis) % If c_axis unspecified/empty, normalize c_axis for trial
c_limits_glo_all_trial_br_stim(3,:) = caxis;
c_max = max(max(RHO_all_glo_stimulus_adjusted-...
diag(diag(RHO_all_glo_stimulus_adjusted))));
c_limits_glo_all_trial_br_stim(3,2) = c_max;
else % Use c_axis if given, e.g. c_axis = [-1 1]
caxis(c_axis)
end
if isempty(colorbar_m)
colormap(redblue())
else
colormap(redblue(colorbar_m))
end