-
Notifications
You must be signed in to change notification settings - Fork 7
/
GenericApplication.py
2254 lines (1971 loc) · 90.4 KB
/
GenericApplication.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
# -*- coding: utf-8 -*-
#
# $Id: GenericApplication.py 4144 2012-06-17 04:48:37Z jhill $
#
# This file is part of the BCPy2000 framework, a Python framework for
# implementing modules that run on top of the BCI2000 <http://bci2000.org/>
# platform, for the purpose of realtime biosignal processing.
#
# Copyright (C) 2007-11 Jeremy Hill, Thomas Schreiner,
# Christian Puzicha, Jason Farquhar
#
# bcpy2000@bci2000.org
#
# The BCPy2000 framework is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import BCPy2000.Generic as Core
from BCPy2000.Generic import *
__all__ = [
"BciGenericApplication",
"BciGenericRenderer",
"SetDefaultFont",
"VisualStimuli",
] + Core.__all__
import os
import sys
import time
import copy
import numpy
from . import PrecisionTiming
# from .CurrentRenderer import VisualStimuli
import types
import importlib
VisualStimuli = types.ModuleType("VisualStimuli")
VisualStimuli.__all__ = []
VisualStimuli.__doc__ = """
TODO: document this
"""
# import imp
# VisualStimuli = imp.new_module('VisualStimuli')
# VisualStimuli.__all__ = []
# VisualStimuli.__doc__ = """
#
# TODO: document this
# """
#################################################################
#################################################################
class oops(Exception):
pass # oops messages are directed at jez
#################################################################
#################################################################
class BciGenericApplication(Core.BciCore):
"""
The BciGenericApplication class is part of the BCPy2000
framework. You create a subclass of it called BciApplication
in order to specify your application module's behaviour. The
BCPy2000 application API is somewhat more extensive than that
of the other modules: it allows you to schedule stimulus
events using an automatic real-time "phase machine" which you
implement in your Phases() and Transition() methods, update
stimuli on a frame-by-frame basis by implementing a Frame()
method, and respond to keyboard and mouse events by implementing
an Event() method.
Hook methods (which you can overshadow in your subclasses)
have names beginning with a capital letter (Construct, Preflight,
Initialize, Process, etc...). API methods, which are useful
calls that help you in writing your subclass implementation,
are lower-case. Anything beginning with underscores should be
avoided---you should not need to call such methods directly,
and should certainly not overshadow them (so, for example, do
not implement __init__ and __del__, but rather use Construct,
Initialize and StartRun for initialization, and use StopRun,
Halt and Destruct for cleanup).
""" ###
#############################################################
#### hooks called by the C++
#############################################################
def __init__(self):
super(BciGenericApplication, self).__init__()
self.frame_count = 0
self.current_presentation_phase = None
self.estimated = Core.BciDict(lazy=True)
self.screen = None
self._regfs = Core.BciDict(lazy=True)
self._block_structure = {}
self._previous_srctime_stateval = None
self._creation_parameters = None
self._transition_block_mode = None
self._transition_block = None
self.forget("transition")
self.forget("packet")
self.forget("frame")
self.forget("trial")
self.forget("block")
self.forget("cycle")
self._stimobjlist = []
self._add_thread("phase machine", self._phase_machine)
self._add_thread("visual display", self._visual_display)
## Various things that might affect frame timing:
# self._add_thread('share', self._share) # four-thread model doesn't seem to improve things in practice
self._optimize_display_thread_affinity = False
self._optimize_display_thread_priority = False
self._optimize_process_priority = False
self._display_sleep_msec = 0
# positive value: absolute number of milliseconds to sleep per frame. 10 msec sleep was what we used
# for 16.666 ms/frame in the early days. Can be increased if desired, but remember
# that you are living on the edge, depending how long the rest of the frame (and the
# releasing of locks from other threads) takes.
# 0: no sleep at all
# negative value: safety margin, in milliseconds, to be subtracted from the nominal time-left-to-wait
# in this frame in order to ascertain sleep time
#############################################################
def _Construct(self):
if self._optimize_display_thread_affinity:
PrecisionTiming.SetThreadAffinity([0])
paramdefs, statedefs = super(
BciGenericApplication, self
)._Construct() # superclass
desc = self.Description().replace("%", "%%").replace(" ", "%20")
paramdefs += [
"PythonApp string ApplicationDescription= "
+ desc
+ " % a z // Identifies the stimulus presentation module",
"PythonApp int ShowSignalTime= 0 0 0 1 // show a timestamp based on the number of processed samples (boolean)",
"PythonApp:Design int TrialsPerBlock= 20 20 1 % // number of trials in one block",
"PythonApp:Design int BlocksPerRun= 1 20 1 % // number of sub-blocks in one run",
]
statedefs += [
"EventOffset 10 0 0 0",
"PresentationPhase 5 0 0 0",
"CurrentTrial 9 0 0 0",
"CurrentBlock 7 0 0 0",
]
self._merge_defs(paramdefs, statedefs, self.Construct()) # subclass
if self.screen == None:
if not hasattr(BciGenericRenderer, "subclass"):
from . import PsychoPyRenderer
self.screen = BciGenericRenderer.subclass()
module = sys.modules[self.screen.__class__.__module__]
for x in module.__all__:
setattr(VisualStimuli, x, getattr(module, x))
VisualStimuli.screen = self.screen
VisualStimuli.__all__ += module.__all__ + ["screen"]
self.VisualStimuli = VisualStimuli
# Memorize internal variables, to delete all additional ones during restart
if self._creation_parameters == None:
self._creation_parameters = dir(self)
statedefs.reverse() # puts developer's definitions first (allows developer to override bit depth for built-in states)
return (paramdefs, statedefs)
#############################################################
def _Halt(self):
super(BciGenericApplication, self)._Halt() # superclass
self._lock.release()
self._lock.reset()
self._lock.acquire("Halt")
self.Halt() # subclass
self._run_callbacks("Halt")
self._lock.release("Halt")
for threadname in ["phase machine", "visual display"]:
th = self._threads[threadname]
if not th.read("ready"):
th.post("stop")
th.read("ready", wait=True)
self._check_threads()
print("Halt done!")
for i in dir(self):
if i not in self._creation_parameters:
try:
delattr(self, i)
except:
pass
print("Attribute Deletion done!")
#############################################################
def _Preflight(self, in_signal_props):
super(BciGenericApplication, self)._Preflight(in_signal_props) # superclass
out_signal_props = self.Preflight(self.in_signal_props) # subclass
self._store_out_signal_props(out_signal_props)
return self.out_signal_props
#############################################################
def _Initialize(self, in_signal_props, out_signal_props):
print("_Init called")
super(BciGenericApplication, self)._Initialize(
in_signal_props, out_signal_props
) # superclass
print("_Init super called")
# if hasattr(self, '_callbacks'): self._callbacks.clear()
self._slave = self.states.read_only = int(self.params["EnslavePython"]) != 0
if self._slave:
print()
print()
print('The application module is running in "slave" mode:')
print("state variables will not be writeable from this module.")
print("NB: the application will not replay its previous behaviour")
print("exactly unless a number of criteria are met. See the")
print('documentation on "replaying".')
print()
self.forget("transition")
self.forget("packet")
self.forget("frame")
self.forget("trial")
self.forget("block")
self.forget("cycle")
th = self._threads["visual display"]
ready = th.read("ready", remove=True)
if not ready:
raise oops("visual display thread is not running")
th.post("init", wait=True)
if not self.volume in [
x.get("func") for x in getattr(self, "_callbacks", {}).get("StartRun", [])
]:
self.init_volume()
#############################################################
def _StartRun(self):
self.frame_count = 0
super(BciGenericApplication, self)._StartRun() # superclass
self.forget("cycle")
self._previous_srctime_stateval = None
self.current_presentation_phase = None
self._regress_sampling_rate(init=True)
self._estimate_rate("SamplesPerSecond", init=2.0)
self._estimate_rate("FramesPerSecond", init=2.0)
self.states["CurrentTrial"] = 0
self.states["CurrentBlock"] = 0
self._lock.acquire("StartRun")
self.StartRun() # subclass
self._run_callbacks("StartRun")
self._lock.release("StartRun")
if not self._lock.enabled:
print("\nWARNING: mutex disabled")
if self._lock.record_timing:
print(
"\nWARNING: mutex is recording timing information, which will eat memory"
)
for threadname in ["phase machine"]:
th = self._threads[threadname]
th.read("ready", wait=True, remove=True)
th.post("go", wait=True)
# playback support
self._slave_memory = None
if "SignalStopRun" in self.states:
self.states.__setitem__("SignalStopRun", 0, "really")
if self._optimize_process_priority:
PrecisionTiming.SetProcessPriority(3)
#############################################################
def _Process(self, in_signal):
if self._transition_block == "waiting for packet":
message = "_Process waiting"
self._transition_block = message
while self._transition_block == message:
pass
self._lock.acquire("Process")
if self.states["EventOffset"] and self.since("transition")["packets"] > 0:
# self.debug('EventOffsetZeroed', val=self.states['EventOffset'])
self.states["EventOffset"] = 0
t = self.prectime()
packet = self.since("run", t)["packets"]
if packet > 0:
srctime = self._update_srctime(t)
self._regress_sampling_rate(
srctime
) # online regression over whole run so far
if packet > 2:
self._estimate_rate(
"SamplesPerSecond", t
) # instantaneous (but smoothed) estimate
self.remember("packet", t)
self._foundation_uses_string_encoding = isinstance(in_signal, bytes)
fallback_signal = super(BciGenericApplication, self)._Process(
in_signal
) # superclass
# fallback_signal is set by superclass to be a copy of the input if same dims, or zeros if not
out_signal = self.Process(self.in_signal) # subclass
self._run_callbacks("Process")
self._store_out_signal(out_signal, fallback_signal)
# playback support
if self._slave:
# Even if enslaved, only the app module can stop a run cleanly.
# So, detect and respond to the special state 'SignalStopRun' if it exists.
if self.states.get("SignalStopRun", 0):
self.states.__setitem__("Running", 0, "really")
# Handle phase transitions
pp, eo = self.states["PresentationPhase"], self.states["EventOffset"]
if self._slave_memory == None:
change = False
elif pp != self._slave_memory["pp"]:
change = True
elif eo == 0:
change = False
elif eo != self._slave_memory["eo"]:
change = True
else:
change = False
if change:
self._really_change_phase(self._phasedefs["bynumber"][pp]["name"])
self._slave_memory = {"pp": pp, "eo": eo}
self._lock.release("Process")
return self._encode_signal(self.out_signal)
#############################################################
def _StopRun(self):
self._parting_shot = True
super(BciGenericApplication, self)._StopRun() # superclass
self._lock.acquire("StopRun")
self.StopRun() # subclass
self._run_callbacks("StopRun")
self._lock.release("StopRun")
#############################################################
def _Resting(self):
super(BciGenericApplication, self)._Resting() # superclass
self._lock.acquire("Resting")
self.Resting() # subclass
self._lock.release("Resting")
#############################################################
def _Destruct(self):
super(BciGenericApplication, self)._Destruct() # superclass
self.Destruct() # subclass
#############################################################
#### low-level helper methods mostly used by the superclass
#############################################################
def _update_srctime(self, t=None):
if t == None:
t = self.prectime()
stateval = self.states["SourceTime"]
statebits = self.bits["SourceTime"]
previous_stateval = getattr(self, "_previous_srctime_stateval", None)
if previous_stateval == None:
tt = uintwrap(t + self._prectime_zero, statebits)
# This recreates what the source module should be doing to make the
# SourceTime stamp. So, if src and app modules are on the same machine,
# tt should now be comparable to the SourceTime state, and should be
# only a small number of msec ahead of it (but possibly wrapped-around)
SourceTimeToNow = float(Core.unwrapdiff(stateval, tt, statebits))
if (
SourceTimeToNow < 0.0
or SourceTimeToNow / 1000.0 > 0.75 * self.nominal["SecondsPerPacket"]
):
SourceTimeToNow = 0.0
# If SourceTimeToNow is negative or too large, we conclude that the two modules
# are not using the same clock chip. So let's pretend that there's no
# offset (if we SourceTimeToNow is too small then we might compute our event
# times a bit early as a result, but that's better than too late).
srctime = t - SourceTimeToNow - self.nominal["SecondsPerPacket"] * 1000.0
# Having unwrapped the difference between the SourceTime and now, re-apply
# that difference to now to give a floating-point non-wrapped SourceTime
# that is comparable to future calls to self.prectime()
else:
elapsed = Core.unwrapdiff(previous_stateval, stateval, statebits)
srctime = self.last["cycle"]["msec"] + float(elapsed)
self.remember("cycle", timestamp=srctime)
self._previous_srctime_stateval = stateval
return srctime
#############################################################
def _trial_update(self):
start = self._block_structure.get("start")
if self.current_presentation_phase == None:
self._really_change_phase(start)
if self.current_presentation_phase == None:
self._really_change_phase("idle")
inc = self._block_structure.get("new_trial")
if inc != self.current_presentation_phase:
return
self.states["CurrentTrial"] += 1
if self.states["CurrentBlock"] == 0:
self.states["CurrentBlock"] = 1
if self.states["CurrentTrial"] > int(self.params["TrialsPerBlock"]):
self.states["CurrentTrial"] = 0
self.states["CurrentBlock"] += 1
interblock = self._block_structure.get("interblock")
if interblock != None:
self.change_phase(interblock)
if self.states["CurrentBlock"] > int(self.params["BlocksPerRun"]):
self.states["CurrentTrial"] = 0
self.states["CurrentBlock"] = 0
endphase = self._block_structure.get("end")
if (
endphase == None
): # by default, automatically press suspend after the last block of the run
self.states["Running"] = 0
else: # ...unless the 'end' key has been defined, in which case pop into that phase
self.change_phase(endphase)
if self.states["CurrentTrial"] > 0:
self.remember("trial")
if self.states["CurrentTrial"] == 1:
self.remember("block")
#############################################################
def _really_change_phase(self, phasename=None):
if phasename == None:
rec = self._phasedefs["byname"].get(self.current_presentation_phase)
if rec != None:
phasename = rec.get("next")
if phasename != None:
self.current_presentation_phase = phasename
self._phase_must_change = True
#############################################################
def _estimate_rate(self, what, t=None, init=0.0):
if t == None:
t = self.prectime()
if what == "FramesPerSecond":
event_type = "frame"
batch = 1
elif what == "SamplesPerSecond":
event_type = "packet"
batch = self.nominal["SamplesPerPacket"]
else:
raise oops(what)
if not hasattr(self, "estimated"):
self.estimated = Core.BciDict(lazy=True)
if init or what not in self.estimated:
self.estimated[what] = Core.BciDict(lazy=True)
d = self.estimated[what]
if len(d) == 0:
if init == 0.0:
init = 4.0
nominal_rate = self.nominal[what]
nominal_delta = 1.0 / nominal_rate
batch_rate = nominal_rate / float(batch)
d["global"] = nominal_rate
d["running"] = nominal_rate
d["buffer"] = numpy.array(
[nominal_delta] * int(round(float(init) * batch_rate))
)
d["n"] = int(round(batch_rate)) # assume ~ 1 sec worth of prior knowledge
if init:
return
elapsed = self.since(event_type, t)
delta = elapsed["msec"]
if delta == None or delta < 0.0:
return
if elapsed[event_type + "s"] != 1:
return
delta /= 1000.0 * batch
i = d["n"] % len(d["buffer"])
oldval, d["buffer"][i] = d["buffer"][i], delta
d["running"] = 1.0 / (
1.0 / d["running"] + (delta - oldval) / float(len(d["buffer"]))
)
persistence = float(d["n"]) / float(d["n"] + 1)
d["global"] = 1.0 / (
persistence * 1.0 / d["global"] + (1.0 - persistence) * delta
)
d["n"] += 1
#############################################################
def _regress_sampling_rate(self, t=None, init=False):
if t == None:
t = self.prectime()
if init or not hasattr(self, "_regfs"):
self._regfs = Core.BciDict(lazy=True)
d = self._regfs
if init or len(d) == 0:
d["Packets"] = None
d["SamplesPerPacket"] = self.nominal["SamplesPerPacket"]
d["SamplesPerSecond"] = self.nominal["SamplesPerSecond"]
d["PacketStartSamples"] = 0.0
d["PacketStartSeconds"] = 0.0
d["OffsetSamples"] = 0.0
d[
"FakePackets"
] = 0 # round(0.5 * d['SamplesPerSecond'] / d['SamplesPerPacket'])
if init:
return
if d["Packets"] == None:
d["Packets"] = 0
y = d["Packets"] * d["SamplesPerPacket"] # y is measured in samples,
x = float(t) / 1000.0 # x is measured seconds,
n = (
d["Packets"] + 1.0
) # so in y = a * x + b, a is SamplesPerSecond, and b is Samples
a = d["SamplesPerSecond"]
b = d["OffsetSamples"]
if n < 2.0:
y = numpy.array([0.0, 1.0]) * d["SamplesPerPacket"]
x = (y - b) / a
ym = numpy.mean(y)
xm = numpy.mean(x)
x -= xm
p = numpy.inner(y, x) / (len(x) ** 3.0)
q = numpy.inner(x, x) / (len(x) ** 3.0)
else:
n += d["FakePackets"]
oldxm = d["xm"]
oldym = d["ym"]
xm = oldxm + (x - oldxm) / n
ym = oldym + (y - oldym) / n
f = (n - 1.0) / n
incp = y * (x - xm) + oldym * (oldxm - x) * f
incq = xm * oldxm - x * xm * (1 + 1 / f) + x * x / f
p = d["p"] * f**3.0 + incp / n**3.0
q = d["q"] * f**3.0 + incq / n**3.0
a = p / q
b = ym - a * xm
y = d["Packets"] * d["SamplesPerPacket"]
x = (y - b) / a
d.update(
{
"SamplesPerSecond": a,
"OffsetSamples": b,
"PacketStartSamples": y,
"PacketStartSeconds": x,
"p": p,
"q": q,
"xm": xm,
"ym": ym,
}
)
d["Packets"] += 1.0
#############################################################
def event_offset(self, timestamp=None, state=None):
if timestamp == None:
timestamp = self.prectime()
# use regressed sampling rate (with event offsets probably doesn't help much
# and may fail if packets are late, and badly if packets are skipped)
d = self._regfs
SamplesSinceStart = (
d["OffsetSamples"] + d["SamplesPerSecond"] * timestamp / 1000.0
)
EventOffset = int(round(SamplesSinceStart - d["PacketStartSamples"]))
# EventOffset = self.samples_since_packet(timestamp=timestamp)
# This would be a safer and *much* simpler method than all the regression-based stuff above
# However, it measured up with +/- 5 msec in an 68-channel RDA test, whereas the regression
# method yielded +/-1.4. The regression is only unsafe when late packets occur, which real EEG
# source modules shouldn't allow
signedval = EventOffset
if state != None:
# put the signed value into an unsigned state variable in a slightly unusual way
bits = self.bits[state]
maxabsval = 2 ** (bits - 1) - 1 # for example, 127 for 8 bits
if (
EventOffset < -maxabsval or EventOffset > maxabsval
): # reserve -128 (will become 0, below)
r, firsttime = self.debug(
"BadEventOffsets", val=EventOffset, statename=state, bits=bits
)
if firsttime:
print(
"WARNING: %s out of range (offset=%d, to be coded in %d-bit state)"
% (state, EventOffset, bits)
)
EventOffset = maxabsval * (EventOffset / abs(EventOffset))
val = (
1 + maxabsval + EventOffset
) # add 1, because 0 is reserved for "no event"
self.states[state] = val
return signedval
#############################################################
def add_callback(self, hookname, func, pargs=(), kwargs=None):
class CallbackRegErr(Exception):
pass
if kwargs == None:
kwargs = {}
if not hasattr(self, "_callbacks"):
self._callbacks = {
"StartRun": [],
"Process": [],
"Frame": [],
"StopRun": [],
"Halt": [],
}
if hookname not in self._callbacks:
raise CallbackRegErr(
"cannot register callbacks for %s, only for %s"
% (hookname, str(list(self._callbacks.keys())))
)
c = {"func": func, "pargs": pargs, "kwargs": kwargs}
if not c in self._callbacks[hookname]:
self._callbacks[hookname].append(c)
#############################################################
def _run_callbacks(self, hookname):
if getattr(self, "_callbacks", None) == None:
return
if not hookname in self._callbacks:
return
for c in self._callbacks[hookname]:
c["func"](*c["pargs"], **c["kwargs"])
#############################################################
def _initfocus(self):
try:
import ctypes # !! Windows-specific code.
opwin = ctypes.windll.user32.FindWindowA(
"TfMain", 0
) # find window by class name
except:
self._focus = {}
print("failed to initialize window focus handlers")
else:
self._focus = {
"stimuli": self.screen.RaiseWindow,
"operator": Core.BciFunc(self._raise_window, opwin),
}
self.add_callback("StartRun", self.focus, ("stimuli",))
self.add_callback("StopRun", self.focus, ("operator",))
#############################################################
def _raise_window(self, hdl, keepFocus=1):
if hdl == None or hdl == 0:
return
try:
import ctypes # !! Windows-specific code.
dll = ctypes.windll.user32
foregroundWnd = dll.GetForegroundWindow() # current foreground window
except:
pass
else:
hdl = ctypes.c_voidp(hdl)
threadID1 = ctypes.c_voidp(dll.GetWindowThreadProcessId(foregroundWnd, 0))
threadID2 = ctypes.c_voidp(dll.GetWindowThreadProcessId(hdl, 0))
if threadID1 != threadID2:
dll.AttachThreadInput(
threadID1, threadID2, 1
) # 1: attach (i.e. make sure the thread that owns the window to focus actually has the user input, so that even WinXP and later will actually consent to raise it)
ret = dll.SetForegroundWindow(hdl) # set to foreground
if not keepFocus:
dll.AttachThreadInput(threadID1, threadID2, 0) # 0: detach
dll.ShowWindow(hdl, 5) # 5: SW_SHOW (keep current size and position)
return ret
#############################################################
def _safe_sleep_until_frame(self, timestamp=None, safety_margin_msec=1.0):
if self.frame_count < 1:
return 0.0
elapsed = self.since("frame", timestamp=timestamp)
self._last_frametime = elapsed["msec"]
sleeptime = 1000.0 * self.nominal["SecondsPerFrame"] - elapsed["msec"]
sleeptime = numpy.floor(sleeptime - safety_margin_msec)
return max(sleeptime, 0.0)
#############################################################
#### main thread controllers
#############################################################
def _phase_machine(self, mythread):
try:
class PhaseChangeErr(Exception):
pass
if self._optimize_display_thread_affinity:
PrecisionTiming.SetThreadAffinity([0])
mythread.read("stop", remove=True)
mythread.post("ready")
mythread.read("go", wait=True, remove=True)
while not self.states["Running"]:
time.sleep(0.001)
previous_phase = None
self.current_presentation_phase = None
self.phase(name="idle", duration=None, next="idle", id=0)
while self.states["Running"] and not mythread.read("stop"):
if self._transition_block_mode != None:
message = "waiting for " + self._transition_block_mode
self._transition_block = message
starttime = self.prectime()
while self._transition_block == message:
t = self.prectime() - starttime
timeouts = {
"packet": 20 * self.nominal["SecondsPerPacket"] * 1000,
"frame": 20 * self.nominal["SecondsPerFrame"] * 1000,
}
if t >= timeouts.get(self._transition_block_mode, 0):
dbrec, firsttime = self.debug(
"TransitionBlockTimeout",
waiting_for=self._transition_block_mode,
timeout_msec=t,
)
if firsttime:
sys.stderr.write(
'WARNING: transition-lock timed out waiting for "%s" after %g msec\n'
% (self._transition_block_mode, t)
)
break
self._lock.acquire("Transition")
self._transition_block = None
self.Phases()
self._trial_update()
if not self.states["Running"]:
break
if not isinstance(self.current_presentation_phase, str):
raise PhaseChangeErr("phase names must be strings")
rec = self._phasedefs["byname"].get(self.current_presentation_phase)
if rec == None:
raise PhaseChangeErr(
'unrecognized phase "' + self.current_presentation_phase + '"'
)
t = self.prectime()
if previous_phase != None:
self.event_offset(state="EventOffset", timestamp=t)
self.states["PresentationPhase"] = rec["id"]
elapsed = self.since("transition", timestamp=t)
self.remember("transition", timestamp=t)
if self._slave:
self.last["transition"]["packet"] -= 1
# self.debug('transition', from_phase=previous_phase, to_phase=self.current_presentation_phase, after=elapsed['msec'], pp=self.states['PresentationPhase'], eo=self.states['EventOffset'])
self.Transition(self.current_presentation_phase)
if elapsed["packets"] == 0 and previous_phase != None:
dbrec, firsttime = self.debug(
"MultipleTransitions",
from_phase=previous_phase,
to_phase=self.current_presentation_phase,
after_msec=elapsed["msec"],
)
if firsttime:
sys.stderr.write(
"WARNING: multiple phase transitions per packet\n"
)
self._lock.release("Transition")
previous_phase = rec["name"]
duration = rec["duration"]
next = rec["next"]
self._phase_must_change = False
while not self._phase_must_change:
if not self.states["Running"] or mythread.read("stop"):
break
if duration != None and next != None and not self._slave:
elapsed = self.since("transition")
overhead = 2
if elapsed["msec"] >= duration - overhead:
self.change_phase(next)
if not self._phase_must_change:
if self._safe_sleep_until_frame(safety_margin_msec=3.0) > 0.0:
time.sleep(0.001)
except:
mythread.fail()
self._lock.release("Transition")
#############################################################
def _visual_display(self, mythread):
try:
mythread.read("init", remove=True)
mythread.read("stop", remove=True)
mythread.post("ready")
mythread.read("init", wait=True) # removed when initialization is complete
self.screen.Initialize(self)
self._initfocus()
self.stimuli = Core.BciDict(lazy=True)
self._stimlist = []
self._stimz = []
self._stimon = []
self._stimq = () # non-list object is a sign to stimulus() that stimuli can be processed immediately, since we are in the right thread
self.Initialize(self.in_signal_dim, self.out_signal_dim) # subclass
self._stimq = [] # list object is a sign that stimuli must be queued
self._hud_setup()
self.frame_count = 0
self.focus("stimuli")
fr = self.screen.GetFrameRate()
if fr == None or fr == 0.0:
print("WARNING: self.screen.GetFrameRate() is returning nonsense")
fr = 1.0 # obviously not a sensible value (renderer developer should have overshadowed this)
# but not None and not 0 (so nothing will break)
self.nominal["FramesPerSecond"] = float(fr)
self.nominal["SecondsPerFrame"] = 1.0 / self.nominal["FramesPerSecond"]
self._estimate_rate(
"FramesPerSecond", init=2.0
) # will be re-initialized at StartRun
if self._optimize_display_thread_affinity:
PrecisionTiming.SetThreadAffinity([1])
if self._optimize_display_thread_priority:
PrecisionTiming.SetThreadPriority(3)
self.focus("operator")
mythread.read("init", remove=False)
while not mythread.read("stop"):
self.ftdb(
"newframe", label="screen.GetEvents"
) # -------------------- (first column of frame timing log is filled in now)
events = self.screen.GetEvents()
self.ftdb(label="lock.acquire") # --------------------
self._lock.acquire("Frame")
self.ftdb(label="Event+Frame") # --------------------
partingShot = not self.states["Running"] and getattr(
self, "_parting_shot", False
)
if partingShot:
self._parting_shot = False
if self.states["Running"] or partingShot:
for event in events:
self.Event(self.current_presentation_phase, event)
self.Frame(self.current_presentation_phase)
self._run_callbacks("Frame")
self.ftdb(label="update_stimlist") # --------------------
self._update_stimlist()
for st in self._stimobjlist:
st.dispatchChanges()
# self.screen.StartFrame(self._stimlist) #-------------------- (also contains ftdb calls)
self.screen.StartFrame(
[
stim
for i, stim in enumerate(self._stimlist)
if self._stimon[i] is True
]
)
self.ftdb(label="lock.release") # --------------------
self._lock.release("Frame")
self.ftdb(label="sleep") # --------------------
sleeptime = self._display_sleep_msec
if sleeptime < 0.0:
sleeptime = self._safe_sleep_until_frame(
safety_margin_msec=abs(sleeptime)
)
if (
sleeptime > 0.0
and sleeptime / 1000.0 < self.nominal["SecondsPerFrame"]
):
time.sleep(sleeptime / 1000.0)
self._last_sleeptime = sleeptime
self.screen.FinishFrame() # -------------------- (also contains ftdb calls)
self.ftdb(label="end") # --------------------
t = self.prectime()
if self.frame_count > 0:
self._estimate_rate("FramesPerSecond", t)
self.remember("frame", t)
self.frame_count += 1
if self._transition_block == "waiting for frame":
self.ftdb(label="transition_block") # --------------------
message = "_visual_display waiting"
self._transition_block = message
while self._transition_block == message:
pass
mythread.read("init", remove=True, wait=False)
except:
if self.frame_count == 0 or self.states["Running"]:
einfo = (
mythread.fail()
) # Initialize or Process will pick this up via _check_threads
else:
sys.excepthook(
*sys.exc_info()
) # we are not running, so nobody will pick this up: at least print a backtrace
self._lock.release("Frame")
if not isinstance(einfo[1], EndUserError):
while mythread.exception != None and not mythread.read("stop"):
time.sleep(
0.001
) # cannot use mythread.read to wait for 'stop' in the normal way until the exception is cleared
mythread.read(
"stop", wait=True
) # because waits normally fall through if the thread has posted an exception
self._stimobjlist.clear()
print("Cleanup")
self._lock.release("Frame")
if hasattr(self, "stimuli"):
delattr(self, "stimuli")
if hasattr(self, "_stimlist"):
delattr(self, "_stimlist")
if hasattr(self, "_stimz"):
delattr(self, "_stimz")
if hasattr(self, "_stimq"):
delattr(self, "_stimq")
if hasattr(self, "statemonitors"):
delattr(self, "statemonitors")
if hasattr(self, "_signalclock"):
delattr(self, "_signalclock")
self.screen.Cleanup()
print("Cleanup done!")
#############################################################
def ftdb(self, subcmd=None, nframes=1000, ntimings=20, filename=None, label=None):
if (
subcmd == "setup"
): # create an array to hold the timings (one row per frame, maximally ntimings columns although may use fewer)
self._ftlog = {
"t": numpy.zeros((nframes, ntimings), dtype=numpy.float64),
"i": 0,
"j": 0,
"started": False,
"rows_used": 0,
"cols_used": 0,
"labels": [],
}
return
ftlog = getattr(self, "_ftlog", None)
if ftlog == None:
return # practically zero overhead if not already called with 'setup' subcommand
t = self.prectime()
if subcmd == "start":
ftlog["i"] = 0
ftlog["j"] = 0
ftlog["rows_used"] = 0
ftlog["cols_used"] = 0
ftlog["started"] = True
ftlog["labels"] = [None] * ftlog["t"].shape[1]
return
if subcmd == "stop":
ftlog["started"] = False
return
if subcmd == "save":
if filename == None:
raise ValueError("no filename supplied")
m = ftlog["t"][: ftlog["rows_used"], : ftlog["cols_used"]]
f = open(filename, "wt")
f.write("ft = [\n")