-
Notifications
You must be signed in to change notification settings - Fork 0
/
on_demand_BPO_v2.m
1914 lines (1433 loc) · 68.6 KB
/
on_demand_BPO_v2.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
function varargout = on_demand_BPO_v2(varargin)
% ON_DEMAND_BPO_V2 MATLAB code for on_demand_BPO_v2.fig
% ON_DEMAND_BPO_V2, by itself, creates a new ON_DEMAND_BPO_V2 or raises the existing
% singleton*.
%
% H = ON_DEMAND_BPO_V2 returns the handle to a new ON_DEMAND_BPO_V2 or the handle to
% the existing singleton*.
%
% ON_DEMAND_BPO_V2('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in ON_DEMAND_BPO_V2.M with the given input arguments.
%
% ON_DEMAND_BPO_V2('Property','Value',...) creates a new ON_DEMAND_BPO_V2 or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before on_demand_BPO_v2_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to on_demand_BPO_v2_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 on_demand_BPO_v2
% Last Modified by GUIDE v2.5 28-May-2018 12:59:51
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @on_demand_BPO_v2_OpeningFcn, ...
'gui_OutputFcn', @on_demand_BPO_v2_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 on_demand_BPO_v2 is made visible.
function on_demand_BPO_v2_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 on_demand_BPO_v2 (see VARARGIN)
% Choose default command line output for on_demand_BPO_v2
clc
daqreset
if license('test','image_acquisition_toolbox')
imaqreset
end
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes on_demand_BPO_v2 wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = on_demand_BPO_v2_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;
function ET_load_path_Callback(hObject, eventdata, handles)
% hObject handle to ET_load_path (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of ET_load_path as text
% str2double(get(hObject,'String')) returns contents of ET_load_path as a double
% --- Executes during object creation, after setting all properties.
function ET_load_path_CreateFcn(hObject, eventdata, handles)
% hObject handle to ET_load_path (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes during object creation, after setting all properties.
function ET_min_width_CreateFcn(hObject, eventdata, handles)
% hObject handle to ET_load_path (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes during object creation, after setting all properties.
function ET_min_spikes_per_two_s_CreateFcn(hObject, eventdata, handles)
% hObject handle to ET_load_path (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in PB_LoadSettings.
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)
load(get(handles.ET_load_path,'String'));
try
set(handles.ET_spike_dist_pos,'String',struc.ET_spike_dist_pos);
end
try
set(handles.ET_spike_dist_neg,'String',struc.ET_spike_dist_neg);
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.t_thresh,'String',struc.ET_threshold_neg);
end
try
set(handles.T_min_width,'String',struc.ET_min_width);
end
try
set(handles.T_min_spikes_per_two_s,'String',struc.ET_min_spikes_per_two_s);
end
try
set(handles.ET_open_loop,'String',struc.ET_open_loop);
end
try
set(handles.ET_high_pass_filter,'String',struc.ET_high_pass_filter);
end
try
set(handles.ET_low_pass_filter,'String',struc.ET_low_pass_filter);
end
try
set(handles.ET_fast_slow_ratio_thresh,'String',struc.ET_fast_slow_ratio_thresh);
end
try
set(handles.ET_G_fast,'String',struc.ET_G_fast);
end
try
set(handles.ET_G_slow,'String',struc.ET_G_slow);
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_AmplitudeRange,'String',struc.ET_AmplitudeRange);
end
try
set(handles.ET_PulseWidthRange,'String',struc.ET_PulseWidthRange);
end
try
set(handles.ET_FrequencyRange,'String',struc.ET_FrequencyRange);
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_stim_scaling,'String',struc.ET_stim_scaling);
end
guidata(hObject,handles);
function ET_save_path_Callback(hObject, eventdata, handles)
% hObject handle to ET_save_path (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of ET_save_path as text
% str2double(get(hObject,'String')) returns contents of ET_save_path as a double
% --- Executes during object creation, after setting all properties.
function ET_save_path_CreateFcn(hObject, eventdata, handles)
% hObject handle to ET_save_path (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function save_settings(path, 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)
struc.ET_open_loop=get(handles.ET_open_loop,'String');
struc.ET_high_pass_filter=get(handles.ET_high_pass_filter,'String');
struc.ET_low_pass_filter=get(handles.ET_low_pass_filter,'String');
struc.ET_fast_slow_ratio_thresh=get(handles.ET_fast_slow_ratio_thresh,'String');
struc.ET_G_fast=get(handles.ET_G_fast,'String');
struc.ET_G_slow=get(handles.ET_G_slow,'String');
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_AmplitudeRange=get(handles.ET_AmplitudeRange,'String');
struc.ET_PulseWidthRange=get(handles.ET_PulseWidthRange,'String');
struc.ET_FrequencyRange=get(handles.ET_FrequencyRange,'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_pos=get(handles.ET_spike_dist_pos,'String');
struc.ET_spike_dist_neg=get(handles.ET_spike_dist_neg,'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.t_thresh,'String');
struc.ET_min_width=get(handles.T_min_width,'String');
struc.ET_min_spikes_per_two_s=get(handles.T_min_spikes_per_two_s,'String');
struc.ET_stim_scaling=get(handles.ET_stim_scaling,'String');
save([path '\settings.mat'], 'struc');
% --- Executes on button press in PB_Go.
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)
daqreset
if license('test','image_acquisition_toolbox')
imaqreset
end
rng(17);
%%
global q
p = gcp();
q{1,1} = parallel.pool.PollableDataQueue;
q{1,2} = parallel.pool.PollableDataQueue;
%% create save folder
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];
if not(exist(save_folder,'dir'))
mkdir(save_folder)
else
warning('folder already exists')
end
save_settings(save_folder, handles);
%% setup video cameras
n_cams = str2num(get(handles.ET_n_cams,'String'));
if license('test','image_acquisition_toolbox')
[vid, src] = setup_video(n_cams);
else
vid = [];
src = [];
end
%% setup daq
devices = daq.getDevices;
if length(devices) == 1 % behavior computer
PCI_6251_dev = devices(1);
else
for i = 1:length(devices)
if strcmp(devices(i).Model,'PCI-6251')
PCI_6251_dev = devices(i);
end
if strcmp(devices(i).Model,'USB-6229 (BNC)')
USB_6229_dev = devices(i);
end
end
end
s = daq.createSession('ni');
global fs
fs = str2num(get(handles.ET_fs,'String'));
dt = 1/fs;
s.Rate = fs;
s.IsContinuous = true;
global out_chunk in_chunk
out_chunk = 0.5; % 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;
n_ch_out = str2num(get(handles.ET_n_ch_out,'String'));
for i_ch_out = 1:n_ch_out
figure(i_ch_out) % do this early so that it doesn't slow things later
end
global stim_remaining
stim_remaining = zeros(1,n_ch_out);
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, PCI_6251_dev.ID, (1:n_ch_out)-1, 'Voltage');
global stim_flag
stim_flag = zeros(1, n_ch_out,'logical');
n_ch_in = str2num(get(handles.ET_n_ch_in,'String')); % hard coded 1 input channel
for i_ch = 1:n_ch_in % add ephys recording channels
if length(devices) == 1
ch(i_ch) = addAnalogInputChannel(s,PCI_6251_dev.ID, i_ch-1+4, 'Voltage');
else
ch(i_ch) = addAnalogInputChannel(s,PCI_6251_dev.ID, i_ch-1, 'Voltage');
end
end
%%
%%
global n_read fast_int slow_int Seizure_On Seizure_Off Seizure_Count Seizure_Duration stim_amp stim_freq Seizure_Start_Ind next_freq next_amp spike_count_history
global duration_amp_freq
n_read = 1;
fast_int = zeros(1,n_ch_out);
slow_int = zeros(1,n_ch_out);
Seizure_On = zeros(1,n_ch_out);
Seizure_Off = zeros(1,n_ch_out);
Seizure_Count = zeros(1,n_ch_out);
Seizure_Duration = zeros(1,n_ch_out);
Seizure_Start_Ind = zeros(1,n_ch_out);
duration_amp_freq = zeros(1,3*n_ch_out);
global pos_spike_count neg_spike_count
pos_spike_count = zeros(1,n_ch_out);
neg_spike_count = zeros(1,n_ch_out);
spike_count_history = zeros(fix(2*1/in_chunk),n_ch_out,2); % giving it an extra dimension to initialize the file
fast_slow_ratio_trigger = zeros(1,n_ch_out,'logical');
spikes_trigger(n_read,:) = zeros(1,n_ch_out,'logical');
next_freq = 10*ones(1,n_ch_out); % initialize arbitrarily to 10 Hz
next_amp = 1*ones(1,n_ch_out); % initialize arbitrarily to 1 unit
set(handles.T_NextFreq,'String',num2str(next_freq));
set(handles.T_NextAmp,'String',num2str(next_amp));
%% initialize matfile
data=zeros(1,1+n_ch_in); % column 1 is time stamps, next n_ch_in columns are the input channels, and the last n_ch_out columns are the output channels
detect_data = zeros(1,1+n_ch_out);
save_mat_path = [save_folder '\' save_name '.mat']
save(save_mat_path,'data','detect_data','fs','-v7.3','-nocompression')
for i_cam = 1:n_cams
eval(['time_cam_' num2str(i_cam) ' = 0;'])
eval(['meta_time_cam_' num2str(i_cam) ' = zeros(1,9);'])
end
for i_cam = 1:n_cams
save(save_mat_path,['time_cam_' num2str(i_cam)],'-nocompression','-append')
save(save_mat_path,['meta_time_cam_' num2str(i_cam)],'-nocompression','-append')
end
save(save_mat_path,'fast_int','slow_int','Seizure_On','Seizure_Off','stim_flag','Seizure_Duration','spike_count_history','fast_slow_ratio_trigger','spikes_trigger','-nocompression','-append')
spike_count_history = zeros(fix(2*1/in_chunk),n_ch_out); % removing extra dimension
clear data
mf = matfile(save_mat_path,'Writable',true);
%% specify optimized variables
opt_freq = optimizableVariable('frequency',str2num(get(handles.ET_FrequencyRange,'String'))); % Hz
opt_amp = optimizableVariable('amplitude',str2num(get(handles.ET_AmplitudeRange,'String'))); % Volts?
%% run the bayes opt and plots one time to get everything compiled
InitialObjective = [1 1 1]';
freq = [1, 5, 100]';
amp = [-1, 3, -10]';
InitialX = table(freq, amp);
parfeval(@BO_wrapper,0,opt_freq, opt_amp, InitialX, InitialObjective, q{1,1});
parfeval(@BO_wrapper,0,opt_freq, opt_amp, InitialX, InitialObjective, q{1,2});
for i_ch_out = 1:n_ch_out
gotMsg = 0;
while gotMsg ~= 1
pause(.1)
[res, gotMsg] = poll(q{1,i_ch_out}, .05); % should save each res
% gotMsg=gotMsg
if gotMsg
% close all
tic
figure(i_ch_out)
% plot(res,@plotObjectiveModel) % A_BPO_vis, would be good to make these into a video
range1 = str2num(get(handles.ET_FrequencyRange,'String'));
range2 = str2num(get(handles.ET_AmplitudeRange,'String'));
plot_bo(res, range1, range2, [0 40], 15)
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};
set(handles.T_NextFreq,'String',num2str(next_freq));
set(handles.T_NextAmp,'String',num2str(next_amp));
end
end
end
%% add listeners
lh1 = addlistener(s,'DataAvailable', @(src, event) Process_Plot_Save(src,event,mf, handles.A_MainPlot,n_cams,vid,seizure_detection_ch_vec,n_ch_out,opt_freq,opt_amp, p, save_mat_path, handles) );
lh2 = addlistener(s,'DataRequired', @(src, event) Generate_Stim_Vec(src,event,handles));
s.NotifyWhenDataAvailableExceeds = fix(fs*in_chunk); % input buffer treshold, hard coded
s.NotifyWhenScansQueuedBelow = fix(fs*out_chunk); % output buffer threshold, hard coded
% s.NotifyWhenDataAvailableExceeds = fix(fs/5); % input buffer treshold, hard coded
% s.NotifyWhenScansQueuedBelow = fix(fs/6); % output buffer threshold, hard coded
handles.s = s;
%% buffer 2 seconds of zeros to the daq output to start with
stim_vec_init = zeros(fix(5*fs),n_ch_out);
queueOutputData(s, [stim_vec_init]);
%% setup video save_file and start the video
for i_cam = 1:n_cams
logfile(i_cam) = VideoWriter([save_folder '\' save_name '_cam_' num2str(i_cam) '.mp4'], 'MPEG-4');
logfile(i_cam).FrameRate = 30;
vid(i_cam).DiskLogger = logfile(i_cam);
start(vid(i_cam))
end
%% trigger cameras to start
pause(.1)
disp('starting cam')
for i_cam = 1:n_cams
trigger(vid(i_cam))
end
pause(0.6)
%% start daq
disp('starting daq')
daq_start_now = now;
daq_start_datetime = datetime;
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.
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)
s = handles.s;
s.stop()
vid = handles.vid;
n_cams = handles.n_cams;
%% stop video
for i_cam = 1:n_cams
stop(vid(i_cam));
end
for i_cam = 1:n_cams
numAvail(i_cam) = vid(i_cam).FramesAvailable;
[~, time{i_cam,1}, metadata] = getdata(vid(i_cam),numAvail(i_cam));
end
% save([save_folder '\' 'video_time_train_' num2str(i_train) '_' date_stamp '.mat' '.mat'],'time','rep_start_time','rep_start_now', 'metadata','-v7.3')
clear time numAvail
function ET_fs_Callback(hObject, eventdata, handles)
% hObject handle to ET_fs (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of ET_fs as text
% str2double(get(hObject,'String')) returns contents of ET_fs as a double
% --- Executes during object creation, after setting all properties.
function ET_fs_CreateFcn(hObject, eventdata, handles)
% hObject handle to ET_fs (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function ET_AmplitudeRange_Callback(hObject, eventdata, handles)
% hObject handle to ET_AmplitudeRange (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of ET_AmplitudeRange as text
% str2double(get(hObject,'String')) returns contents of ET_AmplitudeRange as a double
% --- Executes during object creation, after setting all properties.
function ET_AmplitudeRange_CreateFcn(hObject, eventdata, handles)
% hObject handle to ET_AmplitudeRange (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function ET_PulseWidthRange_Callback(hObject, eventdata, handles)
% hObject handle to ET_PulseWidthRange (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of ET_PulseWidthRange as text
% str2double(get(hObject,'String')) returns contents of ET_PulseWidthRange as a double
% --- Executes during object creation, after setting all properties.
function ET_PulseWidthRange_CreateFcn(hObject, eventdata, handles)
% hObject handle to ET_PulseWidthRange (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function ET_MonoOrBiPhasic_Callback(hObject, eventdata, handles)
% hObject handle to ET_MonoOrBiPhasic (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of ET_MonoOrBiPhasic as text
% str2double(get(hObject,'String')) returns contents of ET_MonoOrBiPhasic as a double
% --- Executes during object creation, after setting all properties.
function ET_MonoOrBiPhasic_CreateFcn(hObject, eventdata, handles)
% hObject handle to ET_MonoOrBiPhasic (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function ET_FrequencyRange_Callback(hObject, eventdata, handles)
% hObject handle to ET_FrequencyRange (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of ET_FrequencyRange as text
% str2double(get(hObject,'String')) returns contents of ET_FrequencyRange as a double
% --- Executes during object creation, after setting all properties.
function ET_FrequencyRange_CreateFcn(hObject, eventdata, handles)
% hObject handle to ET_FrequencyRange (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function ET_TrainDuration_Callback(hObject, eventdata, handles)
% hObject handle to ET_TrainDuration (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of ET_TrainDuration as text
% str2double(get(hObject,'String')) returns contents of ET_TrainDuration as a double
% --- Executes during object creation, after setting all properties.
function ET_TrainDuration_CreateFcn(hObject, eventdata, handles)
% hObject handle to ET_TrainDuration (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function ET_SaveFolder_Callback(hObject, eventdata, handles)
% hObject handle to ET_SaveFolder (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of ET_SaveFolder as text
% str2double(get(hObject,'String')) returns contents of ET_SaveFolder as a double
% --- Executes during object creation, after setting all properties.
function ET_SaveFolder_CreateFcn(hObject, eventdata, handles)
% hObject handle to ET_SaveFolder (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function ET_SaveName_Callback(hObject, eventdata, handles)
% hObject handle to ET_SaveName (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of ET_SaveName as text
% str2double(get(hObject,'String')) returns contents of ET_SaveName as a double
% --- Executes during object creation, after setting all properties.
function ET_SaveName_CreateFcn(hObject, eventdata, handles)
% hObject handle to ET_SaveName (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function [vid, src] = setup_video(n_cams)
%% setup video
low_res_flag = 1;
dev_info = imaqhwinfo('winvideo');
default_format = dev_info.DeviceInfo(1).DefaultFormat;
if strcmp(default_format,'MJPG_1024x576') == 1
behavior_computer_flag = 0;
elseif strcmp(default_format,'RGB24_640x480') == 1
behavior_computer_flag = 1
else
error('unrecognized winvideo video format')
end
for i_cam = 1:n_cams
if low_res_flag == 1
if behavior_computer_flag == 1
vid(i_cam) = videoinput('winvideo', i_cam, 'RGB24_320x240'); % could use 640x480
else
vid(i_cam) = videoinput('winvideo', i_cam, 'MJPG_320x240'); % could use 640x480
end
else
if behavior_computer_flag == 1
vid(i_cam) = videoinput('winvideo', i_cam, 'RGB24_640x480'); % could use 640x480
else
vid(i_cam) = videoinput('winvideo', i_cam, 'MJPG_640x480'); % could use 640x480
end
end
src(i_cam) = getselectedsource(vid(i_cam));
src(i_cam).BacklightCompensation = 'on';
src(i_cam).ExposureMode='manual';
src(i_cam).Exposure = -6;
preview(vid(i_cam))
end
choice = menu('Preview Control','End preview and continue');
for i_cam = 1:n_cams
closepreview(vid(i_cam))
end
for i_cam = 1:n_cams
vid(i_cam).LoggingMode = 'disk&memory';
vid(i_cam).FramesPerTrigger = Inf;
triggerconfig(vid(i_cam), 'manual')
end
if n_cams == 0
vid = [];
src = [];
end
function Process_Plot_Save(src,event,mf,plot_handle,n_cams,vid, seizure_detection_ch_vec, n_ch_out,opt_freq,opt_amp, p, save_mat_path, handles)
% disp('Process_Plot_Save')
global stim_flag
global duration_amp_freq
global q
global n_read fast_int slow_int Seizure_On Seizure_Off Seizure_Count Seizure_Duration stim_amp stim_freq Seizure_Start_Ind next_freq next_amp
global in_chunk spike_count_history
global pos_spike_count neg_spike_count
n_read = n_read+1;
%% log the frame timestamps
for i_cam = 1:n_cams
numAvail(i_cam) = vid(i_cam).FramesAvailable;
[~, time{i_cam,1}, metadata] = getdata(vid(i_cam),numAvail(i_cam));
[ro_frame, ~] = size(mf,['time_cam_' num2str(i_cam)]);
[ro_frame_meta, ~] = size(mf,['meta_time_cam_' num2str(i_cam)]);
n_new_frames = size(time{i_cam,1},1);
meta_mat = table2array(struct2table(metadata));
n_new_frames_meta = size(meta_mat,1);
if ro_frame ~= ro_frame_meta
warning('ro_frame ~= ro_frame_meta')
end
if n_new_frames ~= n_new_frames_meta
warning('n_new_frames ~= n_new_frames_meta')
end
eval(['mf.time_cam_' num2str(i_cam) '(ro_frame+(1:n_new_frames),1) = time{i_cam,1};'])
eval(['mf.meta_time_cam_' num2str(i_cam) '(ro_frame_meta+(1:n_new_frames),:) = meta_mat;'])
end
%% plot decimated data
deci = 1;
% MainPlot_handle = findobj('Tag', 'A_MainPlot');
data_deci = event.Data(1:deci:end,:);
time_deci = event.TimeStamps(1:deci:end);
n_t_deci = length(time_deci);
n_ch = size(data_deci,2);
channel_spacing = str2double(get(handles.ET_channel_spacing,'String'));;
plot(plot_handle, time_deci, data_deci+repmat(channel_spacing*(1:n_ch), n_t_deci,1))
hold(plot_handle, 'on')
ylim(plot_handle,[0 channel_spacing*(n_ch+1)])
%% save raw data
data = event.Data;
[ro, co] = size(mf,'data');
[r, c] = size(event.Data);
if co~=c+1
error('data dims not equal in columns')
end
mf.data(ro+(1:r), :) = [event.TimeStamps event.Data];
%% seizure detection code
% decimate and remove mean
fs = str2double(get(handles.ET_fs,'String'));
detect_deci = fix(fs/1000);
if n_read == 2
mf.detect_deci = detect_deci;
end
fs_deci = fs/detect_deci;
dt_deci = 1/fs_deci;
detect_data = event.Data(1:detect_deci:end,seizure_detection_ch_vec+1); % select channels and decimate
detect_data = detect_data - repmat(mean(detect_data,1), size(detect_data,1),1); % remove mean
n_t_detect_deci = size(detect_data,1);
detect_time_deci = event.TimeStamps(1:detect_deci:end);
%% filter data
hp_f_vec = str2num(get(handles.ET_high_pass_filter,'String'));
lp_f_vec = str2num(get(handles.ET_low_pass_filter,'String'));
for i_ch = 1:n_ch_out
hp_f = hp_f_vec(i_ch);
lp_f = lp_f_vec(i_ch);
if hp_f ~= 0
[bH,aH] = butter(3,hp_f/(fs_deci/2),'high');
detect_data(:,i_ch) = filtfilt(bH,aH,detect_data(:,i_ch));
end
if lp_f ~= 0
[bL,aL] = butter(3,lp_f/(fs_deci/2),'low');
detect_data(:,i_ch) = filtfilt(bL,aL,detect_data(:,i_ch));
end
end
plot(plot_handle, detect_time_deci, detect_data+repmat(channel_spacing*(seizure_detection_ch_vec+1), n_t_detect_deci,1))
%% save decimated and filtered data
[ro, co] = size(mf,'detect_data');
[r, c] = size(detect_data);
mf.detect_data(ro+(1:r), :) = [detect_time_deci detect_data];
%% fast/slow stdev detector
detect_data_std = std(detect_data,0,1);
G_fast = str2num(get(handles.ET_G_fast,'String'));
G_slow = str2num(get(handles.ET_G_slow,'String'));
if n_read == 2
fast_int(1,:) = detect_data_std;
slow_int(1,:) = detect_data_std;
mf.fast_int(1,:) = fast_int(1,:);
mf.slow_int(1,:) = slow_int(1,:);
end
fast_int(n_read,:) = (1-G_fast).*detect_data_std + G_fast.*fast_int(n_read-1,:);
slow_int(n_read,:) = (1-G_slow).*detect_data_std + G_slow.*slow_int(n_read-1,:);
mf.fast_int(n_read,:) = fast_int(n_read,:);
mf.slow_int(n_read,:) = slow_int(n_read,:);
disp('.............')
disp('.............')
disp(['fast std = ' num2str(fast_int(n_read,:))])
disp(['slow std = ' num2str(slow_int(n_read,:))])
fast_slow_ratio_thresh = str2num(get(handles.ET_fast_slow_ratio_thresh,'String'));
fast_slow_ratio = fast_int(n_read,:)./slow_int(n_read,:);
disp(['fast/slow ratio = ' num2str(fast_slow_ratio)])
fast_slow_ratio_trigger = fast_slow_ratio > fast_slow_ratio_thresh;
mf.fast_slow_ratio_trigger(n_read,:) = fast_slow_ratio_trigger;
%% spike analysis
dist_pos_vec = str2num(get(handles.ET_spike_dist_pos,'String')); % ms?
dist_neg_vec = str2num(get(handles.ET_spike_dist_neg,'String')); % ms?
SpikesUpper_vec = str2num(get(handles.ET_threshold_pos,'String')); % SD?
SpikesLower_vec = str2num(get(handles.ET_threshold_neg,'String')); % SD?
ht_perc_vec = str2num(get(handles.ET_width_at_percent_height,'String')); %Width of a spike is determined at specified height of spikes (fraction)
req_width_vec = str2num(get(handles.ET_min_width,'String')); %Spike is considered wide if width exceeds this threshold (in s)
DoDisplay = 0;
spike_count_history = circshift(spike_count_history,-1); % shift values
for i_ch = 1:n_ch_out
Settings.dist_pos = dist_pos_vec(i_ch);
Settings.dist_neg = dist_neg_vec(i_ch);
Settings.SpikesUpper = SpikesUpper_vec(i_ch);
Settings.SpikesLower = SpikesLower_vec(i_ch);
Settings.ht_perc = ht_perc_vec(i_ch);
Settings.req_width = req_width_vec(i_ch);
[posspikes,negspikes,posspikes_narrow,negspikes_narrow,posspikes_wide,negspikes_wide]=SpikeFinder(detect_data(:,i_ch),fs_deci,Settings,DoDisplay);
n_spikes_this_chunk = size(negspikes_wide,1)+size(posspikes_wide,1);
spike_count_history(end,i_ch) = n_spikes_this_chunk;
if not(isempty(posspikes_wide))
pos_spike_times = detect_time_deci(posspikes_wide(:,1));
pos_spike_val = posspikes_wide(:,2);
n_pos_spike(1,i_ch) = length(pos_spike_times);
mf.pos_spike_times(pos_spike_count(1,i_ch)+(1:n_pos_spike(1,i_ch)),i_ch) = pos_spike_times;
mf.pos_spike_val(pos_spike_count(1,i_ch)+(1:n_pos_spike(1,i_ch)),i_ch) = pos_spike_val;
pos_spike_count(1,i_ch) = pos_spike_count(1,i_ch) + n_pos_spike(1,i_ch);
end
if not(isempty(negspikes_wide))
neg_spike_times = detect_time_deci(negspikes_wide(:,1));
neg_spike_val = negspikes_wide(:,2);
n_neg_spike(1,i_ch) = length(neg_spike_times);
mf.neg_spike_times(neg_spike_count(1,i_ch)+(1:n_neg_spike(1,i_ch)),i_ch) = neg_spike_times;
mf.neg_spike_val(neg_spike_count(1,i_ch)+(1:n_neg_spike(1,i_ch)),i_ch) = neg_spike_val;
neg_spike_count(1,i_ch) = neg_spike_count(1,i_ch) + n_neg_spike(1,i_ch);
end
if size(posspikes_wide,1)>0
plot(plot_handle, detect_time_deci(posspikes_wide(:,1)),channel_spacing*(seizure_detection_ch_vec(i_ch)+1)+posspikes_wide(:,2),'*r')
end
if size(negspikes_wide,1)>0
plot(plot_handle, detect_time_deci(negspikes_wide(:,1)),channel_spacing*(seizure_detection_ch_vec(i_ch)+1)+negspikes_wide(:,2),'*r')
end
end
hold(plot_handle, 'off')