-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBayes_Op_estim_2021_09_01.m
More file actions
4413 lines (3696 loc) · 192 KB
/
Bayes_Op_estim_2021_09_01.m
File metadata and controls
4413 lines (3696 loc) · 192 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
% %EFF21 is comment signaling change to make code more efficient
% use single for spike_val but not for spike_times
% spikes_trigger and spikes_trigger_stop are not yet sparse
% update sz_on_index and sz_off_index in own function and check for
% emptyness before trying to save
% spikes_trigger to sparse? spikes_trigger initialization
% when loading data and then resaving them it might be slightly off with
% being exactly every 600 time (60*10), so saving vars won't quite work.
% when to save if only running part of file but dont push stop
% spike_count_history becomes [spike_count_history spike_count_raw
% spike_count_combined] to reduce number of times we save to file. (columns
% next to each other.
%% INITIALIZATION OF GUI
function varargout = Bayes_Op_estim_2021_09_01(varargin)
% Bayes_Op_estim_2021_09_01 MATLAB code for Bayes_Op_estim_2021_09_01.fig
% Bayes_Op_estim_2021_09_01, by itself, creates a new Bayes_Op_estim_2021_09_01 or raises the existing
% singleton*.
%
% H = Bayes_Op_estim_2021_09_01 returns the handle to a new Bayes_Op_estim_2021_09_01 or the handle to
% the existing singleton*.
%
% Bayes_Op_estim_2021_09_01('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in Bayes_Op_estim_2021_09_01.M with the given input arguments.
%
% Bayes_Op_estim_2021_09_01('Property','Value',...) creates a new Bayes_Op_estim_2021_09_01 or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before Bayes_Op_estim_2021_09_01_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to Bayes_Op_estim_2021_09_01_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help Bayes_Op_estim_2021_09_01
% Last Modified by GUIDE v2.5 01-Sep-2021 22:26:47
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @Bayes_Op_estim_2021_09_01_OpeningFcn, ...
'gui_OutputFcn', @Bayes_Op_estim_2021_09_01_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
%% --- Executes just before Bayes_Op_estim_2021_09_01 is made visible.
function Bayes_Op_estim_2021_09_01_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to Bayes_Op_estim_2021_09_01 (see VARARGIN)
% Choose default command line output for bayes_opt_estim_v62
%Clear command window
clc
%Reset the Data Aquisition and Image Aquisition
daqreset
if license('test','image_acquisition_toolbox')
try
imaqreset
catch
disp('Cannot run imaqreset - computer might not have image aquisition toolbox');
warndlg('Cannot run imaqreset - computer might not have image aquisition toolbox');
end
end
handles.output = hObject;
%initialize flags used in offline detection and in troubleshooting
global DoTroubleshoot DoRestartOffline DoStopOffline DoPauseOffline
global DoLog
global DoSaveToFile DoResaveDataFiles DoFinishedFile
DoTroubleshoot=0;
DoStopOffline=0;
DoRestartOffline=0;
DoPauseOffline=0;
DoResaveDataFiles=0; %in offline mode, this flag will force resaving of individual data files ???!!!???built in as option?
DoLog=2; %1=create 1 log file for entire recording, 2=create log for every hour of running,0=no log file
DoSaveToFile=1; %standard is that program saves output to files (might get overridden by offline detection
DoFinishedFile=0; %for offline reanalysis, we have to know when to start new file
% Update handles structured
guidata(hObject, handles);
%% --- Outputs from this function are returned to the command line.
function varargout = Bayes_Op_estim_2021_09_01_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
%% FUNCTIONS CALLED WHEN PRESSING A BUTTON
% =====================================================================
%% --- Executes on button press: LOAD SETTINGS
% Will load the settings file provided in the input box next to it
function PB_LoadSettings_Callback(hObject, eventdata, handles)
% hObject handle to PB_LoadSettings (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global DoTroubleshoot
if DoTroubleshoot
disp('Run: PB_LoadSettings_Callback...')
end
%Load in the settings from the file provided
load(get(handles.ET_load_path,'String'));
%Overwrite the values from the structure struc to the GUI
% try
set(handles.ET_spike_dist_min,'String',struc.ET_spike_dist_min);
% end
% try
set(handles.ET_spike_dist_max,'String',struc.ET_spike_dist_max);
% end
% try
set(handles.ET_width_at_percent_height,'String',struc.ET_width_at_percent_height);
% end
% try
set(handles.ET_threshold_pos,'String',struc.ET_threshold_pos);
% end
% try
set(handles.ET_threshold_neg,'String',struc.ET_threshold_neg);
% end
% try
set(handles.ET_maxAmp_pos,'String',struc.ET_maxAmp_pos);
% end
% try
set(handles.ET_maxAmp_neg,'String',struc.ET_maxAmp_neg);
% end
% try
set(handles.ET_min_width,'String',struc.ET_min_width);
% end
% try
set(handles.ET_max_width,'String',struc.ET_max_width);
% end
% try
set(handles.ET_spike_dist_min_raw,'String',struc.ET_spike_dist_min_raw);
% end
% try
set(handles.ET_spike_dist_max_raw,'String',struc.ET_spike_dist_max_raw);
% end
% try
set(handles.ET_width_at_percent_height_raw,'String',struc.ET_width_at_percent_height_raw);
% end
% try
set(handles.ET_threshold_pos_raw,'String',struc.ET_threshold_pos_raw);
% end
% try
set(handles.ET_threshold_neg_raw,'String',struc.ET_threshold_neg_raw);
% end
% try
set(handles.ET_maxAmp_raw_pos,'String',struc.ET_maxAmp_raw_pos);
% end
% try
set(handles.ET_maxAmp_raw_neg,'String',struc.ET_maxAmp_raw_neg);
% end
% try
set(handles.ET_min_width_raw,'String',struc.ET_min_width_raw);
% end
% try
set(handles.ET_max_width_raw,'String',struc.ET_max_width_raw);
% end
% try
set(handles.ET_min_spikes_per_two_s,'String',struc.ET_min_spikes_per_two_s);
% end
% try
set(handles.ET_min_spikes_per_two_s_stop,'String',struc.ET_min_spikes_per_two_s_stop);
% end
% try
set(handles.ET_spike_logic_1,'String',struc.ET_spike_logic_1);
% end
% try
set(handles.ET_spike_logic_2,'String',struc.ET_spike_logic_2);
% end
% try
set(handles.ET_spike_logic_3,'String',struc.ET_spike_logic_3);
% end
% try
set(handles.ET_spike_logic_4,'String',struc.ET_spike_logic_4);
% end
% try
set(handles.ET_exclusion_time,'String',struc.ET_exclusion_time);
% end
% try
set(handles.ET_and_window,'String',struc.ET_and_window);
% end
% try
set(handles.ET_n_ch_in,'String',struc.ET_n_ch_in);
% end
% try
set(handles.ET_n_ch_out,'String',struc.ET_n_ch_out);
% end
% try
set(handles.ET_seizure_detection_channels,'String',struc.ET_seizure_detection_channels);
% end
% try
set(handles.ET_n_cams,'String',struc.ET_n_cams);
% end
% try
set(handles.ET_fs,'String',struc.ET_fs);
% end
% try
set(handles.ET_MonoOrBiPhasic,'String',struc.ET_MonoOrBiPhasic);
% end
% try
set(handles.ET_ampLo,'String',struc.ET_ampLo);
% end
% try
set(handles.ET_widthLo,'String',struc.ET_widthLo);
% end
% try
set(handles.ET_freqLo,'String',struc.ET_freqLo);
% end
% try
set(handles.ET_TrainDuration,'String',struc.ET_TrainDuration);
% end
% try
set(handles.ET_SaveFolder,'String',struc.ET_SaveFolder);
% end
% try
set(handles.ET_SaveName,'String',struc.ET_SaveName);
% end
% try
set(handles.ET_device_ID,'String',struc.ET_device_ID);
% end
% try
set(handles.ET_time_plot,'String',struc.ET_time_plot);
% end
% try
set(handles.ET_exclusion_time,'String',struc.ET_exclusion_time);
% end
set(handles.ET_channel_spacing,'String',struc.ET_channel_spacing);
% try
set(handles.ET_stim_dev,'String',struc.ET_stim_dev);
% end
% try
set(handles.ET_fs_stim,'String',struc.ET_fs_stim);
% end
% try
set(handles.ET_chgRatioHi,'String',struc.ET_chgRatioHi);
% end
% try
set(handles.ET_ampHi,'String',struc.ET_ampHi);
% end
% try
set(handles.ET_freqHi,'String',struc.ET_freqHi);
% end
% try
set(handles.ET_widthHi,'String',struc.ET_widthHi);
% end
% try
set(handles.ET_path_for_restart,'String',struc.ET_path_for_restart);
% end
% try
set(handles.ET_widthBins,'String',struc.ET_ampBins)
% end
% try
set(handles.ET_widthBins,'String',struc.ET_freqBins)
% end
% try
set(handles.ET_widthBins,'String',struc.ET_widthBins)
% end
% try
set(handles.ET_ampRatioLo,'String',struc.ET_ampRatioLo);
% end
% try
set(handles.ET_ampRatioHi,'String',struc.ET_ampRatioHi)
% end
% try
set(handles.ET_ampRatioBins,'String',struc.ET_ampRatioBins)
% end
% try
set(handles.ET_chgRatioLo,'String',struc.ET_chgRatioLo);
% end
% try
set(handles.ET_chgRatioHi,'String',struc.ET_chgRatioHi)
% end
% try
set(handles.ET_chgRatioBins,'String',struc.ET_chgRatioBins)
% end
try
set(handles.ET_optimize_vec,'String',struc.ET_optimize_vec)
end
try
set(handles.ET_non_optimized_val_vec,'String',struc.ET_non_optimized_val_vec)
end
try
set(handle.ET_non_optimized_val_vec_ch1,'String',struc.ET_non_optimized_val_vec_ch1)
end
try
set(handle.ET_non_optimized_val_vec_ch2,'String',struc.ET_non_optimized_val_vec_ch2)
end
try
set(handle.ET_non_optimized_val_vec_ch3,'String',struc.ET_non_optimized_val_vec_ch3)
end
try
set(handle.ET_non_optimized_val_vec_ch4,'String',struc.ET_non_optimized_val_vec_ch4)
end
try
set(handle.ET_non_optimized_val_vec,'String',struc.ET_non_optimized_val_vec)
end
try
set(handle.ET_non_optimized_val_vec_ch1_worst,'String',struc.ET_non_optimized_val_vec_ch1_worst)
end
try
set(handle.ET_non_optimized_val_vec_ch2_worst,'String',struc.ET_non_optimized_val_vec_ch2_worst)
end
try
set(handle.ET_non_optimized_val_vec_ch3_worst,'String',struc.ET_non_optimized_val_vec_ch3_worst)
end
try
set(handle.ET_non_optimized_val_vec_ch4_worst,'String',struc.ET_non_optimized_val_vec_ch4_worst)
end
guidata(hObject,handles);
%% --- SAVE_SETTINGS is called by PB_Go_Callback (after pressing GO)
function save_settings(path, settings_name, handles)
% hObject handle to PB_SaveSettings (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global DoTroubleshoot
if DoTroubleshoot
disp('Run: save_settings...')
end
struc.ET_n_ch_in=get(handles.ET_n_ch_in,'String');
struc.ET_n_ch_out=get(handles.ET_n_ch_out,'String');
struc.ET_seizure_detection_channels=get(handles.ET_seizure_detection_channels,'String');
struc.ET_n_cams=get(handles.ET_n_cams,'String');
struc.ET_fs=get(handles.ET_fs,'String');
struc.ET_MonoOrBiPhasic=get(handles.ET_MonoOrBiPhasic,'String');
struc.ET_ampLo=get(handles.ET_ampLo,'String');
struc.ET_widthLo=get(handles.ET_widthLo,'String');
struc.ET_freqLo=get(handles.ET_freqLo,'String');
struc.ET_TrainDuration=get(handles.ET_TrainDuration,'String');
struc.ET_SaveFolder=get(handles.ET_SaveFolder,'String');
struc.ET_SaveName=get(handles.ET_SaveName,'String');
struc.ET_load_path=get(handles.ET_load_path,'String');
struc.ET_spike_dist_min=get(handles.ET_spike_dist_min,'String');
struc.ET_spike_dist_max=get(handles.ET_spike_dist_max,'String');
struc.ET_width_at_percent_height=get(handles.ET_width_at_percent_height,'String');
struc.ET_threshold_pos=get(handles.ET_threshold_pos,'String');
struc.ET_threshold_neg=get(handles.ET_threshold_neg,'String');
struc.ET_maxAmp_pos=get(handles.ET_maxAmp_pos,'String');
struc.ET_maxAmp_neg=get(handles.ET_maxAmp_neg,'String');
struc.ET_min_width=get(handles.ET_min_width,'String');
struc.ET_max_width=get(handles.ET_max_width,'String');
struc.ET_spike_dist_min_raw=get(handles.ET_spike_dist_min_raw,'String');
struc.ET_spike_dist_max_raw=get(handles.ET_spike_dist_max_raw,'String');
struc.ET_width_at_percent_height_raw=get(handles.ET_width_at_percent_height_raw,'String');
struc.ET_threshold_pos_raw=get(handles.ET_threshold_pos_raw,'String');
struc.ET_threshold_neg_raw=get(handles.ET_threshold_neg_raw,'String');
struc.ET_maxAmp_raw_pos=get(handles.ET_maxAmp_raw_pos,'String');
struc.ET_maxAmp_raw_neg=get(handles.ET_maxAmp_raw_neg,'String');
struc.ET_min_width_raw=get(handles.ET_min_width_raw,'String');
struc.ET_max_width_raw=get(handles.ET_max_width_raw,'String');
struc.ET_min_spikes_per_two_s=get(handles.ET_min_spikes_per_two_s,'String');
struc.ET_min_spikes_per_two_s_stop=get(handles.ET_min_spikes_per_two_s_stop,'String');
struc.ET_spike_logic_1=get(handles.ET_spike_logic_1,'String');
struc.ET_spike_logic_2=get(handles.ET_spike_logic_2,'String');
struc.ET_spike_logic_3=get(handles.ET_spike_logic_3,'String');
struc.ET_spike_logic_4=get(handles.ET_spike_logic_4,'String');
struc.ET_exclusion_time = get(handles.ET_exclusion_time,'String');
struc.ET_and_window = get(handles.ET_and_window,'String');
struc.ET_device_ID = get(handles.ET_device_ID,'String');
struc.ET_time_plot = get(handles.ET_time_plot,'String');
struc.ET_channel_spacing = get(handles.ET_channel_spacing,'String');
struc.ET_stim_dev = get(handles.ET_stim_dev,'String');
struc.ET_fs_stim = get(handles.ET_fs_stim,'String');
struc.ET_chgRatioHi = get(handles.ET_chgRatioHi,'String');
struc.ET_ampHi = get(handles.ET_ampHi,'String');
struc.ET_freqHi = get(handles.ET_freqHi,'String');
struc.ET_widthHi = get(handles.ET_widthHi,'String');
struc.ET_path_for_restart = get(handles.ET_path_for_restart,'String');
struc.ET_ampBins = get(handles.ET_ampBins,'String');
struc.ET_freqBins = get(handles.ET_freqBins,'String');
struc.ET_widthBins = get(handles.ET_widthBins,'String');
struc.ET_ampRatioLo = get(handles.ET_ampRatioLo,'String');
struc.ET_ampRatioHi = get(handles.ET_ampRatioHi,'String');
struc.ET_ampRatioBins = get(handles.ET_ampRatioBins,'String');
struc.ET_chgRatioLo = get(handles.ET_chgRatioLo,'String');
struc.ET_chgRatioHi = get(handles.ET_chgRatioHi,'String');
struc.ET_chgRatioBins = get(handles.ET_chgRatioBins,'String');
struc.ET_optimize_vec = get(handles.ET_optimize_vec,'String');
struc.ET_non_optimized_val_vec_ch1 = get(handles.ET_non_optimized_val_vec_ch1 ,'String');
struc.ET_non_optimized_val_vec_ch2 = get(handles.ET_non_optimized_val_vec_ch2 ,'String');
struc.ET_non_optimized_val_vec_ch3 = get(handles.ET_non_optimized_val_vec_ch3 ,'String');
struc.ET_non_optimized_val_vec_ch4 = get(handles.ET_non_optimized_val_vec_ch4 ,'String');
struc.ET_non_optimized_val_vec = get(handles.ET_non_optimized_val_vec,'String');
struc.ET_non_optimized_val_vec_ch1_worst = get(handles.ET_non_optimized_val_vec_ch1_worst ,'String');
struc.ET_non_optimized_val_vec_ch2_worst = get(handles.ET_non_optimized_val_vec_ch2_worst ,'String');
struc.ET_non_optimized_val_vec_ch3_worst = get(handles.ET_non_optimized_val_vec_ch3_worst ,'String');
struc.ET_non_optimized_val_vec_ch4_worst = get(handles.ET_non_optimized_val_vec_ch4_worst ,'String');
save([path '\' settings_name '.mat'], 'struc');
%% --- Executes on button press in PB_Go: PRESSING THE GO BUTTON
function PB_Go_Callback(hObject, eventdata, handles)
% hObject handle to PB_Go (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%0. Create folder to save data in - use selected folder, but make subfolder with current time stamp
save_folder_base = get(handles.ET_SaveFolder,'String');
save_name = get(handles.ET_SaveName,'String');
date_stamp = datestr(datetime,'mm-dd-yyyy_HH-MM-SS');
save_folder = [save_folder_base '\' date_stamp];
handles.save_folder = save_folder;
if not(exist(save_folder,'dir'))
mkdir(save_folder)
else
warning('folder already exists')
end
%Optionally start a log file
global DoLog d_num
d_num = 1;
%Possibly start new log file
if DoLog
logname=[save_folder '\Log_Bayes_' num2str(d_num) '__' datestr(now,'mm_dd_yyyy__HH_MM') '.txt'];
diary(logname);
end
%Optionally show troubleshooting message on screen
global DoTroubleshoot
if DoTroubleshoot
disp('Run: PB_Go_Callback...')
end
global DoExisting %We are doing on demand (use of go button)
DoExisting=0;
%RUNS WHEN GO IS PRESSED
%1. Reset data aquisition
daqreset
if license('test','image_acquisition_toolbox')
imaqreset
end
rng(17);
%%
global q
p = gcp();
%%
restart_mat_paths = get(handles.ET_path_for_restart,'String'); % this could be multiple mats
restart_mat_paths_cell = strsplit(restart_mat_paths,';');
global prior_Seizure_Count prior_Seizure_Duration prior_stim_freq prior_stim_amp prior_stim_width prior_stim_ampRatio prior_stim_chgRatio
%2. Optionally load in data from given location prior to starting current session
% Loading in one or more summary files and aggregating data from those.
if not(isempty(restart_mat_paths))
%Initialize variables
n_ch_out = length(str2num(get(handles.ET_n_ch_out,'String')));
prior_Seizure_Count = zeros(1,n_ch_out);
prior_Seizure_Duration = [];
prior_stim_freq = [];
prior_stim_amp = [];
prior_stim_width = [];
prior_stim_ampRatio = [];
prior_stim_chgRatio = [];
%Loop through previous summary files
for i_mat = 1:length(restart_mat_paths_cell)
%Access summary file
mf_restart = matfile(restart_mat_paths_cell{1,i_mat});
%???!!!???might work with my new saving method
% prior_Seizure_Count = mf_restart.Seizure_Count; % doesn't work reliably because it is only saved at the end
% Seizure_Count = min([sum(mf_restart.stim_freq~=0,1); sum(mf_restart.Seizure_Duration~=0,1)],[],1);
Seizure_Count_mf = mf_restart.Seizure_Count;
%Loop through channels
for i_ch = 1:n_ch_out
if Seizure_Count_mf(i_ch)>0
%Extract stimulation parameters for current summary file
Seizure_Duration_ch = mf_restart.Seizure_Duration(1:Seizure_Count_mf(i_ch),i_ch);
stim_freq_ch = mf_restart.stim_freq(1:Seizure_Count_mf(i_ch),i_ch);
stim_amp_ch = mf_restart.stim_amp(1:Seizure_Count_mf(i_ch),i_ch); %tom:was not correctly saved previously due to typo, but data is also in duration amp freq
% stim_amp_ch = mf_restart.duration_amp_freq(1:Seizure_Count_mf(i_ch),(i_ch-1)*3+2);
stim_width_ch = mf_restart.stim_width(1:Seizure_Count_mf(i_ch),i_ch);
stim_ampRatio_ch = mf_restart.stim_ampRatio(1:Seizure_Count_mf(i_ch),i_ch);
stim_cghRatio_ch = mf_restart.stim_chgRatio(1:Seizure_Count_mf(i_ch),i_ch);
%Aggregate stimulation parameters for ALL summary files
prior_Seizure_Duration(prior_Seizure_Count(i_ch)+(1:Seizure_Count_mf(i_ch)),i_ch) = Seizure_Duration_ch;
prior_stim_freq(prior_Seizure_Count(i_ch)+(1:Seizure_Count_mf(i_ch)),i_ch) = stim_freq_ch;
prior_stim_amp(prior_Seizure_Count(i_ch)+(1:Seizure_Count_mf(i_ch)),i_ch) = stim_amp_ch;
prior_stim_width(prior_Seizure_Count(i_ch)+(1:Seizure_Count_mf(i_ch)),i_ch) = stim_width_ch;
prior_stim_ampRatio(prior_Seizure_Count(i_ch)+(1:Seizure_Count_mf(i_ch)),i_ch) = stim_ampRatio_ch;
prior_stim_chgRatio(prior_Seizure_Count(i_ch)+(1:Seizure_Count_mf(i_ch)),i_ch) = stim_cghRatio_ch;
end
end
%Update counts for loading in next file (next iteration)
prior_Seizure_Count = prior_Seizure_Count+Seizure_Count_mf;
end
disp('loaded prior data!')
ET_SF = get(handles.ET_SaveFolder,'String');
set(handles.ET_SaveFolder,'String',[ET_SF '_RS']);
else
disp('no prior data loaded')
prior_Seizure_Count = zeros(1,4);
prior_Seizure_Duration = [];
prior_stim_freq = [];
prior_stim_amp = [];
prior_stim_width = [];
prior_stim_ampRatio = [];
prior_stim_chgRatio = [];
end
%% load hierarchical model
%3. Loading hierarchical model if selected
optim_string = get(handles.ET_bayes_or_AB,'String');
global hier_model_settings P_t_g theta_t_g off_set_est
if strcmpi(optim_string,'Hier') == 1
hier_mat_path = get(handles.ET_hier_model_mat,'String');
load(hier_mat_path,'theta_t','P_t','n_setting_combos','n_prior_mice','bins_of_optimized_dims','sigma')
theta_0 = theta_t;
P_0 = P_t;
hier_model_settings.n_setting_combos = n_setting_combos;
hier_model_settings.n_prior_mice = n_prior_mice;
hier_model_settings.bins_of_optimized_dims = bins_of_optimized_dims;
hier_model_settings.sigma = sigma;
clear theta_t P_t
P_t_g = repmat(P_0,1,1,n_ch_out); % replicate P_0 for every mouse
theta_t_g = repmat(theta_0,1,n_ch_out); % theta_t is column vector, replicate it into a matrix for each mouse
global P_orig theta_orig % make a copy of the initial P and theta so that recalculation can be done from scratch if offset changes
P_orig = P_t_g;
theta_orig = theta_t_g;
off_set_est = log(2)*ones(1,n_ch_out);
end
n_ch_out = length(str2num(get(handles.ET_n_ch_out,'String')));
%% create save folder
save_settings(save_folder, 'settings',handles);
n_cams = str2num(get(handles.ET_n_cams,'String'));
if n_cams >0 %launch new matlab to record videos
eval(['!matlab /r n_cams=' num2str(n_cams) ';path=''' save_folder '\' save_name '_vid'';cam_corder&'])
end
% eval(['!matlab /r bo_res_path_base=''' save_folder ''';&']);% ND_load_n_blot_bo_SEP_res& % commenting out for debug
%% setup daq
% 'PCI-6251'
% 'USB-6229 (BNC)'
% 'USB-6221 (BNC)' ?
devices = daq.getDevices;
device_ID_str = get(handles.ET_device_ID,'String');
device_ID_stim = get(handles.ET_stim_dev,'String');
for i = 1:length(devices)
if strcmp(devices(i).Model, device_ID_str)
NI_dev = devices(i);
end
if strcmp(devices(i).Model,device_ID_stim)
stim_dev = devices(i);
end
end
s = daq.createSession('ni');
% s_stim = daq.createSession('ni');
handles.s = s;
% handles.s_stim = s_stim;
global fs_rec
fs_rec = str2num(get(handles.ET_fs,'String'));
% fs_stim = str2num(get(handles.ET_fs_stim,'String'));
s.Rate = fs_rec;
s.IsContinuous = true;
% s_stim.Rate = fs_stim;
% s_stim.IsContinuous = true;
ch_out_vec = str2num(get(handles.ET_n_ch_out,'String'));
n_ch_out = length(ch_out_vec);
for i_ch = 1:n_ch_out
q{1,i_ch} = parallel.pool.PollableDataQueue;
end
% % stim_on_durs = randi(35,10,1);
% % stim_off_durs = randi(35,10,1);
% % for i_ch_out = 1:n_ch_out
% % figure(i_ch_out)
% % subplot(1,2,1)
% % histogram(stim_on_durs,.5:1:100)
% % title('stim')
% % subplot(1,2,2)
% % histogram(stim_off_durs,.5:1:100)
% % title('no stim')
% % end
global stim_remaining
global stim_flag
seizure_detection_ch_vec = str2num(get(handles.ET_seizure_detection_channels,'String'));% detect seizures on ACH0 and ACH2, these are BNC-2090 numbers
if length(seizure_detection_ch_vec) ~= n_ch_out
error('length(seizure_detection_ch_vec) ~= n_ch_out')
end
addAnalogOutputChannel(s, stim_dev.ID, ch_out_vec, 'Voltage');
for i_D_out = 1:length(ch_out_vec)
addDigitalChannel(s,stim_dev.ID,['port0/line' num2str(i_D_out-1)],'OutputOnly');
end
ch_in_vec = str2num(get(handles.ET_n_ch_in,'String')); % hard coded 1 input channel
n_ch_in = length(ch_in_vec);
for i_ch = ch_in_vec % add ephys recording channels
addAnalogInputChannel(s,NI_dev.ID, i_ch, 'Voltage');
end
if or(strcmpi(device_ID_str,'USB-6343 (BNC)'),strcmpi(device_ID_str,'USB-6229 (BNC)'))
for i_D_out = 1:length(ch_out_vec)
addDigitalChannel(s,NI_dev.ID,['port0/line' num2str(i_D_out-1+10)],'InputOnly');
end
elseif or(strcmpi(device_ID_str,'USB-6221 (BNC)'),strcmpi(device_ID_str,'USB-6341 (BNC)'))
for i_D_out = 1:length(ch_out_vec)
addDigitalChannel(s,NI_dev.ID,['port0/line' num2str(i_D_out-1+4)],'InputOnly'); %6341
end
end
%%
%Initialize data structures needed
InitializeVarsInput(n_ch_in,n_ch_out); %Initializes variables used in spike detection and seizure detection
%call global variables that will be needed in the rest of this function
global fast_int slow_int Seizure_On Seizure_Off Seizure_Duration
global spike_count
global spikes_trigger spikes_trigger_stop
global last_spike_time Seizure_Start_First_Spike_Time
global time_out
global in_chunk out_chunk
global ro_data co_data ro_dd co_dd ro_ard co_ard %keep track of row number in output data var
global datatype
global TimeStamp_postfix
fast_slow_ratio_trigger = zeros(1,n_ch_out,'logical');
global next_freq next_amp next_width next_ampRatio next_chgRatio
next_freq = 10*ones(1,n_ch_out); % initialize arbitrarily to 10 Hz
next_amp = 5*ones(1,n_ch_out); % initialize arbitrarily to 1 unit
next_width = 0.150*ones(1,n_ch_out); % initialize arbitrarily to 1 unit
next_ampRatio = 1*ones(1,n_ch_out); % initialize to a 4:1 amplitude ratio
next_chgRatio = 1*ones(1,n_ch_out); % initialize to a 1:1 chg ratio
set(handles.T_NextFreq,'String',num2str(next_freq));
set(handles.T_NextAmp,'String',num2str(next_amp));
set(handles.T_NextWidth,'String',num2str(next_width));
%% initialize matfile
%Data variables get initialized to zeros and saved to file
time=zeros(1,1); %EFF21: time as separate variable
data=zeros(1,n_ch_in+n_ch_out); %EFF21: next n_ch_in columns are the input channels, and the last n_ch_out columns are the output channels
art_rem_data = zeros(1,n_ch_out,datatype); %EFF21
art_rem_data_raw = zeros(1,n_ch_out,datatype); %EFF21
detect_data = zeros(1,n_ch_out,datatype); %EFF21
detect_data_raw = zeros(1,n_ch_out,datatype);%EFF21
ro_data=1; co_data=size(data,2); %Keep track of row we are in
ro_dd=1; co_dd=size(detect_data,2); %Keep track of row we are in
ro_ard=1; co_ard=size(art_rem_data,2); %Keep track of row we are in
%Define extra variables to be stored in the files, to be used for
%identification purposes.
LiveRecording=1; %LiveRecording=0 means offline reanalysis, LiveRecording=1 means new recording
ReferenceDir=''; %This means the _d_ analysis files are in this same directory
ID=save_name; %identifying ID (???for now this is the save_name chosen
SettingsName='settings.mat'; %name of the settings file to be used
TimeStampString=datestr(datetime,'mm-dd-yyyy_HH-MM-SS'); %current time stamps. Included in EVERY file saved.
TimeStamp=now; %Current time and date
TimeStamp_postfix=''; %[' (' TimeStamp ')'];
%Define extra variables so that individual files can store some of the data
%as a safety precaution when the large file gets corrupted.
global last_spike_time_Current Seizure_Start_First_Spike_Time_Current Seizure_Duration_Current stim_Current
last_spike_time_Current = zeros(1,n_ch_out);
Seizure_Start_First_Spike_Time_Current = zeros(1,n_ch_out);
Seizure_Duration_Current = zeros(1,n_ch_out);
stim_Current = zeros(1,5*n_ch_out); %n_ch_out*[freq,amp,width,ampratio,chgratio]
%Create the output files and preload them with variabes to be adjusted
%throughout.
global mf mf2 save_mat_path2_base save_mat_path save_mat_path2
save_mat_path = [save_folder '\' save_name '.mat']
save_mat_path2_base = [save_folder '\' save_name '_d_'] % c
save_mat_path2 = [save_mat_path2_base num2str(d_num) TimeStamp_postfix '.mat'];
save(save_mat_path2,'time','data','art_rem_data','art_rem_data_raw','detect_data','detect_data_raw','fs_rec',...
'ID','TimeStamp','last_spike_time_Current','Seizure_Start_First_Spike_Time_Current','Seizure_Duration_Current','stim_Current','-v7.3','-nocompression')
save(save_mat_path,'fast_int','slow_int','Seizure_Off','stim_flag','Seizure_Duration','spike_count','fast_slow_ratio_trigger','spikes_trigger','spikes_trigger_stop','Seizure_Start_First_Spike_Time','last_spike_time','time_out',...
'LiveRecording','ReferenceDir','ID','SettingsName','TimeStamp','TimeStampString','-v7.3','-nocompression')
%EFF21: No need anymore since I rewrote structure
%spike_count_history = spike_count_history(:,:,1); % remove 3rd dimension
%spike_count_history_raw = spike_count_history_raw(:,:,1); % remove 3rd dimension
%spike_count_history_combined = spike_count_history_combined(:,:,1); % remove 3rd dimension
%We initialized these vars to large size for saving to file, but now
%these can be reduced for internal use, where we only need to save most
%recent 10 rows. 11 is HARDCODED as 1+10
clear data spike_count
mf = matfile(save_mat_path,'Writable',true);
mf2 = matfile(save_mat_path2,'Writable',true);
%% specify optimized variables
% opt_freq = []; % Hz
% opt_amp = []; % Volts?
%% (don't) run the bayes opt and plots one time to get everything compiled, just set the first point
% freqLo_vec = str2num(get(handles.ET_freqLo,'String'));
% freqHi_vec = str2num(get(handles.ET_freqHi,'String'));
% ampLo_vec = str2num(get(handles.ET_ampLo,'String'));
% ampHi_vec = str2num(get(handles.ET_ampHi,'String'));
% % widthLo_vec = str2num(get(handles.ET_widthLo,'String'));
% % widthHi_vec = str2num(get(handles.ET_widthHi,'String'));
% width_vec = str2num(get(handles.ET_widthLo,'String'));
%
% InitialObjective = [15 31 5 52]'; % make up some data
% InitialObjective = log(InitialObjective);
% freq = randi([freqLo_vec(1), freqHi_vec(1)],4,1);
% amp = randi(fix([ampLo_vec(1), ampHi_vec(1)]),4,1);;
% InitialX = table(freq, amp);
%
% for i_ch = 1:n_ch_out
% amp_range = [ampLo_vec(i_ch) ampHi_vec(i_ch)];
% freq_range = [freqLo_vec(i_ch) freqHi_vec(i_ch)];
% opt_amp = Variable('amplitude',amp_range,'Type','integer'); % Volts
% opt_freq = optimizableVariable('frequency',freq_range); % Hz
% parfeval(@BO_wrapper,0,opt_freq, opt_amp, InitialX, InitialObjective, q{1,i_ch});
% end
%
%
% for i_ch_out = 1:n_ch_out
% gotMsg = 0;
% while gotMsg ~= 1
% pause(.1)
% [res, gotMsg] = poll(q{1,i_ch_out}, .02); % should save each res
%
% if gotMsg
% % close all
% % % tic ;% plots are now handled seperately
% % % figure(i_ch_out)
% % % % plot(res,@plotObjectiveModel) % A_BPO_vis, would be good to make these into a video
% % % amp_range = [ampLo_vec(i_ch) ampHi_vec(i_ch)];
% % % freq_range = [freqLo_vec(i_ch) freqHi_vec(i_ch)];
% % % plot_bo(res, freq_range, amp_range, [0 4.5], 35)
% % % toc
%
% % eval(['res_ch_' num2str(i_ch_out) '_sz_' num2str(Seizure_Count(1,i_ch_out)) '= res;'])
% % tic
% % save(save_mat_path,['res_ch_' num2str(i_ch_out) '_sz_' num2str(Seizure_Count(1,i_ch_out))],'-nocompression','-append')
% % toc
%
% next_freq(1,i_ch_out) = res.NextPoint{1,1};
% next_amp(1,i_ch_out) = res.NextPoint{1,2};
% next_width(1,i_ch_out) = res.NextPoint{1,3};
%
% set(handles.T_NextFreq,'String',num2str(next_freq));
% set(handles.T_NextAmp,'String',num2str(next_amp));
% set(handles.T_NextWidth,'String',num2str(next_width));
% end
% end
% end
next_freq(1,:) = 10;
next_amp(1,:) = 5;
next_width(1,:) = 0.1;
next_ampRatio(1,:) = 1;
next_chgRatio(1,:) = 1;
set(handles.T_NextFreq,'String',num2str(next_freq));
set(handles.T_NextAmp,'String',num2str(next_amp));
set(handles.T_NextWidth,'String',num2str(next_width));
set(handles.T_NextAmpRatio,'String',num2str(next_ampRatio));
set(handles.T_NextChgRatio,'String',num2str(next_chgRatio));
%% add listeners
lh1 = addlistener(s,'DataAvailable', @(src, event) Process_Plot_Save(src,event, handles.A_MainPlot,ch_in_vec,seizure_detection_ch_vec,n_ch_in,n_ch_out,save_mat_path, handles) );
lh2 = addlistener(s,'DataRequired', @(src, event) Generate_Stim_Vec(src,event,handles));
lh3 = addlistener(s, 'ErrorOccurred', @(~,event) disp(getReport(event.Error)));
s.NotifyWhenDataAvailableExceeds = fix(fs_rec*in_chunk); % input buffer treshold, hard coded
%CKM: When there is 1s (in_chunk) of data available, use listener lh1 to run Process_Plot
s.NotifyWhenScansQueuedBelow = fix(fs_rec*1.4*out_chunk); % output buffer threshold, hard coded
%CKM: When there is less than 1.4s of data available in the buffer, it will trigger Generate_Stim_Vec using listener lh2
%% buffer 5 seconds of zeros to the daq output to start with, then wait 0.5second
stim_vec_init = zeros(fix(5*fs_rec),n_ch_out*2);
queueOutputData(s, [stim_vec_init]);
pause(0.5);
%% start daq
disp('starting daq')
daq_start_now = now;
daq_start_datetime = datetime;
% startBackground(s_stim);
startBackground(s); % start the daq
%% record daq start time info
[Y,M,D,H,MN,S] = datevec(daq_start_datetime);
daq_date_vector = [Y,M,D,H,MN,S];
save(save_mat_path,'daq_date_vector','daq_start_now','daq_start_datetime','-nocompression','-append')
% handles.vid = vid;
% handles.n_cams = n_cams;
guidata(hObject,handles);
%% --- Executes on button press in PB_Stop: PRESSING THE STOP BUTTON
function PB_Stop_Callback(hObject, eventdata, handles)
% hObject handle to PB_Stop (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global DoSaveToFile
global DoTroubleshoot
if DoTroubleshoot
disp('PB_Stop_Callback...')
end
%CKM: Called when STOP button is pressed.
s = handles.s;
s.stop()
% s_stim = handles.s_stim;
% s_stim.stop()
ch_out_vec = str2num(get(handles.ET_n_ch_out,'String'));
n_ch_out = length(ch_out_vec);
if DoSaveToFile
%Final save to file of all vars that did not yet get updated since last
%switch of data-files.
UpdateFiles(n_ch_out,1);
end
% for i_ch_out = 1:n_ch_out
% saveas(i_ch_out,[handles.save_folder '\figure_' num2str(i_ch_out) '.fig'])
% saveas(i_ch_out,[handles.save_folder '\figure_' num2str(i_ch_out) '.png'])
% end
%Turn off diary if it was running
global DoLog
if DoLog
diary off
end
%% --- Executes when you want to open existing file to check for seizures under current settings
function btn_open_Callback(hObject, eventdata, handles)
%When using this option:
%- data is loaded from file, not from daq
%- it does not save to file any of your data (might later)
global DoStopOffline DoRestartOffline
global DoExisting %1=Load from existing (offline), 0=online
global DoSaveToFile %0=don't save variables to file, 1=save to file
global fs_rec %sampling rate
DoExisting = 1; %1=we do offline run on existing file
DoStopOffline = 0; %1=stop offline analysis after current chunk
DoRestartOffline = 0;%0=load in data for first time, 1=restart same data
DoSaveToFile = 0;
%Ask user to select one or more files
global ReanalysisFolder ReanalysisFiles ReanalysisIndex
[ReanalysisFiles,ReanalysisFolder]=uigetfile('*.mat','MultiSelect','on');
if ~iscell(ReanalysisFiles)
if ReanalysisFiles==0
return
else
ReanalysisFiles={ReanalysisFiles};
ReanalysisIndex=1;
end
end
ReanalysisPath = [ReanalysisFolder ReanalysisFiles{1}];
%Extract necessary input from file1 to obtain some basic info (such as fs)
InputMatfile=matfile(ReanalysisPath);
%Check if time exists as separate variable or is included as first column of data
listOfVariables = who('-file', ReanalysisPath);
TimeIncluded=0+~ismember('time', listOfVariables); % returns true if it is first column
SizeData=size(InputMatfile,'data');
SizeNrChOut=size(InputMatfile,'detect_data');
SizeNrChOut=SizeNrChOut(2)-TimeIncluded; %nr output channels
SizeNrChIn=SizeData(2)-SizeNrChOut-TimeIncluded; %nr input channels
fs_rec=InputMatfile.fs_rec; %sampling rate
%Unhide popup
set(handles.PanelTest,'Visible','on');
%Update parts of GUI to reflect we loaded in data with certain criteria
set(handles.ListOfFiles,'String',ReanalysisFiles);
set(handles.ListOfFiles,'value',1);
set(handles.TextFS,'String',['FS: ' num2str(fs_rec) ' Hz']);
locs=strfind(ReanalysisFolder,'\');
set(handles.TextFN,'String',['Loaded: ' ReanalysisFolder(1:3) '...' ReanalysisFolder(locs(end-1):end) ReanalysisFiles{ReanalysisIndex}]);
set(handles.TextChIn,'String',['#Channels In: ' num2str(SizeNrChIn)]);
set(handles.TextChOut,'String',['#Channels Out: ' num2str(SizeNrChOut)]);
set(handles.InputFileName,'String',[ReanalysisFolder 'Reanalysis']);
%Check if the number of channels specified in settings matches what we
%pulled from the files. if not, show warning
numberin = str2num(get(handles.ET_n_ch_in,'String'));% detect seizures on ACH0 and ACH2, these are BNC-2090 numbers
if length(numberin)~=SizeNrChIn
warndlg('The number of input channels in datafile does not match "ch in vec" in the GUI')
end
n_ch_out = length(str2num(get(handles.ET_n_ch_out,'String')));
if n_ch_out~=SizeNrChOut
warndlg('The number of output channels in datafile does not match "ch out vec" in the GUI')
end
%Disable open button
set(handles.btn_open,'Enable','off');
set(handles.ButtonStart,'Enable','on');
%reset figure
hold(handles.A_MainPlot, 'off')
plot(handles.A_MainPlot,0,0);
hold(handles.A_MainPlot, 'on')
%% --- Initialize variables (called by both online and offline detections)
function InitializeVarsInput(n_ch_in,n_ch_out)
% Contains variables needed for detection of spikes and events
global fs_rec %recording frequency (sampling rate)
global n_read %number of iterations (chunks)
n_read=1;
% Setup how many times the sampling rate it loaded in at a time and set up at a time
global out_chunk in_chunk
out_chunk = 1; % these are very long, 1/2 second would be better, but computation time of bayes opt is too slow to fit inside the loop
in_chunk = 1;
global fast_int slow_int
global Seizure_On Seizure_Off Seizure_Count Seizure_Duration Seizure_Start_Ind