-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstimgen.py
2370 lines (1817 loc) · 87.9 KB
/
stimgen.py
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
from __future__ import division
import numpy as np
import scipy.stats as stats
from PyQt4 import QtCore, QtGui
import logging
import os
from matplotlib.backends.backend_qt4agg import FigureCanvas #ensure matplotlib is updated
from matplotlib.figure import Figure
from matplotlib.pyplot import Line2D
from matplotlib import patches
from matplotlib import cm
from random import randint
from copy import deepcopy
import pickle
from listquote import LineParser
#import cv2
from matplotlib import rcParams
if rcParams['backend.qt4']!='PyQt4':
raise ValueError('matplotlib.rcParams[\'backend.qt4\'] should be = PyQt4. Edit matplotlibrc file')
import spot
'''
try:
from numba import jit # used for detrending maths. Not required.
except ImportError:
logging.warning('Numba is not installed. Please install numba package for optimal performance!')
def jit(a):
return a
'''
__author__ = 'edmund'
LIST_ITEM_ENABLE_FLAG = QtCore.Qt.ItemFlag(QtCore.Qt.ItemIsSelectable + QtCore.Qt.ItemIsEnabled +
QtCore.Qt.ItemIsDragEnabled + QtCore.Qt.ItemIsUserCheckable) # 57
class CalibrationViewer(QtGui.QMainWindow):
def __init__(self):
self.filters = list()
super(CalibrationViewer, self).__init__()
self.autolabel=1 #automatically generate pattern labels
self.setWindowTitle('Pattern stim')
self.statusBar()
self.trial_selected_list = []
self.session_id=0
self.sess_list=[]
self.spots={}
self.stim_types=['target','nontarget','probe']
self.file_list=[]
self.fn=''
self.gridmax=[]
self.DMD_dim=[]
self.update_mode=True
self.random_spacing=1.5 #when generating new spot, the minimum spot spacing from others in self.spots['list']
mainwidget = QtGui.QWidget(self)
self.setCentralWidget(mainwidget)
layout = QtGui.QVBoxLayout(mainwidget)
mainwidget.setLayout(layout)
self.statusbar = QtGui.QStatusBar()
self.setStatusBar(self.statusbar)
#===menu items====
menu = self.menuBar()
filemenu = menu.addMenu("&File")
toolsmenu = menu.addMenu("&Tools")
openAction = QtGui.QAction("&Open datafile...", self)
openAction.triggered.connect(self._openAction_triggered)
openAction.setStatusTip("Open a processed results file.")
openAction.setShortcut("Ctrl+O")
filemenu.addAction(openAction)
#==save to current file==
saveAllAction = QtGui.QAction('&Save to current file...', self)
saveAllAction.triggered.connect(self._saveAllAction_triggered)
saveAllAction.setShortcut('Ctrl+S')
saveAllAction.setStatusTip("Saves patterns,spots and options to pickle.")
filemenu.addAction(saveAllAction)
#==save as==
saveAsAction = QtGui.QAction('Save to new file...', self)
saveAsAction.triggered.connect(self._saveAsAction_triggered)
filemenu.addAction(saveAsAction)
#==full screen==
screenAction = QtGui.QAction("Toggle screen size...", self)
screenAction.triggered.connect(self._screenAction_triggered)
screenAction.setStatusTip("Toggle screen.")
screenAction.setShortcut("Ctrl+E")
filemenu.addAction(screenAction)
#===quit===
exitAction = QtGui.QAction("&Quit", self)
exitAction.setShortcut("Ctrl+Q")
exitAction.setStatusTip("Quit program.")
exitAction.triggered.connect(QtGui.qApp.quit)
filemenu.addAction(exitAction)
#===toggle auto-label===
autolabelAction = QtGui.QAction("&Autolabel", self)
autolabelAction.setStatusTip('Apply auto-labelling to new sessions.')
autolabelAction.triggered.connect(self._make_autolabel_all)
toolsmenu.addAction(autolabelAction)
#===fix spots===
displayParamsAction = QtGui.QAction("&Finalize spots", self)
displayParamsAction.setStatusTip('Finalize spot definitions.')
displayParamsAction.triggered.connect(self._finalize_spots)
toolsmenu.addAction(displayParamsAction)
#===fix spots===
QAction = QtGui.QAction("Set 1st session number", self)
QAction.triggered.connect(self._set_first_sess)
toolsmenu.addAction(QAction)
row1_layout = QtGui.QHBoxLayout()
row2_layout = QtGui.QHBoxLayout()
layout.addLayout(row1_layout)
layout.addLayout(row2_layout)
#===session list====
sess_select_box = QtGui.QGroupBox()
sess_select_layout = QtGui.QVBoxLayout()
sess_select_box.setLayout(sess_select_layout)
sess_select_box.setTitle('Sessions')
sess_select_box.setFixedWidth(100)
self.sess_select = SessListWidget()
sess_select_layout.addWidget(self.sess_select)
self.sess_select.itemSelectionChanged.connect(self._sess_select_changed)
row1_layout.addWidget(sess_select_box)
self.sess_select.showh5Sig.connect(self.showh5)
self.sess_select.deleteSessionSig.connect(self.delete_session)
#define push button to generate new session
self.new_session_btn = QtGui.QPushButton('Add')
self.new_session_btn.clicked.connect(self._new_session)
sess_select_layout.addWidget(self.new_session_btn)
#===session info===
sess_info_box = QtGui.QWidget()
sess_info_layout = QtGui.QVBoxLayout()
row1_layout.addWidget(sess_info_box)
sess_info_box.setLayout(sess_info_layout)
sess_info_box.setFixedWidth(150)
self.sess_info = SessInfoWidget()
self.sess_comments = SessCommentsWidget()
self.sess_option_select = SessOptionSelectWidget()
self.sess_option_select.currentIndexChanged.connect(self._sess_option_select_changed)
self.sess_option_value = SessOptionValueWidget()
sess_info_layout.addWidget(self.sess_info)
sess_info_layout.addWidget(self.sess_comments)
sess_info_layout.addWidget(self.sess_option_select)
sess_info_layout.addWidget(self.sess_option_value)
#===session plot===
plots_box = QtGui.QGroupBox()
plots_box.setTitle('Session Plot')
plots_layout = QtGui.QHBoxLayout()
self.figure = Figure((9, 5))
self.figure.patch.set_facecolor('white')
self.canvas = FigureCanvas(self.figure)
self.canvas.setParent(plots_box)
self.canvas.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
plots_layout.addWidget(self.canvas)
plots_box.setLayout(plots_layout)
row1_layout.addWidget(plots_box)
self.ax_sess = self.figure.add_subplot(1, 1, 1)
self.ax_sess.set_title('Left bias')
self.ax_sess.set_ylabel('%')
self.ax_sess.set_xlabel('Trial')
#self.ax_mean_plots.autoscale(enable=True, axis=u'both', tight=False)
self.figure.tight_layout()
#===defined spot list===
spot_select_box = QtGui.QGroupBox()
spot_select_layout = QtGui.QVBoxLayout()
spot_select_layout.setSpacing(0)
spot_select_box.setLayout(spot_select_layout)
spot_select_box.setTitle('Defined spots')
spot_select_box.setFixedWidth(100)
self.spot_select = SpotListWidget()
self.spot_select.itemSelectionChanged.connect(self._spot_select_changed)
spot_select_layout.addWidget(self.spot_select)
self.spot_select.renameSpotSig.connect(self.rename_spot)
self.spot_select.deleteSpotSig.connect(self.delete_spot)
self.spot_select.RNGSpotSig.connect(self.RNG_spot)
self.spot_select.emptySpotSig.connect(self.empty_spot)
#===spot x, y coordinate entry boxes==
spot_xy_box = QtGui.QGroupBox()
spot_xy_box.setFlat(True)
spot_xy_layout = QtGui.QHBoxLayout()
spot_xy_box.setLayout(spot_xy_layout)
spot_select_layout.addWidget(spot_xy_box)
self.spot_x=QtGui.QLineEdit()
self.spot_y=QtGui.QLineEdit()
spot_xy_layout.addWidget(self.spot_x)
spot_xy_layout.addWidget(self.spot_y)
spot_xy_layout.setSpacing(0)
#==button to add new spot==
self.new_spot_btn = QtGui.QPushButton('New')
self.new_spot_btn.clicked.connect(self._new_spot)
spot_select_layout.addWidget(self.new_spot_btn)
self.redo_spot_btn = QtGui.QPushButton('Redo')
self.redo_spot_btn.clicked.connect(self._redo_spot)
spot_select_layout.addWidget(self.redo_spot_btn)
row2_layout.addWidget(spot_select_box)
#===spot(s) display===
spot_disp_box = QtGui.QGroupBox()
spot_disp_layout = QtGui.QHBoxLayout()
#spot_disp_box.setFixedWidth(200)
self.spot_disp_figure = Figure()
self.spot_disp_figure.patch.set_facecolor('white')
self.spot_disp_canvas = FigureCanvas(self.spot_disp_figure)
self.spot_disp_canvas.setParent(spot_disp_box)
#self.spot_disp_canvas.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
#self.spot_disp_canvas.setFixedHeight(200)
spot_disp_layout.addWidget(self.spot_disp_canvas)
spot_disp_box.setLayout(spot_disp_layout)
row2_layout.addWidget(spot_disp_box)
self.ax_spot_disp = self.spot_disp_figure.add_subplot(1, 1, 1)
#===pattern sequence list===
pattern_select_box = QtGui.QGroupBox()
pattern_select_layout = QtGui.QVBoxLayout()
pattern_select_layout.setSpacing(0)
pattern_select_box.setLayout(pattern_select_layout)
pattern_select_box.setTitle('Session-defined patterns')
pattern_select_box.setFixedWidth(280)
self.pattern_select = PatternSelectWidget()
self.pattern_select.currentIndexChanged.connect(self._pattern_select_changed)
self.pattern_select.deletePatternSig.connect(self.delete_pattern)
pattern_select_layout.addWidget(self.pattern_select)
row2_layout.addWidget(pattern_select_box)
#==pattern spot list==
self.patternspot_select = PatternspotListWidget()
self.patternspot_select.itemSelectionChanged.connect(self._patternspot_select_changed)
pattern_select_layout.addWidget(self.patternspot_select)
#==pattern spot onset and duration==
spot_timing_layout = QtGui.QHBoxLayout()
spot_timing_box = QtGui.QGroupBox()
spot_timing_box.setLayout(spot_timing_layout)
spot_timing_box.setFlat(True)
pattern_select_layout.addWidget(spot_timing_box)
self.spot_onset=QtGui.QLineEdit()
self.spot_onset.setStatusTip("To specify random, input 'lower, upper' e.g. 10,80")
self.spot_dur=QtGui.QLineEdit()
self.spot_dur.setStatusTip("To specify random, input 'lower, upper' e.g. 10,80")
self.spot_intensity=QtGui.QLineEdit()
self.spot_intensity.setStatusTip("0-255. For random, input 'lower, upper'. e.g. 0,255")
spot_onset_box= QtGui.QGroupBox()
spot_onset_layout=QtGui.QVBoxLayout()
spot_onset_box.setLayout(spot_onset_layout)
spot_onset_layout.addWidget(self.spot_onset)
spot_onset_box.setTitle('Onset')
spot_dur_box= QtGui.QGroupBox()
spot_dur_layout=QtGui.QVBoxLayout()
spot_dur_box.setLayout(spot_dur_layout)
spot_dur_layout.addWidget(self.spot_dur)
spot_dur_box.setTitle('Dur')
spot_intensity_box= QtGui.QGroupBox()
spot_intensity_layout=QtGui.QVBoxLayout()
spot_intensity_box.setLayout(spot_intensity_layout)
spot_intensity_layout.addWidget(self.spot_intensity)
spot_intensity_box.setTitle('Pwr')
spot_timing_layout.addWidget(spot_onset_box)
spot_timing_layout.addWidget(spot_dur_box)
spot_timing_layout.addWidget(spot_intensity_box)
spot_timing_layout.setSpacing(0)
#==pattern grouping==
spot_grouping_layout = QtGui.QHBoxLayout()
spot_grouping_box = QtGui.QGroupBox()
spot_grouping_box.setLayout(spot_grouping_layout)
spot_grouping_box.setFlat(True)
pattern_select_layout.addWidget(spot_grouping_box)
self.spot_grouptime=QtGui.QLineEdit()
self.spot_grouptime.setStatusTip("group number, offset. e.g. 1, 20 means 20 ms after group 1")
generic_box= QtGui.QGroupBox()
generic_layout=QtGui.QVBoxLayout()
generic_box.setLayout(generic_layout)
generic_layout.addWidget(self.spot_grouptime)
generic_box.setTitle('group time')
spot_grouping_layout.addWidget(generic_box)
self.sequence_omit=QtGui.QLineEdit()
self.sequence_omit.setStatusTip("Randomly choose n spots to omit from pattern on each trial")
generic_box= QtGui.QGroupBox()
generic_layout=QtGui.QVBoxLayout()
generic_box.setLayout(generic_layout)
generic_layout.addWidget(self.sequence_omit)
generic_box.setTitle('Omit')
spot_grouping_layout.addWidget(generic_box)
self.sequence_replace=QtGui.QLineEdit()
self.sequence_replace.setStatusTip("Randomly choose n spots to replace with random pool spot ")
generic_box= QtGui.QGroupBox()
generic_layout=QtGui.QVBoxLayout()
generic_box.setLayout(generic_layout)
generic_layout.addWidget(self.sequence_replace)
generic_box.setTitle('Sub')
spot_grouping_layout.addWidget(generic_box)
self.sequence_meanT=QtGui.QLineEdit()
self.sequence_meanT.setStatusTip("Define mean timing.")
generic_box= QtGui.QGroupBox()
generic_layout=QtGui.QVBoxLayout()
generic_box.setLayout(generic_layout)
generic_layout.addWidget(self.sequence_meanT)
generic_box.setTitle('meanT')
spot_grouping_layout.addWidget(generic_box)
spot_grouping_layout.setSpacing(0)
#==pattern grouping==
spot_grouping_layout2 = QtGui.QHBoxLayout()
spot_grouping_box2 = QtGui.QGroupBox()
spot_grouping_box2.setLayout(spot_grouping_layout2)
spot_grouping_box2.setFlat(True)
pattern_select_layout.addWidget(spot_grouping_box2)
self.sequence_scramble=QtGui.QLineEdit()
self.sequence_scramble.setStatusTip("Scramble order while preserving timing.")
generic_box= QtGui.QGroupBox()
generic_layout=QtGui.QVBoxLayout()
generic_box.setLayout(generic_layout)
generic_layout.addWidget(self.sequence_scramble)
generic_box.setTitle('scramble')
spot_grouping_layout2.addWidget(generic_box)
self.sequence_randt=QtGui.QLineEdit()
self.sequence_randt.setStatusTip("Randomize timing.")
generic_box= QtGui.QGroupBox()
generic_layout=QtGui.QVBoxLayout()
generic_box.setLayout(generic_layout)
generic_layout.addWidget(self.sequence_randt)
generic_box.setTitle('randt')
spot_grouping_layout2.addWidget(generic_box)
self.sequence_randdur=QtGui.QLineEdit()
self.sequence_randdur.setStatusTip("Randomize duration.")
generic_box= QtGui.QGroupBox()
generic_layout=QtGui.QVBoxLayout()
generic_box.setLayout(generic_layout)
generic_layout.addWidget(self.sequence_randdur)
generic_box.setTitle('randdur')
spot_grouping_layout2.addWidget(generic_box)
self.sequence_randxyt=QtGui.QLineEdit()
self.sequence_randxyt.setStatusTip("Randomize x,y,t.")
generic_box= QtGui.QGroupBox()
generic_layout=QtGui.QVBoxLayout()
generic_box.setLayout(generic_layout)
generic_layout.addWidget(self.sequence_randxyt)
generic_box.setTitle('randxyt')
spot_grouping_layout2.addWidget(generic_box)
spot_grouping_layout2.setSpacing(0)
#==button to add/remove spot from pattern==
self.patternspot_transfer_btn = QtGui.QPushButton('Add Spot')
self.patternspot_transfer_btn.clicked.connect(self._patternspot_transfer)
pattern_select_layout.addWidget(self.patternspot_transfer_btn)
#==buttons to add new pattern==
self.pattern_add_btn = QtGui.QPushButton('Add Pattern')
self.pattern_add_btn.clicked.connect(self._add_pattern)
pattern_select_layout.addWidget(self.pattern_add_btn)
#====box that displays timing image===
timing_disp_box = QtGui.QGroupBox()
timing_disp_layout = QtGui.QHBoxLayout()
self.timing_disp_figure = Figure()
self.timing_disp_figure.patch.set_facecolor('white')
self.timing_disp_canvas = FigureCanvas(self.timing_disp_figure)
self.timing_disp_canvas.setParent(timing_disp_box)
self.timing_disp_canvas.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
self.timing_disp_canvas.setFixedHeight(200)
timing_disp_layout.addWidget(self.timing_disp_canvas)
timing_disp_box.setLayout(timing_disp_layout)
row2_layout.addWidget(timing_disp_box)
self.ax_timing_disp = self.timing_disp_figure.add_subplot(1, 1, 1)
self.ax_timing_disp.set_frame_on(False)
self.ax_timing_disp.get_xaxis().tick_bottom()
self.ax_timing_disp.axes.get_yaxis().set_visible(False)
#===create lists for stim definitions===
self.stim_widgets={}
stim_select_width=200
for s in self.stim_types:
self.stim_widgets[s]={}
self.stim_widgets[s]['select_box']=QtGui.QGroupBox()
select_layout = QtGui.QVBoxLayout()
self.stim_widgets[s]['select_box'].setLayout(select_layout)
self.stim_widgets[s]['select_box'].setTitle(s)
self.stim_widgets[s]['select_box'].setFixedWidth(stim_select_width)
self.stim_widgets[s]['select'] = StimListWidget(s)
select_layout.addWidget(self.stim_widgets[s]['select'])
#==button to add/remove pattern from Stim list==
self.stim_widgets[s]['transfer_btn'] = QtGui.QPushButton('Add')
select_layout.addWidget(self.stim_widgets[s]['transfer_btn'])
#==button to add/remove odors==
self.stim_widgets[s]['add_odor'] = QtGui.QPushButton('Add odor')
self.stim_widgets[s]['add_odor'].setObjectName(s)
select_layout.addWidget(self.stim_widgets[s]['add_odor'])
self.stim_widgets[s]['add_odor'].clicked.connect(self._add_odor)
x = QtGui.QPushButton('x')
#==unresolved: in passing arguments to lambda functions, so I can't just pass s in a loop==
self.stim_widgets[self.stim_types[0]]['transfer_btn'].clicked.connect(lambda: self._stim_transfer(self.stim_types[0]))
self.stim_widgets[self.stim_types[1]]['transfer_btn'].clicked.connect(lambda: self._stim_transfer(self.stim_types[1]))
self.stim_widgets[self.stim_types[2]]['transfer_btn'].clicked.connect(lambda: self._stim_transfer(self.stim_types[2]))
self.stim_widgets[self.stim_types[0]]['select'].itemSelectionChanged.connect(lambda: self._stim_select_changed(self.stim_types[0]))
self.stim_widgets[self.stim_types[1]]['select'].itemSelectionChanged.connect(lambda: self._stim_select_changed(self.stim_types[1]))
self.stim_widgets[self.stim_types[2]]['select'].itemSelectionChanged.connect(lambda: self._stim_select_changed(self.stim_types[2]))
row1_layout.addWidget(self.stim_widgets[self.stim_types[0]]['select_box'])
row1_layout.addWidget(self.stim_widgets[self.stim_types[1]]['select_box'])
row2_layout.addWidget(self.stim_widgets[self.stim_types[2]]['select_box'])
def _format_option_dtype(self,optionval,option):
"""returns dtype (pre-defined) of voyeur option. maybe implement as class??"""
floats=['reinforcementpercentage','ratio_training','ratio_probe','ratio_training_probe']
ints=['debias','gridsize','graylevel','initialtrials',
'laserdur','fvdur','lickgraceperiod','order','probeMode']
strings=['initialport','mouse_protocol','protocol_type','rig']
if option in floats:
try:
return float(optionval)
except ValueError:
type_required='float'
elif option in ints:
try:
return int(optionval)
except ValueError:
type_required='int'
else:
try:
return str(optionval)
except ValueError:
type_required='str'
message = 'Cannot parse input. Type '+type_required+ ' required.'
msgBox = QtGui.QMessageBox()
msgBox.setText(message)
msgBox.exec_()
@QtCore.pyqtSlot()
def _openAction_triggered(self):
filedialog = QtGui.QFileDialog(self)
startpath = 'F:/ss_config/'
self.fn = filedialog.getOpenFileName(self, "Select a data file.", startpath, "pickle (*.pickle)", "", QtGui.QFileDialog.DontUseNativeDialog)
#self.fn='template.pickle'
self.setWindowTitle(self.fn)
if self.fn:
with open(self.fn) as f:
[sess_list,spots]=pickle.load(f)
if 'emulation' not in spots: #maintain backward compatibility
spots['emulation']=False
#===populate defined spots==
self.spots= spots
self.spot_select.clear()
spotNames = self.spots['list'].keys()
spotNames.sort()
for i, tstr in enumerate(spotNames):
it = QtGui.QListWidgetItem(tstr, self.spot_select)
if self.spots['finalized']:
self.spot_x.setReadOnly(True)
self.spot_y.setReadOnly(True)
else:
self.spot_x.setReadOnly(False)
self.spot_y.setReadOnly(False)
self.spot_x.returnPressed.connect(self._xy_changed)
self.spot_y.returnPressed.connect(self._xy_changed)
#===populate session info===
self.sess_list = sess_list
self.sess_select.clear()
sessions = [sess['post']['id'] for sess in sess_list]
completed = [sess['completed'] for sess in sess_list]
for tstr,complete in zip(sessions,completed):
it = QtGui.QListWidgetItem(tstr, self.sess_select)
if complete:
it.setTextColor(QtGui.QColor(127,127,127))
else:
it.setTextColor(QtGui.QColor(0,0,0))
self.sess_select.setCurrentRow(0)
for i in range(self.spot_select.count()):
self.spot_select.item(i).setSelected(True)
else:
print('No file selected.')
return
def _screenAction_triggered(self):
if self.windowState() == QtCore.Qt.WindowMaximized:
self.showNormal()
else:
self.showMaximized()
def _rand_xy(self,(x_max,y_max),spacing, ref_spots=np.array([-99,-99])):
if self.rig == 'ALP2':
return self._rand_xy_offset(spacing,ref_spots)
#pick random x,y coordinate to define non-overlapping spots
#spacing: minimum euclidean distance between spots, measured by number of spots
#e.g. 1 means spots cannot be above, below, left, or right, but can be diagonal [distance = sqrt(2)]
#can also supply ref_spots (n-by-2 array) that new spots must not overlap with
#spacing < 0 means spots can overlap
if ref_spots.shape==(2L,):
ref_spots=ref_spots.reshape(1L,2L) #if only one spot, need to reshape for concatenation later
new_spot=[]#container holding all spot values, initialized to -99 (to avoid affecting distance calc)
max_loop=10000
for j in range(max_loop):
x=randint(0,x_max)
y=randint(0,y_max)
euclid_dist=np.sqrt(np.sum((ref_spots-[x,y])**2,1))
if euclid_dist.min() > spacing:
new_spot=[x,y]
break
elif j==max_loop-1:
raise ValueError('max iterations reached, no possible spot found')
return new_spot
def _rand_xy_offset(self,spacing, ref_spots=np.array([-99,-99])):
#for ALP2. grid does not start from (0,0)
if self.rig !='ALP2':
raise ValueError('Inappropriate randomization for rig'+str(self.rig))
if ref_spots.shape==(2L,):
ref_spots=ref_spots.reshape(1L,2L) #if only one spot, need to reshape for concatenation later
new_spot=[]#container holding all spot values, initialized to -99 (to avoid affecting distance calc)
max_loop=10000
for j in range(max_loop):
x=randint(self.grid[0][0],self.grid[0][1])
y=randint(self.grid[1][0],self.grid[1][1])
euclid_dist=np.sqrt(np.sum((ref_spots-[x,y])**2,1))
if euclid_dist.min() > spacing:
new_spot=[x,y]
break
elif j==max_loop-1:
raise ValueError('max iterations reached, no possible spot found')
return new_spot
def _saveAllAction_triggered(self):
if not self._check_last_session():
return
#==save comments==
self.sess_list[self.session_id]['post']['comments']=str(self.sess_comments.toPlainText())
#===update pickle file===
with open(self.fn, 'wb') as f:
pickle.dump([self.sess_list, self.spots], f)
def _saveAsAction_triggered(self):
if not self._check_last_session():
return
self.saveDialog = QtGui.QFileDialog()
saveloc = self.saveDialog.getSaveFileName(self, 'Save As', '', 'pickle (*.pickle)')
saveloc = str(saveloc)
print saveloc
self.fn = saveloc
#===new pickle file===
with open(self.fn, 'wb') as f:
pickle.dump([self.sess_list, self.spots], f)
self.setWindowTitle(self.fn)
def _check_last_session(self):
#do basic parameter checks on the last session (new session)
sess=self.sess_list[-1]
message=''
if sess['completed']==1:
message=message+'Last session should be new, uncompleted session.\n'
stim_ratio_sum=sess['pre']['ratio_probe']+sess['pre']['ratio_training']+sess['pre']['ratio_training_probe']
if stim_ratio_sum != 1:
message=message+'Stim ratios should sum to 1. Currently '+str(stim_ratio_sum)
if (sess['pre']['probeMode']==0) and (sess['pre']['ratio_training']!=1):
message=message+'Probe mode = '+str(sess['pre']['probeMode'])+' but ratio_training='+str(sess['pre']['ratio_probe'])
if (sess['pre']['probeMode']==1) and (sess['pre']['ratio_training']==1):
message=message+'Probe mode = '+str(sess['pre']['probeMode'])+' but ratio_training='+str(sess['pre']['ratio_training'])
#==add parameters for backward compatibility==
#graylevel: for both ALP and Polygon, can be in [1,8]
if 'graylevel' not in sess['pre']:
self.sess_list[-1]['pre']['graylevel']=1
if message != '':
showMessage(message)
return False
else:
return True
def _make_autolabel_all(self):
pass
def _make_autolabel(self):
pattern=str(self.pattern_select.currentText())
spots= self.sess_list[self.session_id]['patterns'][pattern]['defn']
#==sort spot/onset pairs==
spotstrings=[]
for s in spots:
onset=spots[s]['onset']
if s.startswith('R'): #in label, drop index of random spot 'R'
s='R'
spotstrings.append(str(onset).zfill(4) + '_' + s)
spotstrings.sort()
newLabel=''
for s in spotstrings:
[onset, spot] = s.split('_')
if ',' in onset: #list
onset='#'
else:
onset=str(int(onset))
newLabel=newLabel+spot+onset+'_'
newLabel = newLabel[:-1]
oldLabel = pattern
#apply label
self.pattern_select.setItemText(self.pattern_select.currentIndex(),newLabel)
self._pattern_renamed()
def _finalize_spots(self):
msgBox = QtGui.QMessageBox()
if self.spots['finalized']:
message='Spots already finalized!'
msgBox.setText(message)
msgBox.exec_()
return
msgBox.setStandardButtons(QtGui.QMessageBox.Cancel|QtGui.QMessageBox.Ok)
#unfortunately default button order is unintuitive, and cannot be swapped
msgBox.setDefaultButton(QtGui.QMessageBox.Cancel)
message='Finalize spot definitions'
msgBox.setText(message)
ret = msgBox.exec_()
if ret == QtGui.QMessageBox.Cancel:
return
elif ret == QtGui.QMessageBox.Ok:
self.spots['finalized']=1
self.spot_x.setReadOnly(True)
self.spot_y.setReadOnly(True)
msgBox.setStandardButtons(QtGui.QMessageBox.Ok)
message='Spots finalized. Save file to preserve change.'
msgBox.setText(message)
msgBox.exec_()
def _set_first_sess(self):
sess_num, ok = QtGui.QInputDialog.getText(self, 'Input', 'Set first session number:')
self.sess_list[0]['post']['id']=str(sess_num)
self.sess_select.item(0).setText(sess_num)
@QtCore.pyqtSlot()
def _sess_select_changed(self):
#==get session index + other info==
idx = self.sess_select.currentRow()
self.session_id=idx
try:
sess=self.sess_list[self.session_id]
except:
print 'session list index error, probably innocuous: could be during deletion of session'
return
self.rig=sess['pre']['rig']
for p in sess['patterns']:
if 'defn' not in sess['patterns'][p]:
sess['patterns'][p]={'defn':sess['patterns'][p].copy()}
print self.sess_list[self.session_id]['patterns']
#==populate session info==
self.sess_info.clear()
params=['date','total_trials','target_left_acc','target_right_acc']
descriptors={'date':'date: ',
'total_trials': 'nTrials: ',
'target_left_acc': 'Target Left: ',
'target_right_acc': 'Target Right: ',
}
for p in params:
textstring = descriptors[p]+str(sess['post'][p])
self.sess_info.append(textstring)
#==get order==
if sess['pre']['order']==0:
side = {'target': ' (left)', 'nontarget': ' (right)'}
elif sess['pre']['order']==1:
side = {'target': ' (right)', 'nontarget': ' (left)'}
for stim in side:
self.stim_widgets[stim]['select_box'].setTitle(stim+side[stim])
#==populate session comments==
self.sess_comments.clear()
textstring = sess['post']['comments']
self.sess_comments.insertPlainText(textstring)
#==re-populate sess option dropdown menu==
options=sess['pre'].keys()
options.sort()
self.sess_option_select.clear()
for o in options:
self.sess_option_select.addItem(o)
self.update_sess_plot()
self._sess_option_select_changed() #update option value too
#==calculate grid x_max and y_max==
s=spot.Spot(sess['pre']['rig'])
if sess['pre']['rig']=='ALP2':
self.grid = self.spots['grid']
self.gridmax=s.get_grid_max(sess['pre']['gridsize'])
self.DMD_dim = s.Im_dim
#===set editability of patterns===
input_params = {}
input_params['setReadOnly'] = [self.sess_option_value,
self.spot_onset,
self.spot_dur,
self.spot_intensity,
self.spot_grouptime,
self.sequence_omit,
self.sequence_replace,
self.sequence_meanT,
self.sequence_scramble,
self.sequence_randt,
self.sequence_randdur,
self.sequence_randxyt]
input_params['setEditable'] = [self.pattern_select]
input_params['setEnabled'] = [self.patternspot_transfer_btn,
self.pattern_add_btn]
for s in self.stim_types:
input_params['setEnabled'].append(self.stim_widgets[s]['transfer_btn'])
if sess['completed']==1:
#==forbid changing options if session was completed===
for param in input_params['setReadOnly']:
param.setReadOnly(True)
for param in input_params['setEditable']:
param.setEditable(False)
for param in input_params['setEnabled']:
param.setEnabled(False)
else:
for param in input_params['setReadOnly']:
param.setReadOnly(False)
for param in input_params['setEditable']:
param.setEditable(True)
for param in input_params['setEnabled']:
param.setEnabled(True)
#===allow saving of edited values by pressing return (without updating pickle yet)
self.sess_option_value.returnPressed.connect(self._option_value_changed)
self.pattern_select.lineEdit().returnPressed.connect(self._pattern_renamed)
self.spot_onset.returnPressed.connect(self._timing_changed)
self.spot_dur.returnPressed.connect(self._timing_changed)
self.spot_intensity.returnPressed.connect(self._timing_changed)
self.spot_grouptime.returnPressed.connect(self._timing_changed)
self.sequence_omit.returnPressed.connect(self._sequence_global_changed)
self.sequence_replace.returnPressed.connect(self._sequence_global_changed)
self.sequence_meanT.returnPressed.connect(self._sequence_global_changed)
self.sequence_scramble.returnPressed.connect(self._sequence_global_changed)
self.sequence_randt.returnPressed.connect(self._sequence_global_changed)
self.sequence_randdur.returnPressed.connect(self._sequence_global_changed)
self.sequence_randxyt.returnPressed.connect(self._sequence_global_changed)
if self.autolabel==1: #override pattern naming settings if autolabel mode is on
self.pattern_select.setEditable(False)
#==define 'odors' dict if not already defined, for backward compatibility
if 'odors' not in self.sess_list[self.session_id]:
self.sess_list[self.session_id]['odors']={'target':[],'nontarget':[],'probe':[],'probeTraining':[]}
#==populate patterns==
patterns=sess['patterns'].keys()
patterns.sort()
self.pattern_select.clear()
for p in patterns:
self.pattern_select.addItem(p)
#==populate stim lists==
for s in self.stim_types:
self.populate_stim_select(s)
return
def _new_session(self):
#create new session, copying the currently selected session
if not self.sess_list: #==first session==
sess_num, ok = QtGui.QInputDialog.getText(self, 'Input', 'Set first session number:')
sess_num = str(sess_num)
sess_dict={'completed':0,'pre':{},'post':{},'patterns':{}, 'stim':{},'odors':{} }
sess_dict['completed']=0
sess_dict['post']['id']=sess_num
sess_dict['pre']['debias']=0
sess_dict['pre']['initialtrials']=0
sess_dict['pre']['initialport']='Left'
sess_dict['pre']['laserdur']=500
sess_dict['pre']['lickgraceperiod']=600
sess_dict['pre']['order']=0
sess_dict['pre']['mouse_protocol']='patternstim_2AFC'
sess_dict['pre']['protocol_type']='test'
sess_dict['pre']['probeMode']=0
sess_dict['pre']['reinforcementpercentage']=1
sess_dict['pre']['gridsize']=20
sess_dict['pre']['graylevel']=1
sess_dict['pre']['ratio_training']=1.0
sess_dict['pre']['ratio_probe']=0.0
sess_dict['pre']['ratio_training_probe']=0.0
sess_dict['pre']['rig']='ALP'
sess_dict['patterns']={}
sess_dict['stim']['target']=[]
sess_dict['stim']['nontarget']=[]
sess_dict['stim']['probe']=[]
sess_dict['stim']['probeTraining']=[]
sess_dict['odors']['target']=[]
sess_dict['odors']['nontarget']=[]
sess_dict['odors']['probe']=[]
sess_dict['odors']['probeTraining']=[]
new_sess = deepcopy(sess_dict)
#initialize spots
self.spots['finalized'] = 0
self.spots['list'] = {}
else:
new_sess = deepcopy(self.sess_list[self.session_id])
new_sess['completed']=0
new_sess['post']['id']='New'
post_vars=['date','target_left_acc','target_right_acc','total_trials','h5file',
'left_plot','right_plot','quit-o-meter','comments']
for v in post_vars:
new_sess['post'][v]=''
self.sess_list.append(new_sess)
self.sess_select.addItem(new_sess['post']['id']) #update listwidget
last_index=self.sess_select.count()-1
self.sess_select.setCurrentRow(last_index) #set selection to new item
def _new_spot(self):
print self.spots
if self.spots['finalized']:
self.spots_finalized()
return
#==randomly generate new name for spot==
spot_name='New'
while spot_name in self.spots['list']:
spot_name='New' + str(randint(0,100))
self.spot_select.addItem(spot_name)
print self.spots
if self.spots['emulation']:
#emulation mode
filedialog = QtGui.QFileDialog(self)
startpath = 'C:/voyeur_rig_config/'
im_path = filedialog.getOpenFileName(self, "Select an image file.", startpath, "png (*.png)", "", QtGui.QFileDialog.DontUseNativeDialog)
spot=cv2.imread(str(im_path),0)
self.spots['list'][spot_name]=spot