forked from robertoostenveld/pymindaffectBCI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselectionMatrix.py
More file actions
1596 lines (1371 loc) · 67.6 KB
/
selectionMatrix.py
File metadata and controls
1596 lines (1371 loc) · 67.6 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 python3
# Copyright (c) 2019 MindAffect B.V.
# Author: Jason Farquhar <jason@mindaffect.nl>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# get the general noisetagging framework
import os
from mindaffectBCI.noisetag import Noisetag, PredictionPhase
from mindaffectBCI.utopiaclient import DataPacket
from mindaffectBCI.decoder.utils import search_directories_for_file
# graphic library
import pyglet
window = None
ss = None
nframe = None
isi = 1/60
drawrate = 0 # rate at which draw is called
class Screen:
'''Screen abstract-class which draws stuff on the screen until finished'''
def __init__(self, window):
self.window = window
def reset(self):
'''reset this screen to clean state'''
pass
def draw(self, t):
'''draw the display, N.B. NOT including flip!'''
pass
def is_done(self):
'''test if this screen wants to quit'''
return False
#-----------------------------------------------------------------
#-----------------------------------------------------------------
#-----------------------------------------------------------------
#-----------------------------------------------------------------
class InstructionScreen(Screen):
'''Screen which shows a textual instruction for duration or until key-pressed'''
def __init__(self, window, text, duration=5000, waitKey=True, logo="MindAffect_Logo.png"):
super().__init__(window)
self.t0 = None # timer for the duration
self.duration = duration
self.waitKey = waitKey
self.isRunning = False
self.isDone = False
self.clearScreen = True
# initialize the instructions screen
self.instructLabel = pyglet.text.Label(x=self.window.width//2,
y=self.window.height//2,
anchor_x='center',
anchor_y='center',
font_size=24,
color=(255, 255, 255, 255),
multiline=True,
width=int(self.window.width*.8))
self.set_text(text)
# add the framerate box
self.framerate=pyglet.text.Label("", font_size=12, x=self.window.width, y=self.window.height,
color=(255, 255, 255, 255),
anchor_x='right', anchor_y='top')
self.logo = None
if isinstance(logo,str): # filename to load
logo = search_directories_for_file(logo,
os.path.dirname(os.path.abspath(__file__)),
os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','..'))
try:
logo = pyglet.image.load(logo)
except:
logo = None
if logo:
logo.anchor_x, logo.anchor_y = (logo.width,logo.height) # anchor top-right
self.logo = pyglet.sprite.Sprite(logo,self.window.width,self.window.height-16)
self.logo.update(scale_x=self.window.width*.1/logo.width,
scale_y=self.window.height*.1/logo.height)
def reset(self):
self.isRunning = False
self.isDone = False
def set_text(self, text):
'''set/update the text to show in the instruction screen'''
if type(text) is list:
text = "\n".join(text)
self.instructLabel.begin_update()
self.instructLabel.text=text
self.instructLabel.end_update()
def is_done(self):
# check termination conditions
if not self.isRunning:
self.isDone = False
return self.isDone
if self.waitKey:
#global last_key_press
if self.window.last_key_press:
self.key_press = self.window.last_key_press
self.isDone = True
self.window.last_key_press = None
if self.elapsed_ms() > self.duration:
self.isDone = True
return self.isDone
def elapsed_ms(self):
return getTimeStamp()-self.t0
def draw(self, t):
'''Show a block of text to the user for a given duration on a blank screen'''
if not self.isRunning:
self.isRunning = True # mark that we're running
self.t0 = getTimeStamp()
if self.clearScreen:
self.window.clear()
self.instructLabel.draw()
# check if should update display
# TODO[]: only update screen 1x / second
global flipstats
flipstats.update_statistics()
self.framerate.begin_update()
self.framerate.text = "{:4.1f} +/-{:4.1f}ms".format(flipstats.median,flipstats.sigma)
self.framerate.end_update()
self.framerate.draw()
if self.logo: self.logo.draw()
#-----------------------------------------------------------------
#-----------------------------------------------------------------
#-----------------------------------------------------------------
#-----------------------------------------------------------------
#-----------------------------------------------------------------
class MenuScreen(InstructionScreen):
'''Screen which shows a textual instruction for duration or until key-pressed'''
def __init__(self, window, text, valid_keys):
super().__init__(window, text, 99999999, True)
self.menu_text = text
self.valid_keys = valid_keys
self.key_press = None
#print("Menu")
def set_message(self,message:str):
self.set_text(self.menu_text+'\n\n\n'+message)
def is_done(self):
# check termination conditions
if not self.isRunning:
self.isDone = False
return self.isDone
# valid key is pressed
global last_key_press
if self.window.last_key_press:
self.key_press = self.window.last_key_press
if self.key_press in self.valid_keys:
self.isDone = True
self.window.last_key_press = None
# time-out
if self.elapsed_ms() > self.duration:
self.isDone = True
return self.isDone
#-----------------------------------------------------------------
#-----------------------------------------------------------------
#-----------------------------------------------------------------
#-----------------------------------------------------------------
#-----------------------------------------------------------------
class ResultsScreen(InstructionScreen):
'''Modified instruction screen with waits for and presents calibration results'''
waiting_text = "Waiting for performance results from decoder\n\nPlease wait"
results_text = "Calibration Performance: %3.0f%% Correct\n\nKey to continue"
def __init__(self, window, noisetag, duration=20000, waitKey=False):
super().__init__(window, self.waiting_text, duration, waitKey)
self.noisetag = noisetag
self.pred = None
def reset(self):
self.noisetag.clearLastPrediction()
self.pred = None
super().reset()
def draw(self, t):
'''check for results from decoder. show if found..'''
if not self.isRunning:
self.reset()
# check for new predictions
pred = self.noisetag.getLastPrediction()
# update text if got predicted performance
if pred is not None and (self.pred is None or pred.timestamp > self.pred.timestamp) :
self.pred = pred
print("Prediction:{}".format(self.pred))
self.waitKey = True
self.set_text(self.results_text%((1.0-self.pred.Perr)*100.0))
super().draw(t)
#-----------------------------------------------------------------
#-----------------------------------------------------------------
#-----------------------------------------------------------------
#-----------------------------------------------------------------
#-----------------------------------------------------------------
class ConnectingScreen(InstructionScreen):
'''Modified instruction screen with waits for the noisetag to connect to the decoder'''
prefix_text = "Welcome to the mindaffectBCI\n\n"
searching_text = "Searching for the mindaffect decoder\n\nPlease wait"
trying_text = "Trying to connect to: %s\n Please wait"
connected_text = "Success!\nconnected to: %s"
query_text = "Couldnt auto-discover mindaffect decoder\n\nPlease enter decoder address: %s"
drawconnect_timeout_ms = 50
autoconnect_timeout_ms = 5000
def __init__(self, window, noisetag, duration=150000):
super().__init__(window, self.prefix_text + self.searching_text, duration, False)
self.noisetag = noisetag
self.host = None
self.port = -1
self.usertext = ''
self.stage = 0
def draw(self, t):
'''check for results from decoder. show if found..'''
global last_text, last_key_press
if not self.isRunning:
super().draw(t)
return
if not self.noisetag.isConnected():
if self.stage == 0: # try-connection
print('Not connected yet!!')
self.noisetag.connect(self.host, self.port,
queryifhostnotfound=False,
timeout_ms=self.drawconnect_timeout_ms)
if self.noisetag.isConnected():
self.set_text(self.prefix_text + self.connected_text%(self.noisetag.gethostport()))
self.t0 = getTimeStamp()
self.duration = 1000
self.noisetag.subscribe("MSPQ")
elif self.elapsed_ms() > self.autoconnect_timeout_ms:
# waited too long, giveup and ask user
self.stage = 1
# ensure old key-presses are gone
self.window.last_text = None
self.window.last_key_press = None
elif self.stage == 1: # query hostname
# query the user for host/port
# accumulate user inputs
if self.window.last_key_press:
if self.window.last_key_press == pyglet.window.key.BACKSPACE:
# remove last character
self.usertext = self.usertext[:-1]
self.window.last_key_press = None
if self.window.last_text:
print(self.window.last_text + ":" + str(ord(self.window.last_text)))
if self.window.last_text == '\n' or self.window.last_text == '\r':
# set as new host to try
self.host = self.usertext
self.usertext = ''
self.set_text(self.prefix_text + self.trying_text%(self.host))
self.stage = 0 # back to try-connection stage
elif self.window.last_text:
# add to the host string
self.usertext += last_text
self.window.last_text = None
if self.stage == 1: # in same stage
# update display with user input
self.set_text(self.prefix_text + self.query_text%(self.usertext))
super().draw(t)
#-----------------------------------------------------------------
#-----------------------------------------------------------------
#-----------------------------------------------------------------
#-----------------------------------------------------------------
#-----------------------------------------------------------------
class SettingsScreen(InstructionScreen):
'''Modified instruction screen to change various settings - selection threshold'''
prefix_text = "Configuration Settings\n\n"
threshold_text = "New Selection Threshold: %s\n"
def __init__(self, window, settings_class, duration=150000):
super().__init__(window, self.prefix_text + self.threshold_text%(settings_class.selectionThreshold), duration, False)
self.settings_class = settings_class
self.usertext = ''
def draw(self, t):
'''check for results from decoder. show if found..'''
global last_text, last_key_press
if not self.isRunning:
super().draw(t)
return
# query the user for host/port
# accumulate user inputs
if self.window.last_key_press:
if self.window.last_key_press == pyglet.window.key.BACKSPACE:
# remove last character
self.usertext = self.usertext[:-1]
self.window.last_key_press = None
if self.window.last_text:
print(self.window.last_text + ":" + str(ord(self.window.last_text)))
if self.window.last_text == '\n' or self.window.last_text == '\r':
# set as new host to try
try:
self.threshold = float(self.usertext)
self.settings_class.selectionThreshold=self.threshold
self.isDone = True
except ValueError:
# todo: flash to indicate invalid..
pass
elif self.window.last_text and self.window.last_text in "0123456789.":
# add to the host string
self.usertext += window.last_text
self.window.last_text = None
self.set_text(self.prefix_text + self.threshold_text%(self.usertext))
super().draw(t)
#-----------------------------------------------------------------
class QueryDialogScreen(InstructionScreen):
'''Modified instruction screen queries the user for textual input'''
def __init__(self, window, text, duration=50000, waitKey=True):
super().__init__(window, text, 50000, False)
self.query = text
self.usertext = ''
def draw(self, t):
'''check for results from decoder. show if found..'''
# query the user for host/port
# accumulate user inputs
global last_key_press, last_text
if self.window.last_key_press:
if self.window.last_key_press == pyglet.window.key.BACKSPACE:
self.usertext = self.usertext[:-1]
self.set_text(self.query +self.usertext)
self.window.last_key_press = None
if self.window.last_text:
if self.window.last_text == '\r' or self.window.last_text == '\n':
self.isDone = True
elif self.window.last_text:
# add to the host string
self.usertext += self.window.last_text
self.window.last_text=None
# update display with user input
self.set_text(self.query +self.usertext)
super().draw(t)
#-----------------------------------------------------------------
#-----------------------------------------------------------------
#-----------------------------------------------------------------
#-----------------------------------------------------------------
from math import log10
from collections import deque
class ElectrodequalityScreen(Screen):
'''Screen which shows the electrode signal quality information'''
instruct = "Electrode Quality\n\nAdjust headset until all electrodes are green\n(or noise to signal ratio < 5)"
def __init__(self, window, noisetag, nch=4, duration=3600*1000, waitKey=True):
super().__init__(window)
self.noisetag = noisetag
self.t0 = None # timer for the duration
self.duration = duration
self.waitKey = waitKey
self.clearScreen = True
self.isRunning = False
self.update_nch(nch)
self.dataringbuffer = deque() # deque so efficient sliding data window
self.datawindow_ms = 4000 # 5seconds data plotted
self.datascale_uv = 20 # scale of gap between ch plots
print("Electrode Quality (%dms)"%(duration))
def update_nch(self, nch):
self.batch = pyglet.graphics.Batch()
self.background = pyglet.graphics.OrderedGroup(0)
self.foreground = pyglet.graphics.OrderedGroup(1)
winw, winh = self.window.get_size()
r = (winh*.8)/(nch+1)
# TODO[X] use bounding box
self.chrect = (int(winw*.1), 0, r, r) # bbox for each signal, (x, y, w, h)
# make a sprite to draw the electrode qualities
img = pyglet.image.SolidColorImagePattern(color=(255, 255, 255, 255)).create_image(2, 2)
# anchor in the center to make drawing easier
img.anchor_x = 1
img.anchor_y = 1
self.sprite = [None]*nch
self.label = [None]*nch
self.linebbox = [None]*nch # bounding box for the channel line
for i in range(nch):
x = self.chrect[0]
y = self.chrect[1]+(i+1)*self.chrect[3]
# convert to a sprite and make the right size
self.sprite[i] = pyglet.sprite.Sprite(img, x=x, y=y,
batch=self.batch,
group=self.background)
# make the desired size
self.sprite[i].update(scale_x=r*.6/img.width, scale_y=r*.6/img.height)
# and a text label object
self.label[i] = pyglet.text.Label("%d"%(i), font_size=32,
x=x, y=y,
color=(255, 255, 255, 255),
anchor_x='center',
anchor_y='center',
batch=self.batch,
group=self.foreground)
# bounding box for the datalines
self.linebbox[i] = (x+r, y, winw-(x+r)-.5*r, self.chrect[3])
# title for the screen
self.title=pyglet.text.Label(self.instruct, font_size=32,
x=winw*.1, y=winh, color=(255, 255, 255, 255),
anchor_y="top",
width=int(winw*.9),
multiline=True,
batch=self.batch,
group=self.foreground)
def reset(self):
self.isRunning = False
def is_done(self):
# check termination conditions
isDone=False
if not self.isRunning:
return False
if self.waitKey:
global last_key_press
if self.window.last_key_press:
self.key_press = self.window.last_key_press
isDone = True
self.window.last_key_press = None
if getTimeStamp() > self.t0+self.duration:
isDone=True
if isDone:
self.noisetag.removeSubscription("D")
self.noisetag.modeChange("idle")
return isDone
def draw(self, t):
'''Show a set of colored circles based on the lastSigQuality'''
if not self.isRunning:
self.isRunning = True # mark that we're running
self.t0 = getTimeStamp()
self.noisetag.addSubscription("D") # subscribe to "DataPacket" messages
self.noisetag.modeChange("ElectrodeQuality")
self.dataringbuffer.clear()
if self.clearScreen:
self.window.clear()
# get the sig qualities
electrodeQualities = self.noisetag.getLastSignalQuality()
if not electrodeQualities: # default to 4 off qualities
electrodeQualities = [.5]*len(self.sprite)
if len(electrodeQualities) != len(self.sprite):
self.update_nch(len(electrodeQualities))
issig2noise = True #any([s>1.5 for s in electrodeQualities])
# update the colors
#print("Qual:", end='')
for i, qual in enumerate(electrodeQualities):
self.label[i].text = "%d: %3.1f"%(i+1, qual)
#print(self.label[i].text + " ", end='')
if issig2noise:
qual = log10(qual)/1 # n2s=50->1 n2s=10->.5 n2s=1->0
qual = max(0, min(1, qual))
qualcolor = (int(255*qual), int(255*(1-qual)), 0) #red=bad, green=good
self.sprite[i].color=qualcolor
#print("")
# draw the updated batch
self.batch.draw()
# get the raw signals
msgs=self.noisetag.getNewMessages()
for m in msgs:
if m.msgID == DataPacket.msgID:
print('D', end='', flush=True)
self.dataringbuffer.extend(m.samples)
if getTimeStamp() > self.t0+self.datawindow_ms: # slide buffer
# remove same number of samples we've just added
for i in range(len(m.samples)):
self.dataringbuffer.popleft()
if self.dataringbuffer:
if len(self.dataringbuffer[0]) != len(self.sprite):
self.update_nch(len(self.dataringbuffer[0]))
# transpose and flatten the data
# and estimate it's summary statistics
from statistics import median
# CAR
dataringbuffer =[]
for t in self.dataringbuffer:
mu = median(t)
dataringbuffer.append([c-mu for c in t])
# other pre-processing
data = []
mu = [] # mean
mad = [] # mean-absolute-difference
nch=len(self.linebbox)
for ci in range(nch):
d = [ t[ci] for t in dataringbuffer ]
# mean last samples
tmp = d[-int(len(d)*.2):]
mui = sum(tmp)/len(tmp)
# center (in time)
d = [ t-mui for t in d ]
# scale estimate
madi = sum([abs(t-mui) for t in tmp])/len(tmp)
data.append(d)
mu.append(mui)
mad.append(madi)
datascale_uv = max(5,median(mad)*4)
for ci in range(nch):
d = data[ci]
# map to screen coordinates
bbox=self.linebbox[ci]
# downsample if needed to avoid visual aliasing
#if len(d) > (bbox[2]-bbox[1])*2:
# subsampratio = int(len(d)//(bbox[2]-bbox[1]))
# d = [d[i] for i in range(0,len(d),subsampratio)]
# map to screen coordinates
xscale = bbox[2]/len(d)
yscale = bbox[3]/datascale_uv #datascale_uv # 10 uV between lines
y = [ bbox[1] + s*yscale for s in d ]
x = [ bbox[0] + i*xscale for i in range(len(d)) ]
# interleave x, y to make gl happy
coords = tuple( c for xy in zip(x, y) for c in xy )
# draw this line
col = [0,0,0]; col[ci%3]=1
pyglet.graphics.glColor3d(*col)
pyglet.gl.glLineWidth(1)
pyglet.graphics.draw(len(d), pyglet.gl.GL_LINE_STRIP, ('v2f', coords))
# axes scale
x = bbox[0]+bbox[2]+20 # at *right* side of the line box
y = bbox[1]
pyglet.graphics.glColor3f(1,1,1)
pyglet.gl.glLineWidth(10)
pyglet.graphics.draw(2, pyglet.gl.GL_LINES,
('v2f', (x,y-10/2*yscale, x,y+10/2*yscale)))
#-----------------------------------------------------------------
#-----------------------------------------------------------------
#-----------------------------------------------------------------
#-------------------------------------------------------------
class FrameRateTestScreen(InstructionScreen):
''' screen from testing the frame rate of the display under pyglet control '''
testing_text = "Checking display framerate\nPlease wait"
results_text = "Frame rate: "
failure_text = "WARNING:\nhigh variability in frame timing detected\nyour performance may suffer\n"
success_text = "SUCCESS:\nsufficient accuracy frame timing detected\n"
statistics_text = "\n{:3.0f} +/-{:3.1f} [{:2.0f},{:2.0f}]\n mean +/-std [min,max]"
closing_text = "\n Press key to continue."
def __init__(self, window, testduration=2000, warmup_duration=1000, duration=20000, waitKey=False):
super().__init__(window, self.testing_text, duration, waitKey)
self.testduration = testduration
self.warmup_duration = warmup_duration
self.ftimes = []
self.logtime = None
self.log_interval = 2000
def draw(self, t):
if not self.isRunning:
self.ftimes = []
self.logtime = 0
# call parent draw method
super().draw(t)
# record the flip timing info
# TODO[]: use a deque to make sliding window...
# TODO[]: plot the histogram of frame-times?
if self.elapsed_ms() > self.warmup_duration:
self.ftimes.append(self.window.lastfliptime)
if self.elapsed_ms() > self.warmup_duration + self.testduration:
if self.elapsed_ms() > self.logtime:
self.logtime=self.elapsed_ms() + self.log_interval
log=True
else:
log=False
(medt,madt,mint,maxt) = self.analyse_ftimes(self.ftimes,log)
# show warning if timing is too poor
if madt > 1:
msg=self.failure_text
else:
msg=self.success_text
msg += self.statistics_text.format(medt,madt,mint,maxt)
msg += self.closing_text
self.set_text(msg)
self.waitKey = True
@staticmethod
def analyse_ftimes(ftimes, verb=0):
# convert to inter-frame time
fdur = [ ftimes[i+1]-ftimes[i] for i in range(len(ftimes)-1) ]
#print(["%d"%(int(f)) for f in fdur])
# analyse the frame durations, in outlier robust way
from statistics import median
medt=median(fdur) # median (mode?)
madt=0; mint=999; maxt=-999; N=0;
for dt in fdur:
if dt > 200 : continue # skip outliers
N=N+1
madt += (dt-medt) if dt>medt else (medt-dt)
mint = dt if dt<mint else mint
maxt = dt if dt>maxt else maxt
madt = madt/len(fdur)
if verb>0 :
print("Statistics: %f(%f) [%f,%f]"%(medt,madt,mint,maxt))
try:
from numpy import histogram
[hist,bins]=histogram(fdur,range(8,34,2))
# report summary statistics to the user
print("Histogram:",
"\nDuration:","\t".join("%6.4f"%((bins[i]+bins[i+1])/2) for i in range(len(bins)-1)),
"\nCount :","\t".join("%6d"%t for t in hist))
except:
pass
return (medt,madt,mint,maxt)
#-----------------------------------------------------------------
#-----------------------------------------------------------------
#-----------------------------------------------------------------
#-------------------------------------------------------------
class SelectionGridScreen(Screen):
'''Screen which shows a grid of symbols which will be flickered with the noisecode
and which can be selected from by the mindaffect decoder Brain Computer Interface'''
LOGLEVEL=0
def __init__(self, window, symbols, noisetag, objIDs=None,
bgFraction:float=.2, instruct:str="",
clearScreen:bool=True, sendEvents:bool=True, liveFeedback:bool=True, optosensor:bool=True,
target_only:bool=False, show_correct:bool=True,
waitKey:bool=True, stimulus_callback=None, framerate_display:bool=True,
logo:str='MindAffect_Logo.png'):
'''Intialize the stimulus display with the grid of strings in the
shape given by symbols.
Store the grid object in the fakepresentation.objects list so can
use directly with the fakepresentation BCI presentation wrapper.'''
self.window=window
# create set of sprites and add to render batch
self.clearScreen= True
self.isRunning=False
self.isDone=False
self.sendEvents=sendEvents
self.liveFeedback=liveFeedback
self.framestart = getTimeStamp()
self.frameend = getTimeStamp()
self.symbols = symbols
self.objIDs = objIDs
self.optosensor = optosensor
self.framerate_display = framerate_display
self.logo = logo
# N.B. noisetag does the whole stimulus sequence
self.set_noisetag(noisetag)
self.set_grid(symbols, objIDs, bgFraction, sentence=instruct, logo=logo)
self.liveSelections = None
self.feedbackThreshold = .4
self.waitKey=waitKey
self.stimulus_callback = stimulus_callback
self.last_target_idx = -1
self.show_correct = show_correct
def reset(self):
self.isRunning=False
self.isDone=False
self.nframe=0
self.last_target_idx=-1
self.set_grid()
def set_noisetag(self, noisetag):
self.noisetag=noisetag
def setliveFeedback(self, value):
self.liveFeedback=value
def setliveSelections(self, value):
if self.liveSelections is None :
self.noisetag.addSelectionHandler(self.doSelection)
self.liveSelections = value
def get_idx(self,idx):
ii=0 # linear index
for i in range(len(self.symbols)):
for j in range(len(self.symbols[i])):
if self.symbols[i][j] is None: continue
if idx==(i,j) or idx==ii :
return ii
ii = ii + 1
return None
def getLabel(self,idx):
ii = self.get_idx(idx)
return self.labels[ii] if ii is not None else None
def setLabel(self,idx,val):
ii = self.get_idx(idx)
# update the label object to the new value
if ii is not None and self.labels[ii]:
self.labels[ii].text=val
def setObj(self,idx,val):
ii = self.get_idx(idx)
if ii is not None and self.objects[ii]:
self.objects[ii]=val
def doSelection(self, objID):
if self.liveSelections == True:
if objID in self.objIDs:
print("doSelection: {}".format(objID))
symbIdx = self.objIDs.index(objID)
sel = self.getLabel(symbIdx)
sel = sel.text if sel is not None else ''
text = self.update_text(self.sentence.text, sel)
if self.show_correct and self.last_target_idx>=0:
text += "*" if symbIdx==self.last_target_idx else "_"
self.set_sentence( text )
def update_text(self,text:str,sel:str):
# process special codes
if sel in ('<-','<bkspc>','<backspace>'):
text = text[:-1]
elif sel in ('spc','<space>','<spc>'):
text = text + '😀'
elif sel in ('home','quit'):
pass
elif sel == ':)':
text = text + ""
else:
text = text + sel
return text
def set_sentence(self, text):
'''set/update the text to show in the instruction screen'''
if type(text) is list:
text = "\n".join(text)
self.sentence.begin_update()
self.sentence.text=text
self.sentence.end_update()
def set_framerate(self, text):
'''set/update the text to show in the frame rate box'''
if type(text) is list:
text = "\n".join(text)
self.framerate.begin_update()
self.framerate.text=text
self.framerate.end_update()
def set_grid(self, symbols=None, objIDs=None, bgFraction=.3, sentence="What you type goes here", logo=None):
'''set/update the grid of symbols to be selected from'''
winw, winh=self.window.get_size()
# tell noisetag which objIDs we are using
if symbols is None:
symbols = self.symbols
if isinstance(symbols, str):
symbols = load_symbols(symbols)
self.symbols=symbols
# Number of non-None symbols
nsymb = sum([sum([(s is not None and not s == '') for s in x ]) for x in symbols])
if objIDs is not None:
self.objIDs = objIDs
else:
self.objIDs = list(range(1,nsymb+1))
objIDs = self.objIDs
if logo is None:
logo = self.logo
# get size of the matrix
gridheight = len(symbols) + 1 # extra row for sentence
gridwidth = max([len(s) for s in symbols])
self.ngrid = gridwidth * gridheight
self.noisetag.setActiveObjIDs(self.objIDs)
# add a background sprite with the right color
self.objects=[None]*nsymb
self.labels=[None]*nsymb
self.batch = pyglet.graphics.Batch()
self.background = pyglet.graphics.OrderedGroup(0)
self.foreground = pyglet.graphics.OrderedGroup(1)
# now create the display objects
w=winw/gridwidth # cell-width
bgoffsetx = w*bgFraction
h=winh/gridheight # cell-height
bgoffsety = h*bgFraction
idx=-1
for i in range(len(symbols)): # rows
y = (gridheight-1-i-1)/gridheight*winh # top-edge cell
for j in range(len(symbols[i])): # cols
# skip unused positions
if symbols[i][j] is None or symbols[i][j]=="": continue
idx = idx+1
symb = symbols[i][j]
x = j/gridwidth*winw # left-edge cell
try : # symb is image to use for this button
img = search_directories_for_file(symb,os.path.dirname(__file__))
img = pyglet.image.load(img)
symb = '.' # symb is a fixation dot
except :
# create a 1x1 white image for this grid cell
img = pyglet.image.SolidColorImagePattern(color=(255, 255, 255, 255)).create_image(2, 2)
# convert to a sprite (for fast re-draw) and store in objects list
# and add to the drawing batch (as background)
self.objects[idx]=pyglet.sprite.Sprite(img, x=x+bgoffsetx, y=y+bgoffsety,
batch=self.batch, group=self.background)
# re-scale (on GPU) to the size of this grid cell
self.objects[idx].update(scale_x=int(w-bgoffsetx*2)/img.width,
scale_y=int(h-bgoffsety*2)/img.height)
# add the foreground label for this cell, and add to drawing batch
self.labels[idx]=pyglet.text.Label(symb, font_size=32, x=x+w/2, y=y+h/2,
color=(255, 255, 255, 255),
anchor_x='center', anchor_y='center',
batch=self.batch, group=self.foreground)
# add opto-sensor block
img = pyglet.image.SolidColorImagePattern(color=(255, 255, 255, 255)).create_image(1, 1)
self.opto_sprite=pyglet.sprite.Sprite(img, x=0, y=winh*.9,
batch=self.batch, group=self.background)
self.opto_sprite.update(scale_x=int(winw*.1), scale_y=int(winh*.1))
self.opto_sprite.visible=False
# add the sentence box
y = winh # top-edge cell
x = winw*.15 # left-edge cell
self.sentence=pyglet.text.Label(sentence, font_size=32,
x=x, y=y,
width=winw-x-winw*.1, height=(gridheight-1)/gridheight*winh,
color=(255, 255, 255, 255),
anchor_x='left', anchor_y='top',
multiline=True,
batch=self.batch, group=self.foreground)
# add the framerate box
self.framerate=pyglet.text.Label("", font_size=12, x=winw, y=winh,
color=(255, 255, 255, 255),
anchor_x='right', anchor_y='top',
batch=self.batch, group=self.foreground)
# add a logo box
if isinstance(logo,str): # filename to load
logo = search_directories_for_file(logo,os.path.dirname(__file__),
os.path.join(os.path.dirname(__file__),'..','..'))
try :
logo = pyglet.image.load(logo)
logo.anchor_x, logo.anchor_y = (logo.width,logo.height) # anchor top-right
self.logo = pyglet.sprite.Sprite(logo, self.window.width, self.window.height-16) # sprite a window top-right
except :
self.logo = None
if self.logo:
self.logo.batch = self.batch
self.logo.group = self.foreground
self.logo.update(x=self.window.width, y=self.window.height-16,
scale_x=self.window.width*.1/logo.width,
scale_y=self.window.height*.1/logo.height)
def is_done(self):
if self.isDone:
self.noisetag.modeChange('idle')
return self.isDone
# mapping from bci-stimulus-states to display color
state2color={0:(5, 5, 5), # off=grey
1:(255, 255, 255), # on=white
2:(0, 255, 0), # cue=green
3:(0, 0, 255)} # feedback=blue
def draw(self, t):
"""draw the letter-grid with given stimulus state for each object.
Note: To maximise timing accuracy we send the info on the grid-stimulus state
at the start of the *next* frame, as this happens as soon as possible after
the screen 'flip'. """
if not self.isRunning:
self.isRunning=True
self.framestart=self.noisetag.getTimeStamp()
winflip = self.window.lastfliptime
if winflip > self.framestart or winflip < self.frameend:
print("Error: frameend={} winflip={} framestart={}".format(self.frameend,winflip,self.framestart))
self.nframe = self.nframe+1
if self.sendEvents:
self.noisetag.sendStimulusState(timestamp=winflip)#self.frameend)#window.lastfliptime)
# get the current stimulus state to show
try:
self.noisetag.updateStimulusState()
stimulus_state, target_idx, objIDs, sendEvents=self.noisetag.getStimulusState()
target_state = stimulus_state[target_idx] if target_idx>=0 else -1
if target_idx >= 0 : self.last_target_idx = target_idx
except StopIteration:
self.isDone=True
return
if self.waitKey:
global last_key_press
if self.window.last_key_press:
self.key_press = self.window.last_key_press
#self.noisetag.reset()
self.isDone = True
self.window.last_key_press = None
# turn all off if no stim-state
if stimulus_state is None:
stimulus_state = [0]*len(self.objects)
# do the stimulus callback if wanted
if self.stimulus_callback is not None:
self.stimulus_callback(stimulus_state, target_state)
# draw the white background onto the surface
if self.clearScreen:
self.window.clear()
# update the state
# TODO[]: iterate over objectIDs and match with those from the
# stimulus state!
for idx in range(min(len(self.objects), len(stimulus_state))):
# set background color based on the stimulus state (if set)
try:
ssi = stimulus_state[idx]
if self.target_only and not target_idx == idx :
ssi = 0
if self.objects[idx]:
self.objects[idx].color=self.state2color[ssi]
if self.labels[idx]:
self.labels[idx].color=(255,255,255,255) # reset labels