-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·1936 lines (1654 loc) · 91.4 KB
/
Copy pathmain.py
File metadata and controls
executable file
·1936 lines (1654 loc) · 91.4 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
# !/usr/bin/env python
'''
PyBehaviour
(c) 2015 Lloyd Russell
v2019.09.06
'''
import warnings
warnings.filterwarnings('ignore')
import matplotlib
matplotlib.use('Qt5Agg', force=True)
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.figure import Figure
from matplotlib import patches
from matplotlib.colors import LinearSegmentedColormap
from cycler import cycler
from matplotlib import cm
import seaborn
seaborn.set(rc={
'axes.axisbelow': True,
'axes.linewidth': 1,
'axes.facecolor': [1.0, 1.0, 1.0],
'axes.edgecolor': [0.9, 0.9, 0.9],
'grid.color': [0.9, 0.9, 0.9]
},
font_scale=0.9)
import numpy as np
import scipy.io as sio
from scipy import stats
from statsmodels.stats.proportion import proportion_confint
import json
import os
import ctypes
import time
import sys
import serial
from PyQt5.QtCore import QObject, pyqtSignal, QThread, QTimer
from PyQt5.QtWidgets import (QComboBox, QCheckBox, QLineEdit, QSpinBox,
QDoubleSpinBox, QFileDialog, QApplication,
QDesktopWidget, QMainWindow, QMessageBox, QRadioButton)
from PyQt5.QtGui import QIcon
from GUI import GUI, serial_ports
import pickle
import logging
# enable printing colours to command window
import colorama
from termcolor import colored
colorama.init()
# configure logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler('errors.log') # create a file handler
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # create a logging format
handler.setFormatter(formatter)
logger.addHandler(handler) # add the handlers to the logger
logger.info('Started application')
class TrialRunner(QObject):
'''
Background worker. Runs the trials.
'''
def __init__(self):
super(TrialRunner, self).__init__()
self._session_running = False
self._paused = False
self._exiting = False
self.trial_num = 0
def startSession(self):
while not self._exiting:
time.sleep(0.01)
# the main session loop
try:
while self._session_running:
# check to see if arduino is connected
if arduino['connected'] is False:
self.connectArduino()
# the pause loop
if arduino['connected']:
while self._paused:
time.sleep(0.01)
# run the trial!
self.runTrial(self.trial_num, trials)
self.trial_num += 1
# check to see if session has finished
if p['sessionDurationMode'] == 'Trials':
if self.trial_num == p['sessionDuration']:
self._session_running = False
# if arduino cannot be connected, abort
else:
self._session_running = False
# send the session over signal
if self._session_running is False:
self.session_end_signal.emit()
except Exception as e:
logger.exception(e)
self.comm_feed_signal.emit(str(e), 'pc')
def connectArduino(self):
self.comm_feed_signal.emit('Connecting Arduino on port ' + p['device'], '')
try:
arduino['device'] = serial.Serial(p['device'], 19200)
arduino['device'].timeout = 1
connect_attempts = 1
current_attempt = 1
while arduino['connected'] is False and current_attempt <= connect_attempts:
temp_read = arduino['device'].readline().strip().decode('utf-8')
self.comm_feed_signal.emit(temp_read, 'arduino')
if temp_read == '{READY}':
arduino['connected'] = True
self.arduino_connected_signal.emit()
arduino['device'].timeout = 0.05
else:
current_attempt += 1
if current_attempt > connect_attempts:
self.comm_feed_signal.emit('Failed to connect', 'pc')
arduino['device'].close()
except serial.SerialException as e:
logger.exception(e)
self.comm_feed_signal.emit('Serial error', 'pc')
def disconnectArduino(self):
if arduino['connected']:
arduino['connected'] = False
self.comm_feed_signal.emit('Disconnecting Arduino...', '')
arduino['device'].close()
self.arduino_disconnected_signal.emit()
def runTrial(self, trial_num, trials):
self.setupResultsDict(trial_num) # initialise the results for current trial
self.trial_start_signal.emit(trial_num) # let GUI know trial number etc
self.transmitConfig(trial_num) # construct and transmit trial instruction to arduino
self.receiveData(trial_num) # will sit in this function until it receives the {DONE} command
self.trial_end_signal.emit(trial_num) # updates plots, save results
def setupResultsDict(self, trial_num):
trials['results'].append({})
trials['results'][trial_num]['responses'] = [[], []]
trials['results'][trial_num]['trialstart'] = []
trials['results'][trial_num]['withold_req'] = []
trials['results'][trial_num]['withold_act'] = []
trials['results'][trial_num]['stim_type'] = []
trials['results'][trial_num]['stim_var'] = []
trials['results'][trial_num]['response_required'] = []
trials['results'][trial_num]['reward_channel'] = []
trials['results'][trial_num]['parameters'] = p
trials['results'][trial_num]['firstresponse'] = []
trials['results'][trial_num]['correct'] = []
trials['results'][trial_num]['incorrect'] = []
trials['results'][trial_num]['miss'] = []
trials['results'][trial_num]['cheated'] = []
def transmitConfig(self, trial_num):
'''
Configure the current trial parameters.
Construct a string listing all the various configuration parameters.
Send this string to the arduino.
'''
# adjust trial order if repeat-if-incorrect
if trial_num > 0 and p['repeatIfIncorrect']:
max_repeats = int(p['maximumRepeatsIfIncorrect'])
if trial_num >= max_repeats:
prev_trials = p['trialOrder'][trial_num-max_repeats:trial_num]
else:
prev_trials = p['trialOrder'][:trial_num]
if (trial_num >= max_repeats) and (np.sum(trials['running_score'][trial_num-max_repeats:trial_num]) <= 0) and (prev_trials.min() == prev_trials.max()):
pass # do not repeat any more if max_repeats of a stim has been exceeded
# add in here the option of changing to a different stim type if desired
elif trials['running_score'][trial_num-1] <= 0:
# shift next trials back
p['trialOrder'][trial_num+1:-1] = p['trialOrder'][trial_num:-2]
p['trialVariations'][trial_num+1:-1] = p['trialVariations'][trial_num:-2]
# make this stim same as previous
p['trialOrder'][trial_num] = p['trialOrder'][trial_num-1]
p['trialVariations'][trial_num] = p['trialVariations'][trial_num-1]
# get the current stim type
this_stim = int(p['trialOrder'][trial_num])
this_stim_idx = p['stimChannels'].index(this_stim)
this_var = int(p['trialVariations'][trial_num])
trials['results'][trial_num]['stim_type'] = this_stim
trials['results'][trial_num]['stim_var'] = this_var
# get response required
resp_req = p['respRequired'][this_stim_idx]
trials['results'][trial_num]['response_required'] = resp_req
require_x_resps = p['RequireXResponses']
# resonse-cancels-trial (post stim delay)
post_stim_cancel = p['postStimCancel']
# allow second chance if correc choice made after incorrect choice?
second_chance = p['secondChance']
# get reward, cue and punish channels
reward_chan = p['rewardChannels'][this_stim_idx]
trials['results'][trial_num]['reward_channel'] = reward_chan
cue_chan = p['cueChannels'][this_stim_idx]
punish_chan = p['punishChannels'][this_stim_idx]
# auto reward?
auto_reward = p['autoRewards'][this_stim_idx]
if p['autoForceReward']:
if trial_num >= p['autoForceRewardAfter']:
if np.sum(trials['running_score'][trial_num-p['autoForceRewardAfter']:trial_num]) <= 0:
auto_reward = True
trials['results'][trial_num]['auto_reward'] = auto_reward
# add in here the option to trigger auto reward if previous X trials were wrong
# generate withold requirement (if enabled)
if p['witholdBeforeStim']:
withold_min = p['witholdBeforeStimDuration'] - p['witholdBeforeStimRandomise']
withold_max = p['witholdBeforeStimDuration'] + p['witholdBeforeStimRandomise']
withold_req = np.random.uniform(withold_min, withold_max)
else:
withold_req = 0
trials['results'][trial_num]['withold_req'] = withold_req
# get random pre stim delay (if enabled)
pre_stim_delay_min = p['startToStimDelay'] - p['startToStimDelayRandomise']
pre_stim_delay_max = p['startToStimDelay'] + p['startToStimDelayRandomise']
pre_stim_delay = np.random.uniform(pre_stim_delay_min, pre_stim_delay_max)
trials['results'][trial_num]['pre_stim_delay'] = pre_stim_delay
# get random post stim delay (if enabled)
post_stim_delay_min = p['postStimDelay'] - p['postStimDelayRandomise']
post_stim_delay_max = p['postStimDelay'] + p['postStimDelayRandomise']
post_stim_delay = np.random.uniform(post_stim_delay_min, post_stim_delay_max)
trials['results'][trial_num]['post_stim_delay'] = post_stim_delay
stim_start = pre_stim_delay
stim_stop = stim_start + p['stimLength']
response_start = pre_stim_delay + post_stim_delay
response_stop = response_start + p['responseWindow']
response_cue_start = response_start
auto_reward_start = pre_stim_delay + p['autoRewardDelay']
# do trigger timings
do_trigger = p['triggers'][this_stim_idx]
trigger_start = 0
if p['triggerRelativeStim']:
trigger_start = stim_start + p['triggerTiming']
else:
trigger_start = response_start + p['triggerTiming']
# construct arduino config string. Format = <KEY:value;KEY:value;>
config_string = '<' + \
'STIM_CHAN:' + \
str(this_stim) + ';' \
'STIM_VAR:' + \
str(this_var) + ';' \
'RESP_REQ:' + \
str(resp_req) + ';' \
'REWARD_CHAN:' + \
str(reward_chan) + ';' \
'TRIAL_CUE:' + \
str(int(p['cueTrial'])) + ';' \
'TRIAL_STARTED_CUE:' + \
str(int(p['cueTrialActuallyStarted'])) + ';' \
'STIM_CUE:' + \
str(int(p['cueStim'])) + ';' \
'RESP_CUE:' + \
str(int(p['cueResponse'])) + ';' \
'RESP_CUE_START:' + \
str(int(response_start*1000)) + ';' \
'WITHOLD:' + \
str(int(p['witholdBeforeStim'])) + ';' \
'WITHOLD_REQ:' + \
str(int(withold_req*1000)) + ';' \
'STIM_START:' + \
str(int(stim_start*1000)) + ';' \
'STIM_STOP:' + \
str(int(stim_stop*1000)) + ';' \
'RESP_START:' + \
str(int(response_start*1000)) + ';' \
'RESP_STOP:' + \
str(int(response_stop*1000)) + ';' \
'TRIAL_DURATION:' + \
str(int(p['trialDuration']*1000)) + ';' \
'AUTO_REWARD:' + \
str(int(auto_reward)) + ';' \
'AUTO_REWARD_START:' + \
str(int(auto_reward_start*1000)) + ';' \
'PUNISH_TRIGGER:' + \
str(int(p['punishTrigger'])) + ';' \
'PUNISH_CHAN:' + \
str(punish_chan) + ';' \
'PUNISH_DELAY:' + \
str(int(p['punishDelay'])) + ';' \
'PUNISH_DELAY_LENGTH:' + \
str(int(p['punishDelayLength']*1000)) + ';' \
'REWARD_REMOVAL:' + \
str(int(p['rewardRemoval'])) + ';' \
'REWARD_REMOVAL_DELAY:' + \
str(int(p['rewardRemovalDelay']*1000)) + ';' \
'CUE_CHAN:' + \
str(cue_chan) + ';' \
'POST_STIM_CANCEL:' + \
str(int(post_stim_cancel)) + ';' \
'SECOND_CHANCE:' + \
str(int(second_chance)) + ';' \
'REWARD_DURATION:' + \
str(int(p['rewardDuration']*1000)) + ';' \
'PUNISH_TRIGGER_DURATION:' + \
str(int(p['punishTriggerDuration']*1000)) + ';' \
'RUN_TO_INITIATE:' + \
str(int(p['runToInitiate'])) + ';' \
'RUN_DURATION:' + \
str(int(p['runDuration']*1000)) + ';' \
'RUN_SPEED_THRESHOLD:' + \
str(int(p['runSpeedThreshold'])) + ';' \
'RUN_RESET_TIME:' + \
str(int(p['runResetTime']*1000)) + ';' \
'RUN_STOP_TO_START:' + \
str(int(p['runStopToStart'])) + ';' \
'RUN_STOP_DURATION:' + \
str(int(p['runStopDuration']*1000)) + ';' \
'DO_TRIGGER:' + \
str(int(do_trigger)) + ';' \
'TRIGGER_START:' + \
str(int(trigger_start*1000)) + ';' \
'REQUIRE_X_RESPS:' + \
str(int(require_x_resps)) + ';' \
'>'
# write config string to arduino
arduino_ready = 0
while not arduino_ready:
try:
write_string = '@?'
self.comm_feed_signal.emit(write_string, 'pc')
arduino['device'].write(write_string.encode('utf-8'))
temp_read = arduino['device'].readline().strip().decode('utf-8')
self.comm_feed_signal.emit(temp_read, 'arduino')
if temp_read == '{!}':
arduino_ready = 1
write_string = config_string
self.comm_feed_signal.emit(write_string, 'pc')
arduino['device'].write(write_string.encode('utf-8'))
temp_read = arduino['device'].readline().strip().decode('utf-8')
self.comm_feed_signal.emit(temp_read, 'arduino')
except Exception as e:
logger.exception(e)
self.comm_feed_signal.emit('Something went wrong', 'pc')
self.comm_feed_signal.emit(str(e), 'pc')
self.disconnectArduino()
self.connectArduino()
# signals allow communication between the TrialRunner thread and GUI thread. i.e. send data to main GUI thread where it can be displayed and saved. I don't know why they are here outside of any function...
response_signal = pyqtSignal(int, float, int, str, bool, name='responseSignal')
state_signal = pyqtSignal(str, name='stateSignal')
results_signal = pyqtSignal(int, name='resultsSignal')
trial_start_signal = pyqtSignal(int, name='trialStartSignal')
trial_end_signal = pyqtSignal(int, name='trialEndSignal')
session_end_signal = pyqtSignal(name='sessionEndGUISignal')
arduino_connected_signal = pyqtSignal(name='arduinoConnectedSignal')
arduino_disconnected_signal = pyqtSignal(name='arduinoDisconnectedSignal')
comm_feed_signal = pyqtSignal(str, str, name='commFeedSignal')
def receiveData(self, trial_num):
'''
The worker thread will sit in a while loop processing incoming
communication from the arduino, appending data to the results,
unitl the arduino says it has finished the trial.
'''
trials['results'][trial_num]['trialstart'] = time.strftime('%Y%m%d_%H%M%S')
trialRunning = True
session_state = 'PRETRIAL'
is_first_response = True
actual_trial_started = False
while trialRunning:
if actual_trial_started:
trial_elapsed = time.time() - trial_started
# print(trial_elapsed)
if trial_elapsed > 5 * p['trialDuration']:
print('********************************')
print('OH NO, SOMETHING IS UNRESPONSIVE')
print('********************************')
if arduino['connected'] == False:
self.comm_feed_signal.emit('Arduino not connected', 'pc')
trials['running_score'][trial_num] = 0
trialRunning = False # abort current trial if arduino disconnects
try:
temp_read1 = arduino['device'].readline()
temp_read2 = temp_read1.strip()
temp_read = temp_read2.decode('utf-8')
if temp_read:
self.comm_feed_signal.emit(temp_read, 'arduino')
if temp_read[0] == '<' and temp_read[-1] == '>': # whole data packet received
temp_read = temp_read[1:-1] # only process everything between < and >
data = temp_read.split('|')
for idx, val in enumerate(data):
if val: # in val is not just
ID, val = val.split(':')
val = float(val) / 1000
if ID == '*':
actual_trial_started = True
trial_started = time.time()
session_state = 'INTRIAL'
trials['results'][trial_num]['responses'][0] = [x - val for x in trials['results'][trial_num]['responses'][0]]
trials['results'][trial_num]['withold_act'] = val
self.state_signal.emit(session_state)
else:
ID = int(ID)
trials['results'][trial_num]['responses'][0].append(val) # time
trials['results'][trial_num]['responses'][1].append(ID) # channel
self.response_signal.emit(trial_num, val, ID, session_state, is_first_response)
if session_state == 'INTRIAL':
is_first_response = False # first response has now happened
elif temp_read[0] == '{' and temp_read[-1] == '}': # whole trial outcome packet received
temp_read = temp_read[1:-1] # only process everything between { and }
if temp_read == 'DONE':
trialRunning = False
state = temp_read
self.state_signal.emit(state)
elif temp_read == 'READY': # arduino has reset
trialRunning = False
else:
data = temp_read.split('|')
for idx, val in enumerate(data):
if val: # in val is not just
# firstresponse, correct, incorrect, miss, cheated
key, val = val.split(':')
val = int(val)
key = str(key)
trials['results'][trial_num][key] = val
if trials['results'][trial_num]['correct']:
score = 1
trials['correct_tally'] += 1
elif trials['results'][trial_num]['incorrect']:
score = -1
trials['correct_tally'] = 0
else: # miss
score = 0
trials['running_score'][trial_num] = score
self.results_signal.emit(trial_num)
elif temp_read == 'stim on' or temp_read == 'stim off' or temp_read == 'response window open' or temp_read == 'response window closed' or temp_read == 'waiting for withold':
state = temp_read
self.state_signal.emit(state)
except Exception as e:
logger.exception(e)
if self._session_running:
self.comm_feed_signal.emit('Something went wrong', 'pc')
self.comm_feed_signal.emit(str(e), 'pc')
# self.connectArduino()
# trials['running_score'][trial_num] = 0
# trialRunning = False
msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
msg.setText("Error")
msg.setInformativeText(e)
msg.setWindowTitle("Error")
print(temp_read1)
print(temp_read2)
print(temp_read)
self.comm_feed_signal.emit(str(temp_read1), 'pc')
self.comm_feed_signal.emit(str(temp_read2), 'pc')
self.comm_feed_signal.emit(str(temp_read), 'pc')
dict = {}
dict['temp_read'] = temp_read
dict['temp_read1'] = temp_read1
dict['temp_read2'] = temp_read2
save_name = 'errordump' + time.strftime('%Y%m%d_%H%M%S')
sio.savemat(save_name + '.mat', dict)
def stop(self):
if self._session_running:
self._session_running = False # will stop while loop
self.disconnectArduino()
self.session_end_signal.emit() # will update gui
class MainWindow(QMainWindow, GUI.Ui_MainWindow):
'''
The GUI window
'''
def __init__(self):
QMainWindow.__init__(self)
self._gui_ready = False
self.setupUi(self)
# create the worker thread (run trials in the background)
self.trialThread = QThread()
self.trialRunner = TrialRunner()
self.trialRunner.moveToThread(self.trialThread)
self.trialThread.started.connect(self.trialRunner.startSession)
self.trialThread.start()
# make colormaps
self.NUM_STIMS = 8
self.NUM_VARS = 16
self.defineColormaps()
# place figure widgets
self.addFigures()
# configure existing widgets programmatically
self.device_ComboBox.addItems(available_devices)
if available_configs != []:
self.loadPreset_ComboBox.addItems(available_configs)
self.loadPreset_ComboBox.removeItem(0)
self.autoTransitionTo_ComboBox.addItems(available_configs)
self.autoTransitionTo_ComboBox.removeItem(0)
self.stimOrder_ComboBox.model().item(2).setEnabled(False)
# set up dictionaries
self.defaults = {}
self.trial_config = {}
self.trial_log = []
# open the config file and populate GUI with values
self.GUIRestore()
# signal/slot connections
self.setConnects()
self.loadPreset()
# ready
self._gui_ready = True
def defineColormaps(self):
# define colormap for different stims
self.cmap_stims = cm.get_cmap(name='Spectral_r', lut=self.NUM_STIMS)
# define colormap for score bars
low = [1, 0.1, 0.4]
mid = [.8, .8, .8]
high = [0, 0.85, 0.45]
colors = [low, mid, high]
n_bins = 100
self.cmap_score = LinearSegmentedColormap.from_list('hitmiss', colors, N=n_bins)
#self.cmap_score = cm.get_cmap(name='coolwarm', lut=n_bins)
# define colormap for response
low = [0,0,0]
# high = [0.6,0.6,0.6]
high = [1,1,1]
colors = [low, high]
n_bins = 100
self.cmap_resps = LinearSegmentedColormap.from_list('resps', colors, N=n_bins)
# self.cmap_resps = cm.get_cmap(name='Spectral_r', lut=100)
# self.cmap_resps = cm.get_cmap(name='gray')
def sessionTimerUpdate(self):
elapsed_time = int((time.time() - p['sessionStartTime']) * 1000)
s,ms = divmod(elapsed_time, 1000)
m, s = divmod(s, 60)
h, m = divmod(m, 60)
self.sessionTimer_label.setText('%d:%02d:%02d.%d' % (h, m, s, int(ms/100)))
def begin(self):
if self.trialRunner._session_running is False:
# reset everything
self.begin_Button.setEnabled(False)
self.tabWidget.setCurrentIndex(1)
self.sessionAbort_pushButton.setEnabled(True)
self.forceReward_pushButton.setEnabled(True)
self.reset()
p['sessionStartTime'] = time.time()
p['sessionStartTimeString'] = time.strftime('%Y%m%d_%H%M%S')
p['sessionID'] = p['subjectID'] + '_' + p['sessionStartTimeString']
self.setWindowTitle('PyBehaviour - ' + p['sessionID'])
self.sessionTimer.start(10) # start the QTimer, executes every 100ms
self.sessionTimer_label.setStyleSheet('font-size: 18pt; font-weight: bold; color:''black'';')
self.trialRunner._session_running = True
logger.info('Started session: ' + p['sessionID'])
num_stims = len(p['stimChannels'])
#f, axs = self.reactionTimesCanvas.subplots(1, num_stims, sharey=True)
# self.reactionTimesFig.clf()
# ax = list()
# for i in range(num_stims):
# if i > 0:
# ax.append(self.reactionTimesFig.add_subplot(1,num_stims,i+1, sharey=ax[0]))
# ax[-1].set_yticklabels('')
# ax[-1].set_title(str(i+1))
# else:
# ax.append(self.reactionTimesFig.add_subplot(1,num_stims,i+1))
# ax[-1].set_ylabel('Count')
# ax[-1].set_title(str(i+1))
# self.reactionTimesCanvas.draw()
def reset(self):
self.trialRunner.trial_num = 0
NUM_STIMS = 8
num_stims = len(p['stimChannels'])
num_trials = p['sessionDuration']
num_max_variations = int(max(p['trialVariations']) +1)
# reset perfromance plots
plots = [self.runningScorePlot, self.averageScorePlot]
for plot in plots:
plot.set_data([np.empty(0), np.empty(0)])
# reset raster plots
plots = [self.preTrialRaster_responses, self.raster_responses]
for plot in plots:
plot.set_offsets(np.empty(0))
plot.set_array(np.empty(0))
plot.set_sizes(np.empty(0))
global plot_data
plot_data = {}
plot_data['offsets'] = np.empty([0,2])
# self.raster_current_trial.set_data([0,0])
self.raster_current_trial.set_xdata(self.rasterFigAx.get_xlim())
self.raster_current_trial.set_ydata(np.empty(0))
self.CurrentTrialSorted = 0
# reset the performance block plots
self.rasterFigPerfAxIm.set_data(np.full([num_trials,num_stims], np.nan))
self.rasterFigPerfAxVarIm.set_data(np.full([num_trials,num_stims], np.nan))
self.performanceFigPerfAxIm.set_data(np.full([num_stims,num_trials], np.nan))
# reset the trial results dictionary
global trials
trials = {}
trials['results'] = []
trials['running_score'] = np.full([num_trials,1], np.nan)
trials['reaction_time'] = np.full([num_trials,1], np.nan)
trials['correct_tally'] = 0 # not currently used, but will be used for auto incrementing
self.trial_log = []
# reset reaction time hists
self.hist_bins = np.arange(0, p['trialDuration']+0.05, 0.05)
counts,edges = np.histogram(trials['reaction_time'], bins=self.hist_bins, range=[np.nanmin(self.hist_bins), np.nanmax(self.hist_bins)])
for stim in range(NUM_STIMS):
self.reactionTimeHists[stim].set_xy(np.empty([1,2]))
#self.reactionTimeHists[stim].set_xy(np.hstack([np.random.rand(4,1), np.random.randint(0,5,[4,1])]))
if stim+1 in p['stimChannels']:
self.reactionTimeHists[stim].set_visible(True)
else:
self.reactionTimeHists[stim].set_visible(False)
# reset summary results plot
if num_max_variations > 1:
self.summaryResultsAx.set_xlabel('Variation')
self.summaryResultsAx.set_xlim([-1,num_max_variations])
self.summaryResultsAx.set_xticks(np.arange(0,num_max_variations))
self.summaryResultsAx.set_xticklabels(np.arange(0,num_max_variations)+1)
else:
self.summaryResultsAx.set_xlabel('Stimulus type')
self.summaryResultsAx.set_xlim([-1,num_stims])
self.summaryResultsAx.set_xticks(np.arange(0,num_stims))
self.summaryResultsAx.set_xticklabels(np.arange(0,num_stims)+1)
for stim in range(self.NUM_STIMS):
self.summaryResultsPlot[stim].set_xdata(np.nan)
self.summaryResultsPlot[stim].set_ydata(np.nan)
for var in range(self.NUM_VARS):
self.summaryResultsPlotErr[stim][var].set_xdata(np.nan)
self.summaryResultsPlotErr[stim][var].set_ydata(np.nan)
if stim+1 in p['stimChannels']:
self.summaryResultsPlot[stim].set_visible(True)
else:
self.summaryResultsPlot[stim].set_visible(False)
self.updatePlotLayouts()
def pause(self):
self.trialRunner._paused = not self.trialRunner._paused
if self.trialRunner._paused:
self.updateCommFeed('Paused', 'session')
self.sessionPause_pushButton.setText('Resume')
else:
self.updateCommFeed('Resumed', 'session')
self.sessionPause_pushButton.setText('Pause')
def abort(self):
if self.trialRunner._session_running:
self.trialRunner._session_running = False
# self.sessionEndGUI()
self.updateCommFeed('Aborted', 'session')
self.sessionAbort_pushButton.setEnabled(False)
self.forceReward_pushButton.setEnabled(False)
def forceReward(self):
if self.trialRunner._session_running is False:
self.updateCommFeed('Force current reward only works while session is running', 'pc')
if self.trialRunner._session_running is True:
self.updateCommFeed('Forcing current reward', 'pc')
write_string = '@R' # arduino knows this means deliver reward
self.updateCommFeed(write_string, 'pc')
arduino['device'].write(write_string.encode('utf-8'))
def updatePlotLayouts(self):
self.preTrialRasterFigAx.set_xlim(0, np.max([1, p['witholdBeforeStimPlotVal']]))
num_trials = p['sessionDuration']
trial_num = self.trialRunner.trial_num
if self.trialRunner._session_running:
self.updateResultBlockPlots(trial_num)
if p['autoScalePlots']:
if not self.trialRunner._session_running:
trials_ax_lim = [0, trial_num+1]
else:
trials_ax_lim = [0, trial_num+2]
else:
trials_ax_lim = [0, num_trials+1]
if trials_ax_lim[1] < 5:
trials_ax_lim[1] =5
if not self.trialRunner._session_running:
self.raster_current_trial.set_xdata(np.empty(0))
self.raster_current_trial.set_ydata(np.empty(0))
# response raster
pre_stim_plot = 1
self.rasterFigAx.set_xlim(-pre_stim_plot, p['trialDuration'])
self.rasterFigAx.set_ylim(trials_ax_lim[0], trials_ax_lim[1])
self.raster_respwin.set_x(p['responseStart'])
self.raster_respwin.set_width(p['responseWindow'])
self.raster_respwin.set_height(trials_ax_lim[1]+1)
self.raster_stimline.set_ydata(trials_ax_lim)
self.raster_stimlength.set_x(p['stimStart'])
self.raster_stimlength.set_width(p['stimLength'])
self.raster_stimlength.set_height(trials_ax_lim[1]+1)
self.raster_autorewardline.set_ydata(trials_ax_lim)
self.raster_autorewardline.set_xdata([p['autoRewardStart'], p['autoRewardStart']])
self.raster_autorewardline.set_alpha(int(np.any(p['autoRewards'])))
# reaction time plot
rxn_plot_ylim = self.reactionTimesAx.get_ylim()
self.rxn_respwin.set_x(p['responseStart'])
self.rxn_respwin.set_width(p['responseWindow'])
self.rxn_respwin.set_height(rxn_plot_ylim[1])
self.rxn_stimline.set_ydata(rxn_plot_ylim)
self.rxn_stimlength.set_x(p['stimStart'])
self.rxn_stimlength.set_width(p['stimLength'])
self.rxn_stimlength.set_height(rxn_plot_ylim[1])
self.rxn_autorewardline.set_ydata(rxn_plot_ylim)
self.rxn_autorewardline.set_xdata([p['autoRewardStart'], p['autoRewardStart']])
self.rxn_autorewardline.set_alpha(int(np.any(p['autoRewards'])))
# performance line
if p['negativeMarking'] == 0:
self.performanceFigAx.set_ylim([0, 1])
self.performanceFigAx.set_ylabel('Correct (%)')
self.performanceFigAx.set_yticks(np.linspace(0, 1, 11))
self.performanceFigAx.set_yticklabels([0,'',20,'',40,'',60,'',80,'',100])
self.summaryResultsAx.set_ylim([0, 1])
self.summaryResultsAx.set_ylabel('Correct (%)')
self.summaryResultsAx.set_yticks(np.linspace(0, 1, 11))
self.summaryResultsAx.set_yticklabels([0,'',20,'',40,'',60,'',80,'',100])
self.chance_line1.set_ydata([0.5,0.5])
self.chance_line2.set_ydata([0.5,0.5])
#self.summaryResultsIm.set_clim([0,1])
else:
self.performanceFigAx.set_ylim([-1, 1])
self.performanceFigAx.set_ylabel('Score (%)')
self.performanceFigAx.set_yticks(np.linspace(-1, 1, 9))
self.performanceFigAx.set_yticklabels([-100, -75, -50, -25, 0, 25, 50, 75, 100])
self.summaryResultsAx.set_ylim([-1, 1])
self.summaryResultsAx.set_ylabel('Score (%)')
self.summaryResultsAx.set_yticks(np.linspace(-1, 1, 9))
self.summaryResultsAx.set_yticklabels([-100, -75, -50, -25, 0, 25, 50, 75, 100])
self.chance_line1.set_ydata([0,0])
self.chance_line2.set_ydata([0,0])
#self.summaryResultsIm.set_clim([-1,1])
self.performanceFigAx.set_xlim(trials_ax_lim[0], trials_ax_lim[1])
self.chance_line1.set_xdata(trials_ax_lim)
self.chance_line2.set_xdata([-1,16])
# performance blocks
if self.trialRunner._session_running:
if np.any(p['trialVariations']):
num_max_variations = int(max(p['trialVariations']))
else:
num_max_variations = 0
self.rasterFigPerfAxVarIm.set_clim([0,num_max_variations])
self.rasterFigPerfAxIm.set_extent( [0,0.75, (0.5/trials_ax_lim[1]),(num_trials/trials_ax_lim[1])+(0.5/trials_ax_lim[1])])
self.rasterFigPerfAxVarIm.set_extent([0.85,1, (0.5/trials_ax_lim[1]),(num_trials/trials_ax_lim[1])+(0.5/trials_ax_lim[1])])
self.performanceFigPerfAxIm.set_extent([(0.5/trials_ax_lim[1]),(num_trials/trials_ax_lim[1])+(0.5/trials_ax_lim[1]), 0,1])
self.preTrialRasterFigCanvas.draw()
self.rasterFigCanvas.draw()
self.performanceFigCanvas.draw()
# self.preTrialRasterFigCanvas.update() # need to add all the other elements like the lines and rectangles!
# self.rasterFigCanvas.update()
# self.performanceFigCanvas.update()
# self.preTrialRasterFigCanvas.flush_events()
# self.rasterFigCanvas.flush_events()
# self.performanceFigCanvas.flush_events()
def updateRasterPlotData(self, trial_num, val, ID, state, is_first_response):
if state == 'INTRIAL':
plot_series = self.raster_responses
ax = self.rasterFigAx
canvas = self.rasterFigCanvas
x = val
y = self.CurrentTrialSorted
# update plot_data dictionary record
plot_data['offsets'] = np.vstack((plot_data['offsets'], [x, trial_num+1]))
elif state == 'PRETRIAL':
plot_series = self.preTrialRaster_responses
ax = self.preTrialRasterFigAx
canvas = self.preTrialRasterFigCanvas
x = val
y = 0
if x > trials['results'][trial_num]['withold_req']:
ax.set_xlim([0, x])
canvas.draw()
if is_first_response:
new_size = 30
opacity = 1
# update reaction time histogram
trials['reaction_time'][trial_num] = val
stim_type = int(p['trialOrder'][trial_num])
rxn_times = trials['reaction_time']
rxn_times = rxn_times[p['trialOrder']==stim_type]
counts,edges = np.histogram(rxn_times, bins=self.hist_bins, range=[np.nanmin(self.hist_bins), np.nanmax(self.hist_bins)])
counts = np.hstack([counts, np.array([0])])
self.reactionTimeHists[stim_type-1].set_xy(np.vstack([edges, counts]).T)
self.reactionTimesAx.set_ylim([0, max(counts.max()+1, max(self.reactionTimesAx.get_ylim()))])
# self.reactionTimesAxd.raw_artist(self.reactionTimeHists[stim_type])
else:
new_size = 8
opacity = 0.1
# get old data
old_xy = plot_series.get_offsets()
old_sizes = plot_series.get_sizes()
old_colours = plot_series.get_array()
# make new data
new_xy = np.vstack((old_xy, [x,y]))
new_sizes = np.append(old_sizes, new_size)
new_colours = np.append(old_colours, ID)
# set new data
plot_series.set_offsets(new_xy)
plot_series.set_sizes (new_sizes)
plot_series.set_array (new_colours)
# # update/draw plots
ax.draw_artist(plot_series)
canvas.update()
canvas.flush_events()
def updateStatePlot(self, state):
if state == 'stim on':
self.raster_stimlength.set_facecolor([0.9,0.8,0.1, 0.1])
self.rasterFigCanvas.draw()
elif state == 'stim off':
self.raster_stimlength.set_facecolor([0,0,0, 0.05])
self.rasterFigCanvas.draw()
elif state == 'response window open':
self.raster_respwin.set_facecolor([0.9,0.8,0.1, 0.1])
self.rasterFigCanvas.draw()
elif state == 'response window closed':
self.raster_respwin.set_facecolor([0,0,0, 0.05])
self.rasterFigCanvas.draw()
elif state == 'waiting for withold':
ax = self.preTrialRasterFigAx
spine_names = ['top','bottom','left','right']
for spine in spine_names:
ax.spines[spine].set_color([1,.6,.6])
self.preTrialRasterFigCanvas.draw()
elif state == 'INTRIAL':
ax1 = self.preTrialRasterFigAx
ax2 = self.rasterFigAx
spine_names = ['top','bottom','left','right']
for spine in spine_names:
ax1.spines[spine].set_color([.95, .95, .95])
ax2.spines[spine].set_color([1,.6,.6])
self.preTrialRasterFigCanvas.draw()
self.rasterFigCanvas.draw()
elif state == 'DONE':
ax = self.rasterFigAx
spine_names = ['top','bottom','left','right']
for spine in spine_names:
ax.spines[spine].set_color([.95, .95, .95])
self.rasterFigCanvas.draw()
def summaryResults(self, trial_num):
# get details
score = np.copy(trials['running_score'][:trial_num+1])
trial_order = p['trialOrder'][:trial_num+1]
variations = p['trialVariations'][:trial_num+1]
num_diff_stims = len(p['stimChannels'])
num_max_variations = int(max(p['trialVariations']) +1)
# initialise
results = np.full([num_max_variations, num_diff_stims], np.nan)
errs_hi = np.full([num_max_variations, num_diff_stims], np.nan)
errs_lo = np.full([num_max_variations, num_diff_stims], np.nan)
# compute results
if not p['negativeMarking']:
score[score<0] = 0
for stim_idx,stim_num in enumerate(p['stimChannels']):
for var in range(num_max_variations):
values = score[(trial_order==stim_num) & (variations==var)]
if len(values) > 0:
# calculations
count = np.float(sum(values==1))
ntrials = np.float(len(values))
mu = np.nanmean(values)
sd = np.nanstd(values)
sem = sd / np.sqrt(ntrials)
ci_lo, ci_hi = proportion_confint(count, ntrials, alpha=0.1)
if ntrials < 5:
sd = 0
sem = 0
ci_lo = mu
ci_hi = mu
# mean
results[var, stim_idx] = mu
# confidence intervals
errs_lo[var, stim_idx] = ci_lo
errs_hi[var, stim_idx] = ci_hi
# # std dev
# errs_lo[var, stim_idx] = mu - sd
# errs_hi[var, stim_idx] = mu + sd
# # sem
# errs_lo[var, stim_idx] = mu - sem
# errs_hi[var, stim_idx] = mu + sem
# update plot
for stim_idx,stim_num in enumerate(p['stimChannels']):
if num_max_variations > 1:
x = np.arange(0,num_max_variations)
else:
x = [stim_idx]
y = results[:,stim_idx]
yerr_hi = errs_hi[:,stim_idx]
yerr_lo = errs_lo[:,stim_idx]
self.summaryResultsPlot[stim_num-1].set_ydata(y)
self.summaryResultsPlot[stim_num-1].set_xdata(x)
for erridx in range(len(y)):
self.summaryResultsPlotErr[stim_num-1][erridx].set_ydata([yerr_lo[erridx], yerr_hi[erridx]])
self.summaryResultsPlotErr[stim_num-1][erridx].set_xdata([x[erridx], x[erridx]])