-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOperantController.m
More file actions
1748 lines (1301 loc) · 53.8 KB
/
OperantController.m
File metadata and controls
1748 lines (1301 loc) · 53.8 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
function varargout = OperantController(varargin)
% OPERANTCONTROLLER MATLAB code for OperantController.fig
% OPERANTCONTROLLER, by itself, creates a new OPERANTCONTROLLER or raises the existing
% singleton*.
%
% H = OPERANTCONTROLLER returns the handle to a new OPERANTCONTROLLER or the handle to
% the existing singleton*.
%
% OPERANTCONTROLLER('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in OPERANTCONTROLLER.M with the given input arguments.
%
% OPERANTCONTROLLER('Property','Value',...) creates a new OPERANTCONTROLLER or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before OperantController_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to OperantController_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 OperantController
% Last Modified by GUIDE v2.5 13-Jun-2018 16:27:31
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @OperantController_OpeningFcn, ...
'gui_OutputFcn', @OperantController_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 OperantController is made visible.
function OperantController_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 OperantController (see VARARGIN)
current_date = datestr(now,'mmm-dd-yyyy_HH-MM-SS');
handles.current_date = current_date;
handles.test_day.String = current_date;
drawnow;
%
set(handles.image_feed,'XTickLabel',{});
set(handles.image_feed,'XTick',[]);
set(handles.image_feed,'YTick',[]);
set(handles.image_feed,'YTickLabel',{});
set(handles.image_feed,'Box','on');
offset = 720/2;
start_pos = offset/2;
image_height = 480;
right_pos = [offset+start_pos 0 offset+start_pos image_height];
left_pos = [start_pos 0 start_pos image_height];
handles.line_matrix = [left_pos; right_pos];
handles.image_height = image_height;
set(handles.left_slider,'Value',start_pos);
set(handles.left_slider,'Min',0);
set(handles.left_slider,'Max',offset);
set(handles.right_slider,'Value',offset+start_pos);
set(handles.right_slider,'Min',offset);
set(handles.right_slider,'Max',offset*2);
guidata(hObject,handles);
drawnow;
%
protocol_types = {'Training','Baseline','Tinnitus','Other'};
set(handles.proto_type,'String',protocol_types);
set(handles.proto_type,'Value',1);
drawnow;
% Lab specific, computer specific information
shore_comps = {'khri-jim','khri-305971'};
altshuler_comps = {'khri-314461','khri-314463',...
'khri-314464','khri-314465','khri-314466'};
%computer specific items
[~,name] = system('hostname');
name(end) = [];
name = lower(name);
handles.computer_name = name;
set(handles.comp_name,'String',sprintf('Computer: %s',name));
drawnow;
config_email();
%needed to send email to users
if ismember(name,shore_comps)
handles.user_email_addr = 'damartel@umich.edu';
home_server = '\\maize.umhsnas.med.umich.edu\khri-ses-lab\Applications';
video_construct = {'pointgrey', 1, 'F7_BayerRG8_752x480_Mode0'};
elseif ismember(name,altshuler_comps)
handles.user_email_addr = 'shuler@umich.edu';
home_server = '\\maize.umhsnas.med.umich.edu\khri-alt-lab\Applications';
video_construct = {'pointgrey', 1, 'F7_BayerRG8_752x480_Mode0'};
else
handles.user_email_addr = 'the.khri.email@gmail.com';
home_server = '';
end
handles.video_construct = video_construct;
guidata(hObject, handles);
drawnow;
%phone home to see if main data store is present, and do version checking
if ~exist(home_server,'dir')
uiwait(msgbox('Warning: home server not found.'));
else
version_check = load(fullfile(home_server,'OC_Version.mat'));
version_check = version_check.version_check;
end
version_runtime = 0.9;
if version_runtime ~= version_check
uiwait(msgbox('Warning: Newer code available. Please install.'));
end
% folder for data, getting required files
base_dir = 'C:\OperantSetup\';
if ~exist(base_dir,'dir')
mkdir(base_dir);
end
handles.base_dir = base_dir;
%calibration file
calib_folder = fullfile(base_dir,'Calibration_Data');
if ~exist(calib_folder,'dir')
mkdir(calib_folder);
end
calib_data_file = fullfile(calib_folder,'noise_spec.mat');%['calibration_data_' name '.xlsx']
handles.calib_file = calib_data_file;
if ~exist(handles.calib_file,'file')
uiwait(msgbox('Get calibration data before running program'));
end
%data storage location
data_dir_def = fullfile(base_dir,'Data');
if ~exist(data_dir_def,'dir')
mkdir(data_dir_def);
end
handles.save_dir_str.String = sprintf('Save Dir: %s',data_dir_def);
handles.save_dir = data_dir_def;
guidata(hObject, handles);
%animal color model
color_dir = 'Color_Data';
color_save = fullfile(base_dir,color_dir);
if ~exist(color_save,'dir')
mkdir(color_save);
end
handles.color_save = color_save;
guidata(hObject, handles);
%default saving behavior is to save protocol data and not video data
handles.save_proto_data.Value = 1;
handles.save_vid_data.Value = 0;
handles.no_acclim.Value = 1;
%update strigns
handles.shock_str.String = 'SHOCK DISABLED';
handles.shock_str.ForegroundColor = [0 0 1]; %blue
handles.sound_str.String = 'SOUND DISABLED';
handles.shock_str.ForegroundColor = [0 1 1]; %green
%testing parameters
handles.tracking = false;
handles.animal_name = 'Animal 1';
handles.prev_trial_str = [];
handles.protocol_type = 'Training';
%run parameters
handles.left_pos = [];
handles.right_pos = [];
handles.proto_state = 'acclim'; %holding, waiting, freezing, sound, shock, silence
handles.crossings = 0;
handles.boundary = [];
handles.tracking = false;
handles.image = [];
%% Configure hardware
handles.SHOCK_STATE = false;
handles.current_lev = 1.21; %default from GP experiments
[hObject,handles] = config_shocker(hObject, handles);
handles.SOUND_STATE = false;
handles.SILENCE_TRIALS = false;
%Configure camera
[hObject,handles] = config_camera(hObject, handles);
% Update handles structure
guidata(hObject, handles);
%Configure sound
[hObject,handles] = config_sound(hObject,handles);
% handles.vid_timer = timer(...
% 'ExecutionMode','fixedRate',...
% 'Period',1/20,...
% 'StartDelay',1); %,...
% handles.vid_timer.TimerFcn= @(~,~)update_image(hObject,handles);
% Choose default command line output for OperantController
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes OperantController wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = OperantController_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)
% vid = handles.vid;
% close(vid);
% delete(vid);
% clear vid handles.vid;
% Get default command line output from handles structure
varargout{1} = handles.output;
%% Input box handling functions
function config_email()
shore_lab = 'the.khri.email@gmail.com';
shore_lab_pass = 'rwaawkldjgaauslq';
setpref('Internet','SMTP_Server','smtp.gmail.com');
setpref('Internet','E_mail',shore_lab);
setpref('Internet','SMTP_Username',shore_lab);
setpref('Internet','SMTP_Password',shore_lab_pass);
props = java.lang.System.getProperties;
props.setProperty('mail.smtp.auth','true');
props.setProperty('mail.smtp.socketFactory.class', 'javax.net.ssl.SSLSocketFactory');
props.setProperty('mail.smtp.socketFactory.port','465');
drawnow;
function success = animal_name_test(animal_name)
%test for bad characters in animal name
bad_chars = {':','\','/','#','%','&','{','}','<','>','*',...
'?',' ','$','!','~','@','_','-','+','=','(',')'};
if any(contains(animal_name,bad_chars))
uiwait(msgbox(['Animal name cannot contain these characters: '...
strcat(bad_chars)]));
success = 0;
else
success = 1;
end
function [hObject,handles] = make_animal_dir(hObject,handles,animal_name)
save_dir = handles.save_dir;
save_dir = fullfile(save_dir,animal_name);
if ~exist(save_dir,'dir')
uiwait(msgbox('New animal folder being made'));
mkdir(save_dir);
end
handles.save_dir = save_dir;
handles.save_dir_str.String = sprintf('Save data dir: %s',save_dir);
guidata(hObject,handles);
drawnow;
function ani_name_Callback(hObject, eventdata, handles)
% hObject handle to ani_name (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 ani_name as text
% str2double(get(hObject,'String')) returns contents of ani_name as a double
ani_name = get(handles.ani_name,'String');
if animal_name_test(ani_name)
[hObject,handles] = make_animal_dir(hObject,handles,ani_name);
handles.animal_name = ani_name;
[hObject,handles] = get_color_model_Callback(hObject, [], handles);
%handles.get_color_model.Enable = 'off';
else
set(handles.ani_name,'String','Animal 1')
set(handles.ani_name,'UserData','Animal 1')
end
% Choose default command line output for GD_Protocol_Simulink
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% --- Executes during object creation, after setting all properties.
function ani_name_CreateFcn(hObject, eventdata, handles)
% hObject handle to ani_name (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 save_proto_data.
function save_proto_data_Callback(hObject, eventdata, handles)
% hObject handle to save_proto_data (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
value = get(hObject,'Value'); % returns toggle state of save_proto_data
if value
handles.save_proto_data.Value = 1;
else
handles.save_proto_data.Value = 0;
end
guidata(hObject,handles);
drawnow;
% --- Executes on button press in save_vid_data.
function save_vid_data_Callback(hObject, eventdata, handles)
% hObject handle to save_vid_data (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
value = get(hObject,'Value'); % returns toggle state of save_vid_data
if value
handles.save_vid_data.Value = 1;
else
handles.save_vid_data.Value = 0;
end
guidata(hObject,handles);
drawnow;
% --- Executes on selection change in proto_type.
function proto_type_Callback(hObject, eventdata, handles)
% hObject handle to proto_type (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
contents = cellstr(get(hObject,'String')); % returns proto_type contents as cell array
proto_type = contents{get(hObject,'Value')}; % returns selected item from proto_type
handles.protocol_type = proto_type;
silence_types = {'Baseline','Tinnitus'};
if ismember(proto_type,silence_types)
handles.SILENCE_TRIALS = true;
else
handles.SILENCE_TRIALS = false;
end
guidata(hObject,handles);
% --- Executes during object creation, after setting all properties.
function proto_type_CreateFcn(hObject, eventdata, handles)
% hObject handle to proto_type (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox 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 test_day_Callback(hObject, eventdata, handles)
% hObject handle to test_day (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 test_day as text
% str2double(get(hObject,'String')) returns contents of test_day as a double
% --- Executes during object creation, after setting all properties.
function test_day_CreateFcn(hObject, eventdata, handles)
% hObject handle to test_day (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 success = valid_email(email)
success = 0;
email_attr = {'@','.'};
if ~all(contains(email,email_attr))
uiwait(msgbox('Email address must contain: @ and .'));
return
end
success = 1;
function user_email_Callback(hObject, eventdata, handles)
% hObject handle to user_email (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 user_email as text
% str2double(get(hObject,'String')) returns contents of user_email as a double
% Hints: get(hObject,'String') returns contents of ani_name as text
% str2double(get(hObject,'String')) returns contents of ani_name as a double
user_email = get(handles.user_email,'String');
if valid_email(user_email)
gsuite = {'gmail.com','umich.edu'};
if any(contains(user_email,gsuite)) && ~contains(user_email,'+')
user_email = strrep(user_email,'@','+operant@');
end
handles.user_email_addr = user_email;
handles.user_email.String = user_email;
else
set(handles.user_email,'String','PI Email')
set(handles.user_email,'UserData','PI Email')
end
% Choose default command line output for GD_Protocol_Simulink
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% --- Executes during object creation, after setting all properties.
function user_email_CreateFcn(hObject, eventdata, handles)
% hObject handle to user_email (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 update_save_dir.
function update_save_dir_Callback(hObject, eventdata, handles)
% hObject handle to update_save_dir (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
save_dir = handles.save_dir;
new_save_dir = uigetdir(save_dir);
handles.save_dir = new_save_dir;
handles.save_dir_str.String = sprintf('Save data dir: %s',new_save_dir);
guidata(hObject,handles);
drawnow;
%% Tracking and camera functions
function [varargout] = find_animal_local(im,colors,cl_thresh)
%function uses color model and green location in color model to classify
%points as a shade of ear marker green or not. Pts returns empty if less
%than 2% of pixels are classified as green.
BOUNDS = false;
x=size(im,1);
y=size(im,2);
scale = 0.5;
%bad_pts_thresh = 0; %0.1;
%help speed up computation, remove if undeeded for accuracy. speed up = x4
temp = imresize(im,scale);
temp = single(reshape(temp,scale.^2*x*y,3));
color_dist = pdist2(temp,colors); %%slooowwww, faster than knnsearch
[~,close_color] = min(color_dist,[],2);
gr_pts = close_color >= cl_thresh;
if any(gr_pts)
gr_pts = reshape(gr_pts,scale.*x,scale.*y);
if BOUNDS
%don't include parts of image away from guinea pig head, or ass
lower_bound = floor(200.*scale);
upper_bound = ceil(540.*scale);
gr_pts(:,1:lower_bound) = false;
gr_pts(:,upper_bound:end) = false;
end
gr_pts = medfilt2(gr_pts,[3 3]);
gr_pts = imresize(gr_pts,[x y]);
varargout{1} = gr_pts;
[Y,X] = find(gr_pts);
varargout{2} = Y;
varargout{3} = X;
else
gr_pts = [];
end
function run_protocol(hObject,handles)
%insert bounds in image
line_matrix = handles.line_matrix;
left_thresh = line_matrix(1,1);
right_thresh = line_matrix(2,1);
boundary_value = mean([left_thresh right_thresh]);
animal_name = handles.animal_name;
email_address = handles.user_email_addr;
base_dir = handles.base_dir;
run_time = datestr(now,'mmm-dd-yyyy_HH-MM-SS');
%% configure trial parameters
seed = 12281990;%'shuffle'; %
rng(seed);
%need listing of sound types here
aud_play_store = handles.aud_play_store;
freq_spaces = handles.freq_spaces;
if isrow(freq_spaces)
freq_spaces = freq_spaces';
end
sound_lvls = handles.sound_lvls;
if isrow(sound_lvls)
sound_lvls = sound_lvls';
end
rep_counts = 3;
num_trial = numel(sound_lvls)*numel(freq_spaces);
test_trials = floor(num_trial/2);
max_trial_reps = rep_counts*numel(sound_lvls)*numel(freq_spaces);
freq_rep = repmat(freq_spaces,numel(sound_lvls),1);
inten_rep = repmat(sound_lvls,numel(freq_spaces),1);
protocol = [freq_rep inten_rep];
protocol = repmat(protocol,rep_counts,1);
ordering = randsample(1:max_trial_reps,test_trials);
protocol = protocol(ordering,:);
%timings, these should be stored in handles
min_holding = 10;
max_holding = 30;
wait_periods = min_holding+randi((max_holding-min_holding),test_trials,1);
sound_present_time = 30;
max_shock = 15;
trial_max = max_shock+sound_present_time+max_holding;
acclim_time = 10*60; %10 minutes at 60 seconds per min
%freezing and stoopid animals
freeze_fail = 25;
dumb_fail = 30;
if handles.SILENCE_TRIALS
disp('Silence Trials enabled')
num_silence = 10;
silence_dur = 120;
silence_trials = randsample(1:test_trials,num_silence);
wait_periods(silence_trials) = silence_dur;
protocol(silence_trials,1) = 0;
protocol(silence_trials,2) = 2;
protocol(silence_trials,3) = 0;
protocol(silence_trials,4) = silence_dur;
end
%get camera, shocker and sound
vid = handles.vid;
device = handles.device; spi_bus = handles.spi_bus;
current_pin = handles.current_pin;
%% Get Image, find GP
if ~isfield(handles,'color_model')
[hObject,handles] = get_color_model_Callback(hObject, [], handles);
handles.get_color_model.Enable = 'off';
end
color_model=handles.color_model;
cl_thresh=handles.cl_thresh;
pointTracker = vision.PointTracker('NumPyramidLevels',5,'BlockSize',[71 71],'MaxBidirectionalError',5);
if ~isrunning(handles.vid)
start(vid);
end
flushdata(vid);
frame = getdata(vid,1);
[pts,X,Y] = find_animal_local(frame,color_model,cl_thresh);
initialize(pointTracker,median([Y X],1),frame);
old_pos = median([Y X],1);
track_pos = old_pos;
if track_pos(1) <= boundary_value
boundary_val = right_thresh;
plot_line = line_matrix(2,:);
else
boundary_val = left_thresh;
plot_line = line_matrix(1,:);
end
%insert bounds
frame = insertMarker(frame,track_pos,'Color','green','marker','*');
frame = insertShape(frame,'line',plot_line,'Color','Red','LineWidth',2);
%% Update gui labels
%state, trial time, trial number, sound onset time, shock onset time
trial_state_string = {};
set(handles.trial_print,'String',trial_state_string);
drawnow;
%% plot image into axis
set(handles.image_feed,'Units','pixels');
resizePos = get(handles.image_feed,'Position');
frame = imresize(frame,[resizePos(4) resizePos(3)]);
%axes(handles.image_feed);
imshow(frame,'Parent',handles.image_feed);
set(handles.image_feed,'Units','normalized');
guidata(hObject,handles);
drawnow;
state_list = {'acclim','holding','silence','sound','shock','sound-and-shock','freeze'};
if handles.no_acclim.Value
state = 'acclim'; %'holding'; %1 = holding, 2 = sound, 3 = sound and shock, 4 = freeze
protocol_idx = 0;
else
state = 'holding';
protocol_idx = 1;
end
protocol_times = nan(test_trials,3);
time_idx = 1;
SOUND_ENABLE = false;
SHOCK_ENABLE = false;
ERROR_ENABLE = false;
fps = 15;
max_time = ceil((acclim_time+trial_max*test_trials)*fps*1.1);
trajectory = nan(fps*max_time,2);
timestamps = nan(fps*max_time,5);
crossings = 0;
%ensure sound is enabled
system(['"' base_dir '\nircmd.exe" setsysvolume 65535 &']) %max volume = 16 bit
start_time = tic;
protocol_start = toc(start_time);
trial_time = toc(start_time);
max_exp_time = 60*60; %stop all testing after 1 hour
try
total_time = tic;
frame = 0;
gp_freeze = 0;
fail_counter = 0;
while protocol_idx <= test_trials
%% Get new frame, align to background image prior to image subtraction
flushdata(vid);
while ~vid.FramesAvailable
drawnow;
end
frame = getdata(vid,1);
%% Find learned colors
[pts,X,Y] = find_animal_local(frame,color_model,cl_thresh);
if isempty(X) || isempty(Y)
track_pos = old_pos;
else
old_pos = track_pos;
track_pos = median([Y X],1);
end
%update point tracker
[new_coordes,valid] = step(pointTracker,frame);
if ~valid || sqrt(sum((old_pos-track_pos).^2)) >= 10
new_coordes = track_pos;
setPoints(pointTracker,new_coordes);
end
%save old position, update new position
track_pos = mean([new_coordes; track_pos]);
%% Stor vars, run state machine
trajectory(time_idx,:) = track_pos;
frame_time = toc(start_time);
if frame_time >= max_exp_time
state = 'time_over';
end
%Update timestamps matrix
timestamps(time_idx,1) = frame_time;
timestamps(time_idx,2) = crossings;
state_code = find(contains(state_list,state),1);
timestamps(time_idx,3) = state_code;
full_elapsed_time = toc(total_time);
timestamps(time_idx,4) = full_elapsed_time;
trial_time = frame_time - protocol_start;
set(handles.exp_time,'String',sprintf('Time: %4.2f/%4.0f',full_elapsed_time,max_exp_time));
set(handles.state_label,'String',sprintf('State: %s',state));
set(handles.trial_number_str,'String',sprintf('Trials: %d/%d',protocol_idx,test_trials));
set(handles.trial_time,'String',sprintf('Trial time: %3.2f sec',trial_time));
set(handles.cross_str,'String',sprintf('Crossings: %d',crossings));
if strcmp(state,'acclim')
set(handles.sound_time_str,'String',sprintf('Start: %3.2f sec',acclim_time));
set(handles.estim_time_str,'String',sprintf('EStim: %d sec','---'));
else
set(handles.sound_time_str,'String',sprintf('Sound: %d sec',wait_periods(protocol_idx)));
set(handles.estim_time_str,'String',sprintf('EStim: %d sec',wait_periods(protocol_idx) + sound_present_time));
end
%wait_periods(protocol_idx) + sound_present_time + max_shock;
%set(handles.exp_time_str,'String',sprintf('Total Time: %d',
%update string parameters on image
% if ~strcmp(state,'silence')
% marked = insertText(marked,[1 80],...
% ['Sound time: ' num2str(wait_periods(protocol_idx))],image_params{:});
% marked = insertText(marked,[1 120],...
% ['Shock time: ' num2str(wait_periods(protocol_idx)+stim_dur_threshold)],image_params{:});
% else
% marked = insertText(marked,[1 80],['Silence ends: ' num2str(wait_periods(protocol_idx))],image_params{:});
% end
%% State machine
%reset freeze counter
if gp_freeze < 0
gp_freeze = 0;
end
%acclimation period
if strcmp(state,'acclim') || protocol_idx == 0
if trial_time >= acclim_time
state = 'holding';
protocol_idx = protocol_idx + 1;
end
elseif strcmp(state,'holding') %currently holding period
if trial_time >= wait_periods(protocol_idx)
state = 'sound';
protocol_times(protocol_idx,1) = time_idx;
protocol_times(protocol_idx,2) = crossings;
%enable sound
SOUND_ENABLE = true;
SHOCK_ENABLE = false;
drawnow;
if exist('sound_player','var')
stop(sound_player);
end
sound_band = protocol(protocol_idx,1);
sound_inten = protocol(protocol_idx,2);
f_idx = find(freq_spaces==sound_band,1);
i_idx = find(sound_lvls==sound_inten,1);
sound_player = aud_play_store{f_idx,i_idx};
play(sound_player);
drawnow;
elseif protocol(protocol_idx,2) == 2
state = 'silence';
stop(sound_player);
trial_state_string = [trial_state_string; {'Silence'}];
set(handles.trial_print,'String',trial_state_string);
drawnow;
SOUND_ENABLE = false;
SHOCK_ENABLE = false;
end
elseif strcmp(state,'silence')
if trial_time > wait_periods(protocol_idx)
protocol_times(protocol_idx,3) = nan;
protocol_idx = protocol_idx + 1;
start_time = tic;
protocol_start = toc(start_time);
state = 'holding';
end
%% Sound is playing
elseif strcmp(state,'sound')
%if crossings increase after sound starting, disable stim
if timestamps(time_idx,2) > protocol_times(protocol_idx,2)
writeDigitalPin(device,current_pin,false)
stop(sound_player);
trial_state_string = [trial_state_string; {sprintf('Trial %d: Success!',protocol_idx)}];
set(handles.trial_print,'String',trial_state_string);
drawnow;
SOUND_ENABLE = false;
SHOCK_ENABLE = false;
drawnow;
start_time = tic;
protocol_start = toc(start_time);
state = 'holding';
protocol_times(protocol_idx,3) = 1;
protocol_idx = protocol_idx + 1;
elseif trial_time > wait_periods(protocol_idx) + sound_present_time
%animal hasn't crossed, go to sound with shock
writeDigitalPin(device,current_pin,true)
SHOCK_ENABLE = true;
SOUND_ENABLE = true;
trial_state_string = [trial_state_string; {sprintf('Trial %d: Fail!',protocol_idx)}];
set(handles.trial_print,'String',trial_state_string);
drawnow;
state = 'sound-and-shock';
fail_counter = fail_counter + 1;
protocol_times(protocol_idx,3) = 0;
if fail_counter >= dumb_fail
state = 'freeze';
end
end
%% sound is playing and shock enabled
elseif strcmp(state,'sound-and-shock')
max_stim = wait_periods(protocol_idx) + sound_present_time + max_shock;
if timestamps(time_idx,2) > protocol_times(protocol_idx,2) || ...
trial_time > max_stim
%detect freezing behavior
if trial_time > max_stim
gp_freeze = gp_freeze + 1;
else
gp_freeze = gp_freeze - 1;
end
if gp_freeze >= freeze_fail
state = 'freeze';
else
state = 'holding';
end
writeDigitalPin(device,current_pin,false)
stop(sound_player);
SOUND_ENABLE = false;
SHOCK_ENABLE = false;
protocol_idx = protocol_idx + 1;
start_time = tic;
protocol_start = toc(start_time);
end
elseif strcmp(state,'time_over')
protocol_idx = test_trials + 1;
writeDigitalPin(device,current_pin,false)
stop(sound_player);
SOUND_ENABLE = false;
SHOCK_ENABLE = false;
ERROR_ENABLE = false;
elseif strcmp(state,'error')
protocol_idx = test_trials + 1;
writeDigitalPin(device,current_pin,false)
stop(sound_player);
SOUND_ENABLE = false;
SHOCK_ENABLE = false;
ERROR_ENABLE = true;
elseif strcmp(state,'freeze')
protocol_idx = test_trials + 1;
writeDigitalPin(device,current_pin,false)
stop(sound_player);
SOUND_ENABLE = false;
SHOCK_ENABLE = false;
ERROR_ENABLE = true;
end
%% markers and such on frame
if SOUND_ENABLE
handles.sound_str.String = "SOUND ENABLED";
handles.sound_str.ForegroundColor = [0 1 0]; %color green
else
handles.sound_str.String = 'SOUND DISABLED';
handles.sound_str.ForegroundColor = [0 1 1]; %green
end
drawnow;
if SHOCK_ENABLE
handles.shock_str.String = "SHOCK ENABLED";
handles.shock_str.ForegroundColor = [1 0 0]; %color red
else
% marked = insertText(marked,[250 120],['SHOCK'],'FontSize',18,'BoxColor','yellow','BoxOpacity',0.4,'textcolor','red');
handles.shock_str.String = 'SHOCK DISABLED';
handles.shock_str.ForegroundColor = [0 0 1]; %blue
end