-
Notifications
You must be signed in to change notification settings - Fork 6
/
GenericDemo.py
2533 lines (2147 loc) · 90.2 KB
/
GenericDemo.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: Generic.py 5501 2016-08-09 14:27:52Z 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
#
#
# 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/>.
#
__all__ = [
"EndUserError",
"intwrap",
"uintwrap",
] # NB: Only export symbols to which the developer should have access.
# The generic subclasses shouldn't be saying import *
import os
import sys
import time
import copy
import numpy
import random
import threading
import re
from . import PrecisionTiming
#################################################################
### code executed on import
#################################################################
# embedded calls don't provide a shell and thus no sys.argv even though IPython and VisionEgg need it
if not hasattr(sys, "argv"):
sys.argv = [""]
if __name__.startswith("BCPy2000."):
from BCPy2000 import __version__, __author__, __copyright__, __email__
else:
__copyright__ = None
__version__ = "$Revision unknown, so let us use 41450 $".split(" ")[
-2
] # update __version__ in BCPy2000/__init__.py first
# development version (NB: the use of the Revision keyword in this way is not
# so definitive: it only tracks changes to this particular file - see
# http://subversion.tigris.org/faq.html#version-value-in-source
#################################################################
### exception types
#################################################################
class EndUserError(Exception):
"""
EndUserError is an Exception subclass which the developer can
use to flag that an error is intended for the end-user.
Exceptions that are not EndUserError subclasses are assumed to
be directed at the developer.
""" ###
pass
#################################################################
### global functions
#################################################################
def authors():
a = [x.strip() for x in __author__.split(",")]
random.shuffle(a)
return a
def register_framework_dir():
global whereami
whereami = os.path.realpath(os.path.dirname(__file__))
if len(whereami) == 0:
whereami = os.getcwd()
print(
("%04d-%02d-%02d %02d:%02d:%02d" % time.localtime()[:6])
+ (" - BCPy2000 %s is running under\nPython %s\n" % (__version__, sys.version))
)
if __copyright__ != None:
print()
print("BCPy2000 ", __copyright__, ", ".join(authors()))
print(
"This program comes with ABSOLUTELY NO WARRANTY; for details type self.warranty()"
)
print(
'This is free software, and you are welcome to redistribute it under certain conditions; for details type self.doc("License")'
)
print()
print("framework directory is " + whereami)
if not whereami in sys.path:
sys.path.append(whereami)
extensions = [
os.path.join(whereami, x)
for x in os.listdir(whereami)
if not x.startswith(".") and not x.startswith("_")
]
extensions = [
x
for x in extensions
if os.path.isdir(x) and not os.path.isfile(os.path.join(x, "__init__.py"))
]
for x in extensions:
x = os.path.realpath(x)
print("found extension subdir " + x)
if not x in sys.path:
sys.path.append(x)
def register_working_dir():
d = os.getcwd()
if not d in sys.path:
sys.path.append(d)
print(" working directory is " + d)
def search_for_file(filename):
class FileNotFound(Exception):
pass
fullpath = (
[None]
+ list(
filter(
os.path.isfile,
[os.path.realpath(os.path.join(p, filename)) for p in sys.path + ["."]],
)
)
)[-1]
if fullpath == None:
raise FileNotFound('failed to find file "%s"' % filename)
print("running developer file " + fullpath)
return fullpath
def intwrap(t, bits=16):
"""
Re-expresses the input value as a signed integer of the specified
number of bits (wrapped).
""" ###
h = 2 ** (int(bits) - 1)
return ((int(round(t)) + h) % (h * 2)) - h
def uintwrap(t, bits=16):
"""
Re-expresses the input value as an unsigned integer of the specified
number of bits (wrapped), suitable for storage in a state variable.
""" ###
return int(round(t)) % (2 ** int(bits))
def unwrapdiff(a, b, bits=16):
base = 2 ** int(bits)
d = (int(round(b)) % base) - (int(round(a)) % base)
if d < -base / 2:
d += base
if d > +base / 2:
d -= base
return d
def param2val(v, _r=0):
if isinstance(v, (int, float, numpy.ndarray)):
return v
try:
return int(v)
except:
pass
try:
return float(v)
except:
pass
if not isinstance(v, (tuple, list)):
return v
v = list(v)
for i in range(len(v)):
v[i] = param2val(v[i], _r + 1)
if _r > 0 or len(v) == 0 or not isinstance(v[0], list):
return v
try:
return numpy.matrix(v)
except:
pass
try:
return numpy.array(v)
except:
pass
return v
def val2param(v):
if isinstance(v, numpy.ndarray):
v = v.tolist()
elif isinstance(v, (tuple, list)):
v = list(v) # copy container
else:
v = BciStr(v)
if isinstance(v, list):
for i in range(len(v)):
v[i] = val2param(v[i])
return v
#################################################################
#################################################################
class BciCore(object):
"""
This is the grandaddy superclass of all BCPy2000 objects. It is
probably more informative to look at the documentation for the
particular "generic" class of which you are intending to
implement a subclass:
BciGenericSource in BCPy2000.GenericSource
BciGenericSignalProcessing in BCPy2000.GenericSignalProcessing
BciGenericApplication in BCPy2000.GenericApplication
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).
""" ###
#############################################################
#### legall stuff
#############################################################
def warranty(self):
print(
"""
The GNU General Public License v. 3.0 applies. Specifically:
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.
SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY
SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL
ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE
PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
"""
) ###
def doc(self, topic="About"):
"""
Opens the html documentation.
""" ###
if __name__.startswith("BCPy2000."):
try:
from . import Documentation
except ImportError:
print("documentation not found")
else:
Documentation.browse(topic)
else:
import webbrowser
user = os.environ.get("USERNAME", "")
if len(user) == 0:
user = os.environ.get("USER", "")
if len(user):
user += "/"
webbrowser.open(
"http://localhost/cgi-bin/"
+ user
+ "BCPy2000?"
+ topic.replace(" ", "_")
)
#############################################################
#### hooks called by the C++ (or by the "Generic" superclass)
#############################################################
def __init__(self):
super(BciCore, self).__init__()
self._frameworkdir = whereami
self._threads = {}
self._ipshell = None
self._shell_running = False
self._slave = False
self._error_info = (None, None, None)
self._error_reported = False
self._writeable_params = []
self._oldparams = BciDict(lazy=True)
self._oldstates = BciDict(lazy=True)
self._transient_states = {}
self._shared = {}
self._lock = BciLock(record_timing=False, enable=True)
self.params = BciDict(lazy=True)
# self.states = BciDict(lazy=True)
self.stateArrays = BciDict(lazy=True)
self.states = BciScalarDict()
self.prevstates = None
self.bits = BciDict(lazy=True)
self.nominal = BciDict(lazy=True)
self.last = BciDict(lazy=True)
self.db = BciDict(lazy=True)
self.in_signal_props = BciDict(lazy=True)
self.out_signal_props = BciDict(lazy=True)
self.in_signal_dim = []
self.out_signal_dim = []
self.in_signal = numpy.matrix([])
self.out_signal = numpy.matrix([])
self.installation_dir = ""
self.original_working_dir = ""
self.data_dir = ""
self.data_file = None
self.verbose = False
self.packet_count = 0
self._zero_time()
self.forget("packet")
self.forget("run")
self.keyboard = self.dbstop
# PrecisionTiming.SetProcessPriority(+2)
#############################################################
def _set_states(self, states): # transfer states from C++ to Python before _Process
# f = open("D:/setState.txt", "a+")
# f.write("#############################OPEN#############################################\n")
# f.write(str(states))
# f.write("\n\n")
self._lock.acquire("_set_states") # TODO ???
if len(self._oldstates) == 0:
self._oldstates = states.copy()
# self._oldstates = stateArrays.copy()
if len(self.stateArrays) == 0:
self.stateArrays = BciDict(states, complete=True, lazy=True)
# if len(self.stateArrays) == 0:
# self.stateArrays = BciScalarDict(states)
# if len(self.states) == 0:
# # f.write("state Scalar length is 0\n")
# # f.write(str(states))
# self.states = BciScalarDict(states)
self.stateArrays.block = True # TODO: ???
# f.write("\nstate Scalar:")
# f.write(str(self.states))
# f.write("\n\n")
# f.write("stateArrays:")
# f.write(str(self.stateArrays))
# f.write("\n\n")
for i in list(states.keys()):
# if state coming from c++ is not listed in python, or if the state variable hasn't changed since last time, update python according to c++
decoded = numpy.frombuffer(states[i], dtype=numpy.uint32)
# f.write("before decoded: ")
# f.write(str(states[i]))
# f.write("\n")
if decoded.size == 1:
decoded = int(decoded.flat[0])
# _old_states = numpy.frombuffer(self._oldstates[i], dtype=numpy.uint32)
# if (i not in self.stateArrays) or self._oldstates[i] == decoded: # TODO: "and the value coming from c++ is different...."?
# f.write("After decoded: \n")
# f.write(i)
# f.write(str(decoded))
# f.write("\n\n")
dict.__setitem__(
self.stateArrays, i, decoded
) # bypasses 'read_only' and 'block'
dict.__setitem__(self.states, i, decoded)
# #self.stateArrays.__setitem__(i,states[i], 'really') # bypasses 'read_only'
# # whereas if the state has changed since last time, but not to the same value that C++ thinks it should change to, issue a warning
# # (this python module and some other module have tried to change the same state on the same packet, to different values)
# elif _old_states != decoded and decoded != self.stateArrays[i]:
# r,firsttime = self.debug('state collision in '+i, old=_old_states, newpython=self.stateArrays[i], newbci=decoded)
# if firsttime: print('Collision in state',i,': Oldvalue:', _old_states,' New Python Value:',self.stateArrays[i],' New BCI Value:',states[i])
self.stateArrays.block = False # TODO ???
self.stateArrays._bits = self.bits
self._oldstates = (
self.stateArrays.copy()
) # TODO: move this to ^^^ ??? probably not
self._lock.release("_set_states") # TODO ???
# s = dict(self.states)
# f.write("NewArrayDict:")
# f.write(str(self.stateArrays))
# f.write("\nNewScalarDict:")
# f.write(str(self.states))
# f.write(self.stateArrays)
# f.write("\n#############################CLOSE#############################################\n")
# f.close()
#############################################################
def _get_states(self):
# transfer states from Python to C++ after _Process
#
# for k, v in self.states.items():
# print(self.stateArrays.keys())
# print('\n')
# print(self.states.keys())
# print('\n')
for i in list(self.stateArrays.keys()):
# dict.__setitem__(self, k, v)
self.stateArrays[i] = self.states[i]
self.stateArrays.block = True
self.prevstates = self.stateArrays.copy()
self.packet_count += 1
# h = dict(self.states)
s = dict(
self.stateArrays
) # makes a copy TODO: update _oldstates here instead of ^^^ ???
# f = open("D:/getState.txt", "a+")
# f.write("\n\n#########################################################################")
# f.write("\n\nDict:")
# f.write(str(s) + '\n\n')
# data = list(s)
# print(data)
# ByteArray = numpy.array(data, dtype='<u2')
# print(ByteArray)
# fulltArray = numpy.array()
for k, v in s.items():
# print("THIS IS THE CURRENT KEY")
# print(s[i])
# ByteArray = numpy.array(s[i])
# print(ByteArray)
# print(ByteArray.size())
s[k] = numpy.asarray(v, dtype="uint32").tobytes(order="C")
# f.write("after to bytes: \n\n")
# f.write(str(s[k]))
# print(s)
self.stateArrays.block = False
self._handle_transients()
# f.write("\n\nNewDict:")
# f.write(str(s))
# f.write("\n\n###############################CLOSE##########################################")
# f.close()
return s
#############################################################
def _set_state_precisions(self, bits):
self.bits = BciDict(bits, complete=True, lazy=True, read_only=True)
# print("hello")
#############################################################
def _set_parameters(self, params):
self.params = BciDict(params, complete=True, lazy=True)
self._oldparams = self.params.copy()
#############################################################
def _get_parameters(self):
p = {}
for k, v in list(self.params.items()):
v = val2param(v)
if v != self._oldparams[k]:
p[k] = v
return p
#############################################################
def _param_labels(self, param_name, row_labels, column_labels):
p = self.params[param_name]
if isinstance(p, str):
self.params[param_name] = p = BciStr(p)
if not isinstance(p, (list, tuple)) or len(p) == 0:
return
if not isinstance(p[0], (list, tuple)) or len(p[0]) == 0:
column_labels = None
self.params[param_name] = BciList(
p, row_labels=row_labels, column_labels=column_labels
)
#############################################################
def _start(self):
print("\nself is a %s instance\n\n" % self.__class__.__name__)
for th in list(self._threads.values()):
th.start()
for i in range(10):
if not th.isAlive():
time.sleep(0.001)
time.sleep(0.001)
self._check_threads()
if self._ipshell != None:
from . import EmbeddedPythonConsole
if EmbeddedPythonConsole.WaitForShell(0.1):
tr = EmbeddedPythonConsole.Tracer()
self.dbstop = tr
self.keyboard = tr
self._ipshell.IP.magic_bci2000 = self.bci2000shell
#############################################################
def _add_thread(self, name, func, *pargs, **kwargs):
th = BciThread(func=func, pargs=pargs, kwargs=kwargs, loop=True)
self._threads[name] = th
return th
#############################################################
def _enable_shell(self):
pass
# from . import EmbeddedPythonConsole
# self._ipshell = EmbeddedPythonConsole.Shell()
# self._add_thread('shell', self._shell)
#############################################################
def _shell(self, mythread):
del mythread # anything we leave lying around in this namespace becomes available at the shell prompt
self._shell_running = True
self._ipshell()
self._shell_running = False
#############################################################
def _zeros(self, nrows, ncols):
return numpy.asmatrix(
numpy.zeros((nrows, ncols), dtype=numpy.float64, order="C")
)
##########################################################
def _decode_signal(self, m):
if not isinstance(m, bytes):
return m
m = numpy.frombuffer(m, dtype=numpy.float64)
m.shape = tuple(self.in_signal_dim)
return m
##########################################################
def _encode_signal(self, m):
if not self._foundation_uses_string_encoding:
return m # older PythonFilter implementation, compiled using the numpy API, delivers and expects numpy array objects
# print(m)
return m.tostring(order="C")
##########################################################
def _copy_signal(self, m):
if isinstance(m, (list, tuple, numpy.ndarray)):
m = numpy.array(m, dtype=numpy.float64, order="C")
elif isinstance(m, bytes):
m = self._decode_signal(m)
return numpy.asmatrix(m)
###############################################################################
def _decode_state(self, m):
if not isinstance(m, bytes):
return m
m = numpy.frombuffer(m, dtype=numpy.uint32, order="C")
m.shape = tuple(self.in_signal_dim)
return m
##########################################################
def _encode_state(self, m):
if not self._foundation_uses_string_encoding:
return m # older PythonFilter implementation, compiled using the numpy API, delivers and expects numpy array objects
# print(m)
return m.tostring(order="C")
##########################################################
def _copy_state(self, m):
if isinstance(m, (list, tuple, numpy.ndarray)):
m = numpy.array(m, dtype=numpy.uint32, order="C")
elif isinstance(m, bytes):
m = self._decode_state(m)
return numpy.asarray(m)
#############################################################
def define_param(self, *pargs):
"""
As an alternative to returning (paramdefs,statedefs) from your
Construct() hook, you can simply call
self.define_param(paramdef1)
self.define_param(paramdef2)
self.define_state(statedef1)
self.define_state(statedef2)
or
self.define_param(paramdef1, paramdef2, ...)
self.define_state(statedef1, statedef2, ...)
inside the hook.
""" ###
self._subclass_paramdefs = getattr(self, "_subclass_paramdefs", [])
self._subclass_paramdefs += list(pargs)
#############################################################
def define_state(self, *pargs):
"""
As an alternative to returning (paramdefs,statedefs) from your
Construct() hook, you can simply call
self.define_param(paramdef1)
self.define_param(paramdef2)
self.define_state(statedef1)
self.define_state(statedef2)
or
self.define_param(paramdef1, paramdef2, ...)
self.define_state(statedef1, statedef2, ...)
inside the hook.
""" ###
self._subclass_statedefs = getattr(self, "_subclass_statedefs", [])
self._subclass_statedefs += list(pargs)
#############################################################
def _merge_defs(self, paramdefs, statedefs, constructor_output):
if constructor_output == None:
subclass_paramdefs, subclass_statedefs = [], []
else:
subclass_paramdefs, subclass_statedefs = constructor_output
self._subclass_paramdefs = getattr(self, "_subclass_paramdefs", [])
self._subclass_paramdefs += list(subclass_paramdefs)
paramdefs += self._subclass_paramdefs
for i in range(len(paramdefs)):
paramdefs[i] = paramdefs[i].replace("\n", " ")
self._subclass_statedefs = getattr(self, "_subclass_statedefs", [])
if isinstance(subclass_statedefs, dict):
for name, bits in list(subclass_statedefs.items()):
if isinstance(bits, dict):
bits = bits["bits"]
self._subclass_statedefs.append(name + " " + str(bits) + " 0 0 0")
else:
self._subclass_statedefs += list(subclass_statedefs)
statedefs += self._subclass_statedefs
for i in range(len(statedefs)):
statedefs[i] = statedefs[i].replace("\n", " ")
##########################################################
def _Construct(self):
if self.verbose:
print("calling Construct hook")
params = [
"Source:Signal%20Properties:DataIOFilter list ReferenceChannelName= 0 % % a z // list of labels for reference channel or channels",
"Source:Signal%20Properties:DataIOFilter list GroundChannelName= 0 % % a z // label of the ground channel",
"Source:Playback int EnslavePython= 0 0 0 1 // force BCPy2000 modules to follow states supplied by the source module without being able to change them (boolean)",
]
states = []
try:
result = self.operator()
if result != None:
print("BCI2000Remote failed to connect: %s" % result)
except Exception as e:
print(
"failed to instantiate BCI2000Remote class because of %s: %s"
% (e.__class__.__name__, str(e))
)
return (params, states)
#############################################################
def _Halt(self):
if self.verbose:
print("calling Halt hook")
self._slave = self.stateArrays.read_only = False
th = self._threads.get("share")
if th != None:
if not th.read("ready"):
th.post("stop")
th.read("ready", wait=True)
self._check_threads()
#############################################################
def _resolve_data_file_path(self, **kwargs):
sr = kwargs.get("SubjectRun", self.params.get("SubjectRun", 0))
try:
sr = int(sr)
except:
sr = 0
if sr <= 0:
sr, offset = 0, sr
while True:
sr += 1
df = self._resolve_data_file_path(SubjectRun=sr)
if not os.path.isfile(df):
break
df = self._resolve_data_file_path(SubjectRun=sr + offset)
return df
dd = self.params.get("DataDirectory", "../data")
dd = (
self._interpolate_parameter_values(dd, **kwargs)
.replace("\\", os.path.sep)
.replace("/", os.path.sep)
)
if not os.path.isabs(dd):
dd = os.path.join(self.original_working_dir, dd)
df = self.params.get(
"DataFile",
"${SubjectName}${SubjectSession}/${SubjectName}S${SubjectSession}R${SubjectRun}.${FileFormat}",
)
df = (
self._interpolate_parameter_values(df, **kwargs)
.replace("\\", os.path.sep)
.replace("/", os.path.sep)
)
df = os.path.realpath(os.path.join(dd, df))
return df
def _interpolate_parameter_values(self, string, **kwargs):
formats = dict(SubjectSession="%03d", SubjectRun="%02d")
def repl(match):
key = match.group(1)
if key in kwargs:
value = kwargs[key]
elif key in self.params:
value = self.params[key]
else:
value = ""
if not isinstance(value, str):
fmt = formats.get(key, "%s")
value = fmt % value
return value
return re.sub(r"\$\{(.*?)\}", repl, string)
def _data_file_info(self, filepath=None, comment=None):
timefmt = "%Y-%m-%d %H:%M:%S"
if filepath is None:
filepath = self.data_file
if isinstance(filepath, int):
filepath = self._resolve_data_file_path(SubjectRun=filepath)
try:
exists = os.path.isfile(filepath)
except:
exists = False
try:
st = os.stat(filepath)
except:
time_created, time_modified = None, None
else:
time_created, time_modified = [
time.strftime(timefmt, time.localtime(t))
for t in (st.st_ctime, st.st_mtime)
]
try:
dirname, basename = os.path.split(filepath)
except:
dirname, basename = None, None
try:
listed = basename in os.listdir(dirname)
except:
listed = False
try:
startrun = time.strftime(
timefmt,
time.localtime(time.time() - self.since("run")["msec"] / 1000.0),
)
except:
startrun = None
time_now = time.strftime(timefmt)
d = dict(
basename=basename,
dirname=dirname,
exists=exists,
listed=listed,
startrun=startrun,
time_created=time_created,
time_modified=time_modified,
time_now=time_now,
)
if comment:
print("\n%s:" % comment)
for k, v in sorted(d.items()):
print("%20s: %r" % (k, v))
else:
return d
#############################################################
# @apply
# def data_file():
# def fget( self ):
# return self.__data_file
# def fset( self, value):
# caller = sys._getframe(2).f_code.co_name
# print '%s - %s set self.data_file set to %r' % ( time.strftime('%Y-%m-%d %H:%M:%S'), caller, value )
# self.__data_file = value
# return property(fget, fset)
#############################################################
def _Preflight(self, in_signal_props):
if self.verbose:
print("calling Preflight hook")
self.data_dir = os.path.split(self._resolve_data_file_path())[0]
self.in_signal_props = BciDict(in_signal_props, lazy=True).recurse()
self.out_signal_props = copy.deepcopy(in_signal_props)
self._sigprop_to_sigdim()
self.nominal = BciDict(
{
"SamplesPerSecond": float(self.samplingrate()),
"SamplesPerPacket": float(self.params["SampleBlockSize"]),
},
lazy=True,
)
self.nominal["PacketsPerSecond"] = (
self.nominal["SamplesPerSecond"] / self.nominal["SamplesPerPacket"]
)
self.nominal["SecondsPerPacket"] = (
self.nominal["SamplesPerPacket"] / self.nominal["SamplesPerSecond"]
)
self.data_file = None
self._find_newest_file() # store the list of files that are in the directory before StartRun
# self._data_file_info(comment='Preflight')
# self._data_file_info(-1, comment='Preflight')
#############################################################
def _Initialize(self, in_signal_dim, out_signal_dim):
if self.verbose:
print("calling Initialize hook")
self.packet_count = 0
self._zero_time()
self.in_signal = self._zeros(*self.in_signal_dim)
self.out_signal = self._zeros(*self.out_signal_dim)
self.db.clear()
self.data_file = self._find_newest_file()
# self._data_file_info(comment='Initialize')
# self._data_file_info(-1, comment='Initialize')
#############################################################
def _StartRun(self):
if self.verbose:
print("calling StartRun hook")
print(
"\n%04d-%02d-%02d %02d:%02d:%02d - starting run\n" % time.localtime()[:6]
)
self.db.clear()
self.packet_count = 0
self._zero_time()
self.remember("run")
if self.params["FileFormat"].lower() == "null":
self.data_file = None
else:
newest = self._find_newest_file() # comes out as None if not found
if newest:
self.data_file = newest
if not self.data_file:
self.data_file = self._resolve_data_file_path(
SubjectRun=0
) # find the next-available slot
# NB: self.data_file = 0 would mean "try again in _Process()" but we're no longer using that strategy
# self._data_file_info(comment='StartRun')
# self._data_file_info(-1,comment='StartRun')
th = self._threads.get("share")
if th != None:
th.read("ready", wait=True, remove=True)
th.post("go", wait=True)
#############################################################
def _Process(self, in_signal):
if (
self.data_file == 0
): # this is performed just once after StartRun (not in StartRun itself to avoid a race condition with the FileWriter)
newest = self._find_newest_file() # comes out as None, not 0, if not found
if newest:
self.data_file = newest
else:
print("failed to find newest data file via the OS")
self.data_file = self._resolve_data_file_path()
# self._data_file_info(comment='Process')
# self._data_file_info(-1,comment='Process')
# f = open("D:/process.txt", "a+")
# f = open("D:/process.txt", "w")
# f.write("before in signal:")
# f.write(str(in_signal))
# f.write("\n")
# f.write("in signal:")
self._check_threads()
self.in_signal = self._copy_signal(in_signal)
# f.write(str(in_signal))
# f.write("\n")
if self.out_signal_dim == self.in_signal_dim:
self.out_signal = self._copy_signal(self.in_signal)
# f.write("out BCI
else:
self.out_signal = self._zeros(*self.out_signal_dim)
# f.write("out BCI
self._check_threads()
# f.close()
return (
self.out_signal
) # the subclass _Process (e.g. BciGenericApplication._Process) will be responsible for calling _encode_signal()
#############################################################
def _StopRun(self):
if self.verbose:
print("calling StopRun hook")
print("\n%04d-%02d-%02d %02d:%02d:%02d - run stopped" % time.localtime()[:6])
if self.data_file:
print(" data file:", self.data_file)
if len(self.db):
print("\ndebug warnings in self.db:")
print(dict([(x[0], len(x[1])) for x in list(self.db.items())]))
self._oldstates.clear()
print()
th = self._threads.get("share")
if th != None:
th.post("stop", wait=True)
#############################################################
def _Resting(self):
if self.verbose:
print("calling Resting hook")
#############################################################
def _Destruct(self):
if self.verbose:
print("calling Destruct hook")
if "pylab" in sys.modules:
import pylab
pylab.close("all")
##########################################################
def _call_hook(self, method, *pargs, **kwargs):
retval = None
try:
retval = method(*pargs, **kwargs)
except:
self._handle_error()
self._check_threads()
return retval
##########################################################
def _sharing_setup(self, indims, outdims, statelist):