-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot_current.m
More file actions
1824 lines (1448 loc) · 62.6 KB
/
plot_current.m
File metadata and controls
1824 lines (1448 loc) · 62.6 KB
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
% Plot the currents used in the experiments
clear all;
close all;
clc;
%%
f = filesep;
% Linux server
%local_root_path = '~/Projects/';
% Handata Server on Linux
server_root_path = '~/handata_server/eng_research_handata3/';
% Windows server
local_root_path = 'C:\Users\fabri\BOSTON UNIVERSITY Dropbox\RKC-HanLab\Pierre PV DBS Project Dropbox\Materials\Interm_Data\';
addpath('../Packages/');
% List path where all of the matfiles are stored
%pv_data_path = [local_root_path 'Pierre Fabris' f 'PV DBS neocortex' f 'PV_Data' f];
% Data on local linux machine
%pv_data_path = [local_root_path 'Pierre Fabris' f 'PV DBS neocortex' f 'PV_Data' f];
% Data on handata3 folder
pv_data_path = [server_root_path 'Pierre Fabris' f 'PV Project' f 'PV_Data' f];
%savepath = Multi_func.save_plot;
% Windows
savepath = 'C:\Users\fabri\BOSTON UNIVERSITY Dropbox\Pierre Fabris\Pierre PV DBS Project Dropbox\Materials\Plots\';
exclude_200ms = 1;
% CSV file to determine which trials to ignore
%ignore_trial_dict = Multi_func.csv_to_struct([local_root_path 'Pierre Fabris' f 'PV DBS neocortex' f ...
% 'Stim Recordings' f 'Data_Config' f 'byvis_ignore.csv']);
% Check that the server path exists
if ~isfolder(local_root_path)
disp('Server rootpath does not exist!!!');
return;
end
%% Load all region data
% Use congregated data to save all of the currents
% Read in the saved pv data and perform analysis
if ~exclude_200ms
save_all_data_file = [local_root_path 'Pierre Fabris' f 'PV DBS neocortex' f 'Interm_Data' f 'pv_data.mat'];
else
save_all_data_file = [local_root_path 'Pierre Fabris' f 'PV DBS neocortex' f 'Interm_Data' f 'pv_data_ex200.mat'];
end
tic;
%Load the data
load(save_all_data_file);
toc
disp('Finished Loading Data');
%% <--- determine if the file that has the current info for the flicker experiments is older than the interm pickle file
%% Relabel mouse names from their ID tags
mouse_rename = struct();
mice_names = fieldnames(Multi_func.mouse_color)';
for f_i = 1:length(mice_names)
mouse_rename.(mice_names{f_i}) = ['Mouse ' num2str(f_i)];
end
%% Read in the flicker amplitude data into our currents structure
% Note: Need to only do this once, otherwise neuron names will keep getting appended
% to the end of region_data
% Check if there are more than 27 number of neurons for V1, if there are,
% it means that the flicker experiment data was already added
if ~(length(region_data.r_V1.f_40.neuron_name) > 27)
T = readtable([savepath 'Current' f 'flicker_current.csv']);
% Convert the recording session date to string
T.session = string(T.session);
for i=1:height(T)
freq = T{i, 'stim_freq'};
params = T{i, 'nr_params'}{:};
amp_str = regexp(params, '\d+', 'match');
amp = str2num(amp_str{:});
% Add current data back into structure
region_data.r_V1.(['f_' num2str(freq)]).currents ...
= [region_data.r_V1.(['f_' num2str(freq)]).currents, amp];
% Parse out the mouse name and recording session
mouse_name = T{i, 'mouse'};
mouse_name = mouse_name{:};
mouse_name = strsplit(mouse_name, '_');
mouse_name = mouse_name{1};
session_id = T{i, 'session'};
% Construct full neuron name similar to the regular 3-second stimulation trials
nr_name_array = string({mouse_name, "V1", session_id, "FOV", freq, amp});
full_nr_name = join(nr_name_array, '_');
% Add neuron name back into region_data structure
region_data.r_V1.(['f_' num2str(freq)]).neuron_name{end + 1} = char(full_nr_name);
end
end
%% Loop through and save the current amplitude for each neuron
% Loop through regions
for f_region = fieldnames(region_data)'
f_region = f_region{1};
data_bystim = region_data.(f_region);
stims = fieldnames(data_bystim);
% Skip CA1 neurons from this plot
if strcmp(f_region, 'r_CA1') == 1
continue;
end
% Loop through stim frequencies
for f_stim = stims'
f_stim = f_stim{1};
popul_data = data_bystim.(f_stim);
% Store the current amplitude for each neuron
pop_amps = [];
% Loop through each neuron
for nr=1:length(popul_data.neuron_name)
tokens = regexp(popul_data.neuron_name{nr}, '_', 'split');
% Parse out the current amperage
fov_i = find(contains(tokens, 'FOV', 'IgnoreCase', true) == 1);
amp_i = fov_i + 2;
if contains(tokens{amp_i}, '.') == 1
amp_str = regexp(tokens{amp_i}, '\.', 'split');
amp_str = amp_str{1};
else
amp_str = tokens{amp_i};
end
% Store the amperage into array
amp = str2num(amp_str);
pop_amps(end + 1) = amp;
end
% Save the currents
region_data.(f_region).(f_stim).currents = pop_amps;
end
end
%% Print the central value and dispersion for each condition
for f_region = fieldnames(region_data)'
f_region = f_region{1};
% Skip CA1 neurons from this plot
if strcmp(f_region, 'r_CA1') == 1
continue;
end
data_bystim = region_data.(f_region);
stims = fieldnames(region_data.(f_region));
% Store both frequency currents
reg_currents = [];
reg_mice = {};
for f_stim = stims'
f_stim = f_stim{1};
popul_data = data_bystim.(f_stim);
% Consolidate all of the currents together
reg_currents = [reg_currents, popul_data.currents];
% Grab all of the mice cage number names
names = cellfun(@(s) s(1:strfind(s, '_') - 1), popul_data.neuron_name, 'UniformOutput', false);
% Append all of the mice names into one array
reg_mice = [reg_mice, names];
% Average and std current
avg_amp = nanmean(popul_data.currents);
std_amp = nanstd(popul_data.currents);
% Median and iqr current
med_amp = nanmedian(popul_data.currents);
iqr_amp = iqr(popul_data.currents);
% Print each condition's stats
disp(['Mean+std: ' f_region(3:end) ' ' f_stim(3:end) ...
': ' num2str(avg_amp) '+-' num2str(std_amp)]);
disp(['Median+iqr: ' f_region(3:end) ' ' f_stim(3:end) ...
': ' num2str(med_amp) '+-' num2str(iqr_amp)]);
fprintf('\n');
end
% Calculate the average current amperage and std
disp([f_region ': ' num2str(nanmean(reg_currents)) '+-' num2str(nanstd(reg_currents)) ...
' m=' num2str(length(unique(reg_mice))) ]);
% Calculate the number of unique mice for each region
fprintf('\n\n');
%DEBUG
%unique(reg_mice)
end
%% Print the amplitude ranges for each brain region and stimulation frequency
for f_region = fieldnames(region_data)'
f_region = f_region{1};
% Skip CA1 neurons from this plot
if strcmp(f_region, 'r_CA1') == 1
continue;
end
stims = fieldnames(region_data.(f_region));
data_bystim = region_data.(f_region);
% Loop through stim frequencies
for f_stim = stims'
f_stim = f_stim{1};
popul_data = data_bystim.(f_stim);
% Display the conditions
disp([f_region ' ' f_stim]);
disp(['Current Range: ' num2str(min(popul_data.currents)) ...
'-' num2str(max(popul_data.currents)) ]);
disp([num2str(mean(popul_data.currents)) '+-' num2str(std(popul_data.currents)) ]);
% Print the number of recordings
disp(['Num recordings: ' num2str(length(popul_data.currents))]);
% Grab all of the mice cage number names
names = cellfun(@(s) s(1:strfind(s, '_') - 1), popul_data.neuron_name, 'UniformOutput', false);
unique_names = unique(names);
% Print the number of unique mice
disp(['Num mice: ' num2str(length(unique_names))]);
fprintf('\n');
end
end
%% Plot the current amplitudes for each brain region and stimulation frequency
% Also do the current statistical test for current amplitude
% Store the data and labels for the violinplots
data = [];
labels = [];
for f_region = fieldnames(region_data)'
f_region = f_region{1};
data_bystim = region_data.(f_region);
stims = fieldnames(data_bystim);
% Skip CA1 neurons from this plot
if strcmp(f_region, 'r_CA1') == 1
continue;
end
% Loop through stim frequencies
for f_stim = stims'
f_stim = f_stim{1};
popul_data = data_bystim.(f_stim);
% Add the current amplitudes to violin arrays
data = [data, popul_data.currents];
labels = [labels, repmat({[f_region ' ' f_stim]}, 1, length(popul_data.currents))];
end
end
% Make the violinplots
figure('Renderer', 'Painters');
violinOpts = Multi_func.get_default_violin();
violinplot(data(:)', labels, 'GroupOrder', ...
{'r_M1 f_140', 'r_M1 f_40', 'r_V1 f_140', 'r_V1 f_40'}, ...
violinOpts);
ylabel('Current (uamp)');
Multi_func.set_default_axis(gca);
saveas(gcf, [savepath 'Current/' 'violin_current_by_condtion.png']);
saveas(gcf, [savepath 'Current/' 'violin_current_by_condtion.pdf']);
% Perform statistical analysis on the current amplitudes and log the stats
stats_log = [savepath 'Current' f 'region_stim_stats'];
if exist(stats_log), delete(sprintf('%s', stats_log)), end;
diary(stats_log);
diary off
diary on;
[p, h, stats] = kruskalwallis(data, labels)
disp('Group Columns');
disp(stats.gnames');
c = multcompare(stats, 'CriticalValueType', 'dunn-sidak')
diary off;
%% Loop through and calculate charge density for each neuron
% Perform statistical analysis on the current amplitudes and log the stats
stats_log = [savepath 'Current' f 'charge_density_calcs'];
if exist(stats_log), delete(sprintf('%s', stats_log)), end;
diary(stats_log);
diary off;
electrode_diam = 127*10^-4; % 127 um converted to cm
electrode_shave_len = 500 * 10^-4; % 500 um converted to cm
total_electrode_area = (pi * ((electrode_diam/2)^2)) + ...
(pi * electrode_shave_len * electrode_diam);
phase_width = 200*10^-6; % S
data = [];
labels = [];
for f_region = fieldnames(region_data)'
f_region = f_region{1};
% Skip CA1 neurons from this plot
if strcmp(f_region, 'r_CA1') == 1
continue;
end
data_bystim = region_data.(f_region);
stims = fieldnames(data_bystim);
% Loop through stim frequencies
for f_stim = stims'
f_stim = f_stim{1};
popul_data = data_bystim.(f_stim);
% Charge densities
charg_dens = popul_data.currents * (phase_width)/(total_electrode_area)
data = [data, charg_dens];
labels = [labels, repmat({[f_region ' ' f_stim]}, 1, length(charg_dens))];
region_data.(f_region).(f_stim).charge_density = charg_dens;
% Plot the average and standard deviation of the charge density used
diary on;
disp([f_region ' ' f_stim]);
disp([num2str(mean(charg_dens)) '+- ' num2str(std(charg_dens)) ' (uamp/cm^2)']);
fprintf('\n\n');
diary off;
end
end
% Make the violinplots
figure('Renderer', 'Painters');
violinOpts = Multi_func.get_default_violin();
violinplot(data(:)', labels, 'GroupOrder', ...
{'r_M1 f_140', 'r_M1 f_40', 'r_V1 f_140', 'r_V1 f_40'}, ...
violinOpts);
ylabel('Current (uamp)');
Multi_func.set_default_axis(gca);
saveas(gcf, [savepath 'Current/' 'violin_charge_density_by_condtion.png']);
saveas(gcf, [savepath 'Current/' 'violin_charge_density_by_condtion.pdf']);
%% Plotting current from days to surgery for each neuron
% Red: 140Hz
% Blue: 40Hz
% Circle: M1
% Plus: V1
%A map that keeps track of how many repetitions there are
%of number of days since surgery and amperage
days_amp_map = [];
mouse_color = struct();
figure('Position', [0 0 1000 800]);
% Loop through regions
for f_region = fieldnames(region_data)'
f_region = f_region{1};
% Skip CA1 neurons from this plot
if strcmp(f_region, 'r_CA1') == 1
continue;
end
data_bystim = region_data.(f_region);
stims = fieldnames(data_bystim);
% Loop through stim frequencies
for f_stim = stims'
f_stim = f_stim{1};
popul_data = data_bystim.(f_stim);
% Keep track of neurons plotted
neurons_plotted = [];
% Loop through each neuron
for nr=1:length(popul_data.neuron_name)
if ismember(nr, neurons_plotted)
continue;
end
tokens = regexp(popul_data.neuron_name{nr}, '_', 'split');
% Find all of the neurons that come from the same mouse
same_m_nrs = find(contains(popul_data.neuron_name, tokens{1}) == 1);
same_m_nrs_pts = [];
neurons_plotted = cat(2, neurons_plotted, same_m_nrs);
for i=same_m_nrs
tokens = regexp(popul_data.neuron_name{i}, '_', 'split');
% Calculate the days between imaging and surgery date
surg_date = popul_data.surgery_date.(['m_' tokens{1}]);
if isempty(surg_date)
continue;
end
tokens{3} = erase(tokens{3}, 'rec');
surg_date = datetime(surg_date, 'InputFormat', 'yyyyMMdd');
img_date = datetime(tokens{3}, 'InputFormat', 'yyyyMMdd');
days_from_surg = days(img_date - surg_date);
%DEBUG
if days_from_surg > 400
disp(popul_data.neuron_name{i});
end
% Parse out the current amperage
fov_i = find(contains(tokens, 'FOV') == 1);
amp_i = fov_i + 2;
if contains(tokens{amp_i}, '.') == 1
amp_str = regexp(tokens{amp_i}, '\.', 'split');
amp_str = amp_str{1};
else
amp_str = tokens{amp_i};
end
% Set labels based on brain region and stim frequency
plot_str = '';
if strcmp(f_region, 'r_M1') == 1
plot_str(end+1) = 'o';
elseif strcmp(f_region, 'r_V1') == 1
plot_str(end+1) = '+';
end
% Set the frequency stuff
if strcmp(f_stim, 'f_40') == 1
plot_str(end+1) = 'b';
elseif strcmp(f_stim, 'f_140') == 1
plot_str(end+1) = 'r';
end
% Increment the marker size for repeated points
if size(days_amp_map, 1) < days_from_surg | size(days_amp_map, 2) < str2num(amp_str)
days_amp_map(days_from_surg, str2num(amp_str)) = 1;
else
days_amp_map(days_from_surg, str2num(amp_str)) = ...
1 + days_amp_map(days_from_surg, str2num(amp_str));
end
% Plot data point
hold on;
plot(days_from_surg, str2num(amp_str), plot_str, 'MarkerSize', 8 + days_amp_map(days_from_surg, str2num(amp_str)));
hold on;
% Keep track of points
same_m_nrs_pts(:, end + 1) = [days_from_surg; str2num(amp_str)];
end
% Plot lines across all FOVs of the same mouse
%sort the x values from decreasing to increasing, makes figure easier to read
if ~isempty(same_m_nrs_pts)
[~, i] = sort(same_m_nrs_pts(1, :));
if isfield(mouse_color, ['m_' tokens{1}])
color = mouse_color.(['m_' tokens{1}]);
plot(same_m_nrs_pts(1, i), same_m_nrs_pts(2, i), '-', 'Color', color);
else
plot_h = plot(same_m_nrs_pts(1, i), same_m_nrs_pts(2, i), '-');
mouse_color.(['m_' tokens{1}]) = get(plot_h, 'Color');
end
hold on;
end
end
end
end
% Add legend label for each item
text(400, 600, '+: V1 region');
hold on;
text(400, 580, 'o: M1 region');
hold on;
text(400, 560, '140Hz', 'Color', 'r');
hold on;
text(400, 540, '40Hz', 'Color', 'b');
hold on;
y_val = 600;
for mouse_f=fieldnames(mouse_color)'
mouse_f = mouse_f{1};
text(450, y_val, '--', 'Color', mouse_color.(mouse_f), 'FontWeight', 'bold');
y_val = y_val - 20;
end
% Labels
xlabel('Days since surgery (days)');
ylabel('Amperage (uamp)');
% Set the axis
Multi_func.set_default_axis(gca);
saveas(gcf, [savepath 'Current/' '2d_currents_per_mouse_by_region_frequency.png']);
saveas(gcf, [savepath 'Current/' '2d_currents_per_mouse_by_region_frequency.pdf']);
%% Plotting current from first day of imaging for each neuron separate plots for
% each brain region and stimulation frequency
% TODO were some neurons plotted the same?? check for the long 390 days
% thing
% Red: 140Hz
% Blue: 40Hz
% Circle: M1
% Plus: V1
% Flag for loggin the scales
log_f = 0;
% Loop through regions
for f_region = fieldnames(region_data)'
f_region = f_region{1};
% Skip CA1 neurons from this plot
if strcmp(f_region, 'r_CA1') == 1
continue;
end
data_bystim = region_data.(f_region);
stims = fieldnames(data_bystim);
% Loop through stim frequencies
for f_stim = stims'
f_stim = f_stim{1};
popul_data = data_bystim.(f_stim);
figure('Position', [0 0 1000 800]);
%A map that keeps track of how many repetitions there are
%of number of days since surgery and amperage
days_amp_map = [];
% Keep track of neurons plotted
neurons_plotted = [];
mouse_line_width = 4;
%set(gca, 'ColorOrder', hsv(10), 'NextPlot', 'replacechildren')
% Loop through each neuron
for nr=1:length(popul_data.neuron_name)
if ismember(nr, neurons_plotted)
continue;
end
% Grab tokens for the mouse number, which is the first element
tokens = regexp(popul_data.neuron_name{nr}, '_', 'split');
% Find all of the neurons that come from the same mouse
same_m_nrs = find(contains(popul_data.neuron_name, tokens{1}) == 1);
%DEBUG
disp(tokens{1});
disp(popul_data.neuron_name(same_m_nrs));
% Grab the first recording date
get_third = @(c_array) datetime(erase(c_array{3}, 'rec'), 'InputFormat', 'yyyyMMdd');
rec_days = cellfun(@(x) get_third(regexp(x, '_', 'split')), popul_data.neuron_name(same_m_nrs), ...
'UniformOutput', false);
first_rec_date = min([rec_days{:}]);
neurons_plotted = cat(2, neurons_plotted, same_m_nrs);
same_m_nrs_pts = [];
for i=same_m_nrs
tokens = regexp(popul_data.neuron_name{i}, '_', 'split');
% Get the imaging date
tokens{3} = erase(tokens{3}, 'rec');
img_date = datetime(tokens{3}, 'InputFormat', 'yyyyMMdd');
% Calculate the days between imaging and surgery date
%surg_date = popul_data.surgery_date.(['m_' tokens{1}]);
%if isempty(surg_date)
% continue;
%end
%surg_date = datetime(surg_date, 'InputFormat', 'yyyyMMdd');
% Old way was using the surgery date from recording date
%days_from_surg = days(img_date - surg_date);
days_from_first = days(img_date - first_rec_date);
% Add 1 to every day if going to log the scale
if log_f
days_from_first = days_from_first + 1;
end
% Parse out the current amperage
fov_i = find(contains(tokens, 'FOV') == 1);
amp_i = fov_i + 2;
if contains(tokens{amp_i}, '.') == 1
amp_str = regexp(tokens{amp_i}, '\.', 'split');
amp_str = amp_str{1};
else
amp_str = tokens{amp_i};
end
% Set labels based on brain region and stim frequency
plot_str = '';
plot_str(end + 1) = 'o';
%if strcmp(f_region, 'r_M1') == 1
% plot_str(end+1) = 'o';
%elseif strcmp(f_region, 'r_V1') == 1
% plot_str(end+1) = '+';
%end
% Originally Set the frequency stuff
%if strcmp(f_stim, 'f_40') == 1
% plot_str(end+1) = 'b';
%elseif strcmp(f_stim, 'f_140') == 1
% plot_str(end+1) = 'r';
%end
% Set default to dark
plot_str(end + 1) = 'k';
% Increment the marker size for repeated points
% Need to shift the index for days from first because 0 is not a primary index
if size(days_amp_map, 1) < days_from_first + 1 | size(days_amp_map, 2) < str2num(amp_str)
days_amp_map(days_from_first + 1, str2num(amp_str)) = 1;
else
days_amp_map(days_from_first + 1, str2num(amp_str)) = ...
1 + days_amp_map(days_from_first + 1, str2num(amp_str));
end
% Plot data point
hold on;
plot(days_from_first, str2num(amp_str), plot_str, ...
'HandleVisibility', 'off', ...
'MarkerSize', 4 + 4*days_amp_map(days_from_first + 1, str2num(amp_str)));
hold on;
% Keep track of points
same_m_nrs_pts(:, end + 1) = [days_from_first; str2num(amp_str)];
%EBUG
%disp(length(same_m_nrs_pts));
end
% Plot lines across all FOVs of the same mouse
if ~isempty(same_m_nrs_pts)
[~, i] = sort(same_m_nrs_pts(1, :));
% Specify color based on stim frequency
if strcmp(f_stim, 'f_40') == 1
color = 'b';
elseif strcmp(f_stim, 'f_140') == 1
color = 'r';
end
% Old plotting with the same color for the frequency
%plot(same_m_nrs_pts(1, i), same_m_nrs_pts(2, i), '-', 'Color', color);
% Plot a line if neurons have different amperages,
% otherwise just plot a point
if length(unique(same_m_nrs_pts(1, :))) == 1 && length(unique(same_m_nrs_pts(2, :))) == 1
plot(same_m_nrs_pts(1, 1), same_m_nrs_pts(2, 1), '.', 'MarkerSize', 4*mouse_line_width, 'DisplayName', tokens{1});
hold on;
else
plot(same_m_nrs_pts(1, i), same_m_nrs_pts(2, i), '-', ...
'LineWidth', mouse_line_width, ...
'DisplayName', tokens{1});
end
% If wanted to use distinct color for each mouse
%if isfield(mouse_color, ['m_' tokens{1}])
% color = mouse_color.(['m_' tokens{1}]);
% plot(same_m_nrs_pts(1, i), same_m_nrs_pts(2, i), '-', 'Color', color);
%else
% plot_h = plot(same_m_nrs_pts(1, i), same_m_nrs_pts(2, i), '-');
% mouse_color.(['m_' tokens{1}]) = get(plot_h, 'Color');
%end
hold on;
mouse_line_width = mouse_line_width - 0.5;
end
% EBUG
%if strcmp(f_region, 'r_M1') == 1 && strcmp(f_stim, 'f_40') == 1
% pause(3);
% drawnow;
%end
end
%DEBUG, something is wrong with this code
% Count number of neurons
%f_region
%f_stim
%sum(days_amp_map, "all")
% % Print out the number of neurons for this condition
%length(popul_data.neuron_name)
%
%neurons_plotted
% Check if all enruons were plotted
%h = findobj(gca,'Type','scatter');
%numPoints = arrayfun(@(x) size(x.XData,2), h)
%h = findobj(gcf,'Type','line');
%numPoints = arrayfun(@(x) length(x.XData), h)
disp(length(popul_data.neuron_name));
disp(length(neurons_plotted));
if length(neurons_plotted) ~= length(popul_data.neuron_name)
disp('Not the same');
end
% Labels
xlabel('Days since first recording (days)');
ylabel("Amperage (uamp)");
%ylabel({'Amperage', '(uamp)'});
% Set the axis
Multi_func.set_default_axis(gca);
% Log the scales
if log_f
set(gca, 'XScale', 'log', 'YScale', 'log');
end
y_limits = ylim;
y_range = range(y_limits);
ylim([0, y_limits(2) + .1*y_range]); % scaled lower end y_limits(1) - .1*y_range
x_limits = xlim;
x_range = range(x_limits);
xlim([x_limits(1) - .1*x_range, x_limits(2) + .1*x_range]);
% Make x-axis conditional by brain region
%if strcmp(f_region, 'r_M1') == 1
% x_limits = xlim;
% xlim([-10 x_limits(2)]);
%elseif strcmp(f_region, 'r_V1') == 1
% x_limits = xlim;
% xlim([-40 x_limits(2)]);
%end
legend();
% Title
title([f_region ' ' f_stim], 'Interpreter', 'none');
ax = gca;
ax.Units = "centimeters";
ax.InnerPosition = [10 10 5.9828 5.1729 ];
set(gcf,'Units','centimeters');
fontsize(gcf, 10, "points");
saveas(gcf, [savepath 'Current/' f_region '_' f_stim '_2d_currents_per_mouse_by_frequency_log' num2str(log_f) '.png']);
saveas(gcf, [savepath 'Current/' f_region '_' f_stim '_2d_currents_per_mouse_by_frequency_log' num2str(log_f) '.pdf']);
% TODO check that the number of points plotted equals the number of
% neurons for this condition
end
end
%% Plotting current from days to first recording date for each neuron with violinplots for different time ranges
% Specify the boundaries for each
% This range seems decent
%day_ranges = [0 1 20];
day_ranges = [0 7 21];
% Loop through regions
for f_region = fieldnames(region_data)'
f_region = f_region{1};
% Skip CA1 neurons from this plot
if strcmp(f_region, 'r_CA1') == 1
continue;
end
data_bystim = region_data.(f_region);
stims = fieldnames(data_bystim);
% Loop through stim frequencies
for f_stim = stims'
f_stim = f_stim{1};
popul_data = data_bystim.(f_stim);
% Keep track of neuron points in a table
% - store the x and y, with mouse ID, and determine the range for
% each point
current_t = table('Size', [0 4], 'VariableTypes', {'string', 'double', 'double', 'double'}, ...
'VariableNames',{'mID', 'x', 'y', 'jitter'});
neurons_saved = [];
% Loop through each neuron
for nr=1:length(popul_data.neuron_name)
if ismember(nr, neurons_saved)
continue;
end
% Grab tokens for the mouse number, which is the first element
tokens = regexp(popul_data.neuron_name{nr}, '_', 'split');
% Find all of the neurons that come from the same mouse
same_m_nrs = find(contains(popul_data.neuron_name, tokens{1}) == 1);
% Grab the first recording date
get_third = @(c_array) datetime(erase(c_array{3}, 'rec'), 'InputFormat', 'yyyyMMdd');
rec_days = cellfun(@(x) get_third(regexp(x, '_', 'split')), popul_data.neuron_name(same_m_nrs), ...
'UniformOutput', false);
first_rec_date = min([rec_days{:}]);
neurons_saved = cat(2, neurons_saved, same_m_nrs);
% I do not think I need this
same_m_nrs_pts = [];
% Loop through mouse's neurons
for i=same_m_nrs
tokens = regexp(popul_data.neuron_name{i}, '_', 'split');
tokens{3} = erase(tokens{3}, 'rec');
img_date = datetime(tokens{3}, 'InputFormat', 'yyyyMMdd');
% Calculate the days from the first recording day
days_from_first = days(img_date - first_rec_date);
% Parse out the current amperage
fov_i = find(contains(tokens, 'FOV') == 1);
amp_i = fov_i + 2;
if contains(tokens{amp_i}, '.') == 1
amp_str = regexp(tokens{amp_i}, '\.', 'split');
amp_str = amp_str{1};
else
amp_str = tokens{amp_i};
end
% Save the x and y point to the table
newRow = table(string(tokens{1}), days_from_first, str2num(amp_str), nan, ...
'VariableNames', current_t.Properties.VariableNames);
current_t = [current_t; newRow];
% Increment the marker size for repeated points
% Need to shift the index for days from first because 0 is not a primary index
if size(days_amp_map, 1) < days_from_first + 1 | size(days_amp_map, 2) < str2num(amp_str)
days_amp_map(days_from_first + 1, str2num(amp_str)) = 1;
else
days_amp_map(days_from_first + 1, str2num(amp_str)) = ...
1 + days_amp_map(days_from_first + 1, str2num(amp_str));
end
% Plot data point
%hold on;
%plot(days_from_first, str2num(amp_str), plot_str, 'MarkerSize', 4 + 4*days_amp_map(days_from_first + 1, str2num(amp_str)));
%hold on;
% Keep track of points
same_m_nrs_pts(:, end + 1) = [days_from_first; str2num(amp_str)];
end
end
% Add max amperage to day ranges
if max(day_ranges) < max(current_t.x)
max_x = max(current_t.x);
max_dayrange = max(day_ranges);
cur_day_ranges = day_ranges;
cur_day_ranges(end + 1) = max(current_t.x);
end
% Create the ranges for the violinplots
range_lbl = {};
for i = 1:length(cur_day_ranges) - 1
range_lbl{end+1} = [num2str(cur_day_ranges(i)) '-' num2str(cur_day_ranges(i+1))];
end
current_t.violin_lbl = string(discretize(current_t.x, cur_day_ranges, range_lbl));
% Reset range label to what exists in the table
range_lbl = unique(current_t.violin_lbl);
% Sort the labels
leftVals = arrayfun(@(s) sscanf(s, '%d-%*d'), range_lbl);
[~, idx] = sort(leftVals);
range_lbl = range_lbl(idx)
% Plot the violins
figure('Position', [100 100 700 500]);
% Add violin plot to figure
violinOpts = Multi_func.get_default_violin();
%violinOpts.FaceColor = [0.6 0.6 0.6];
%violinOpts.EdgeColor = 'k';
violinOpts.ViolinColor = {[0.6 0.6 0.6]};
violinplot(current_t.y, current_t.violin_lbl, 'ShowData', false, ...
'GroupOrder', cellstr(range_lbl) ,violinOpts);
hold on;
all_scat_h = [];
lbl_plot_order = {};
% Loop through mice and plot their scatter
for range_i = 1:length(range_lbl)
% Grab points for this violin range
idxs = (current_t.violin_lbl == range_lbl(range_i));
y_data = current_t.y(idxs);
% Skip this group if there are no points
if isempty(y_data)
continue;
end
% Computer jitter based on density
[f, xi] = ksdensity(y_data);
density = interp1(xi, f, y_data);
max_w = 0.3;
width = (density/max(density)) * max_w;
x_jitter = range_i + (rand(length(y_data),1)*2 - 1).*width;
current_t.jitter(idxs) = x_jitter;
% Loop through unique mice
for mouse = unique(current_t.mID)'
idxs = (current_t.mID == mouse) & ...
(current_t.violin_lbl == range_lbl(range_i));
%gscatter(range_i*ones(sum(idxs), 1), current_t.y(idxs), ...
% current_t.mID(idxs), mouse_color.('m' + mouse) ...
% , '.', 24);
h = gscatter(current_t.jitter(idxs), current_t.y(idxs), ...
current_t.mID(idxs), Multi_func.mouse_color.('m' + mouse) ...
, '.', 24);
all_scat_h = [all_scat_h; h];
lbl_plot_order{end + 1} = char(mouse);
%scatter(range_i*ones(sum(idxs), 1), current_t.y(idxs));
hold on;
%drawnow;
%pause(0.5);
end
end
% Grab unique mouse labels
[unique_m, ia] = unique(lbl_plot_order, 'stable');
% Rename mice name
for i = 1:length(unique_m)
unique_m{i} = mouse_rename.(['m' unique_m{i}]);
end
h_l = legend(all_scat_h(ia), unique_m, 'Location', 'none');
h_l.Position = [0.5 0.3 0.06 0.2];
Multi_func.set_default_axis(gca);
ax = gca;
ax.Units = "centimeters";
ax.InnerPosition = [2 2 5.9828 5.1729]; % 10 10
fontsize(gcf, 10, 'points');
% Labels
xlabel('Time since first recording (days)');
ylabel('Amperage (uamp)');
% Save plot for this stimulation condition
% Title
title([f_region ' ' f_stim], 'Interpreter', 'none');
saveas(gcf, [savepath 'Current/' f_region '_' f_stim '_Current_Mouse_Violin.png']);
saveas(gcf, [savepath 'Current/' f_region '_' f_stim '_Current_Mouse_Violin.pdf']);
end
end
%% Fit Current for each mouse
% Plotting current from first day of imaging for each neuron separate plots for
% each brain region and stimulation frequency
% Each color is a unique mouse and a curve is fitted for its points
% Mean current is taken for neurons recorded on the same day for the same
% mouse
% Flag for loggin the scales
log_f = 0;
% Loop through regions
for f_region = fieldnames(region_data)'
f_region = f_region{1};