-
Notifications
You must be signed in to change notification settings - Fork 40
/
brainworkshop.py
4848 lines (4305 loc) · 192 KB
/
brainworkshop.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
#!/usr/bin/env python
# This Python file uses the following encoding: utf-8
#------------------------------------------------------------------------------
# Brain Workshop: a Dual N-Back game in Python
#
# This is a fork of the popular Brain Workshop game. Development on the original
# has not happened for many years. The fork is available at:
# https://github.com/brain-workshop/brainworkshop
#
# Tutorial, installation instructions & links to the dual n-back community
# are available at the original Brain Workshop web site:
#
# http://brainworkshop.net/
#
# Also see Readme.txt.
#
# Copyright (C) 2009-2011: Paul Hoskinson (plhosk@gmail.com)
# Copyright (C) 2017-2018: Samantha McVey (samantham@posteo.net)
# SPDX-License-Identifier: GPL-2.0-or-later
#
# This program 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 2
# of the License, or (at your option) any later version.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not see https://www.gnu.org/licenses/gpl-2.0.html
#------------------------------------------------------------------------------
# Use python3 style division for consistency
from __future__ import division
VERSION = '5.0'
def debug_msg(msg):
if DEBUG:
if isinstance(msg, Exception):
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print('debug: %s Line %i' % (str(msg), exc_tb.tb_lineno))
else:
print('debug: %s' % str(msg))
def error_msg(msg, e = None):
if DEBUG and e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print("ERROR: %s\n\t%s Line %i" % (msg, e, exc_tb.tb_lineno))
else:
print("ERROR: %s" % msg)
def get_argv(arg):
if arg in sys.argv:
index = sys.argv.index(arg)
if index + 1 < len(sys.argv):
return sys.argv[index + 1]
else:
error_msg("Expected an argument following %s" % arg)
exit(1)
import random, os, sys, socket, webbrowser, time, math, traceback, datetime, errno
if sys.version_info >= (3,0):
import urllib.request, configparser as ConfigParser
from io import StringIO
import pickle
else:
import urllib2 as urllib, ConfigParser, StringIO
import cPickle as pickle
from decimal import Decimal
from time import strftime
from datetime import date
import gettext
if sys.version_info >= (3,0):
# TODO check if this is right
gettext.install('messages', localedir='res/i18n')
else:
gettext.install('messages', localedir='res/i18n', unicode=True)
# Clinical mode? Clinical mode sets cfg.JAEGGI_MODE = True, enforces a minimal user
# interface, and saves results into a binary file (default 'logfile.dat') which
# should be more difficult to tamper with.
CLINICAL_MODE = False
# Internal static options not available in config file.
CONFIG_OVERWRITE_IF_OLDER_THAN = '4.8'
NOVBO = True
VSYNC = False
DEBUG = False
FOLDER_RES = 'res'
FOLDER_DATA = 'data'
CONFIGFILE = 'config.ini'
STATS_BINARY = 'logfile.dat'
USER = 'default'
#CHARTFILE = {2:'chart-02-dnb.txt', 3:'chart-03-tnb.txt', 4:'chart-04-dlnb.txt', 5:'chart-05-tlnb.txt',
#6:'chart-06-qlnb.txt',7:'chart-07-anb.txt', 8:'chart-08-danb.txt', 9:'chart-09-tanb.txt',
#10:'chart-10-ponb.txt', 11:'chart-11-aunb.txt'}
ATTEMPT_TO_SAVE_STATS = True
STATS_SEPARATOR = ','
WEB_SITE = 'http://brainworkshop.net/'
WEB_TUTORIAL = 'http://brainworkshop.net/tutorial.html'
CLINICAL_TUTORIAL = WEB_TUTORIAL # FIXME: Add tutorial catered to clinical trials
WEB_DONATE = 'http://brainworkshop.net/donate.html'
WEB_VERSION_CHECK = 'http://brainworkshop.net/version.txt'
WEB_PYGLET_DOWNLOAD = 'http://pyglet.org'
WEB_FORUM = 'https://groups.google.com/group/brain-training'
WEB_MORSE = 'https://en.wikipedia.org/wiki/Morse_code'
TIMEOUT_SILENT = 3
TICKS_MIN = 3
TICKS_MAX = 50
TICK_DURATION = 0.1
DEFAULT_WINDOW_WIDTH = 912
DEFAULT_WINDOW_HEIGHT = 684
preventMusicSkipping = True
def from_width_center(offset):
return int( (window.width/2) + offset * (window.width / DEFAULT_WINDOW_WIDTH) )
def from_height_center(offset):
return int( (window.height/2) + offset * (window.height / DEFAULT_WINDOW_HEIGHT) )
def width_center():
return int(window.width/2)
def height_center():
return int(window.height/2)
def from_top_edge(from_edge):
return int(window.height - (from_edge * window.height/DEFAULT_WINDOW_HEIGHT))
def from_bottom_edge(from_edge):
return int(from_edge * (window.height/DEFAULT_WINDOW_HEIGHT))
def from_right_edge(from_edge):
return int(window.width - (from_edge * window.width/DEFAULT_WINDOW_WIDTH))
def from_left_edge(from_edge):
return int(from_edge * window.width/DEFAULT_WINDOW_WIDTH)
def scale_to_width(fraction):
return int(fraction * window.width/DEFAULT_WINDOW_WIDTH)
def scale_to_height(fraction):
return int(fraction * window.height/DEFAULT_WINDOW_HEIGHT)
def calc_fontsize(size):
return size * (window.height/DEFAULT_WINDOW_HEIGHT)
def calc_dpi(size = 100):
return int(size * ((window.width + window.height)/(DEFAULT_WINDOW_WIDTH + DEFAULT_WINDOW_HEIGHT)))
def get_pyglet_media_Player():
try:
my_player = pyglet.media.Player()
except Exception as e:
debug_msg(e)
my_player = pyglet.media.ManagedSoundPlayer()
return my_player
# some functions to assist in path determination
def main_is_frozen():
return hasattr(sys, "frozen") # py2exe
def get_main_dir():
if main_is_frozen():
return os.path.dirname(sys.executable)
return sys.path[0]
def get_settings_path(name):
'''Get a directory to save user preferences.
Copied from pyglet.resource so we don't have to load that module
(which recursively indexes . on loading -- wtf?).'''
if sys.platform in ('cygwin', 'win32'):
if 'APPDATA' in os.environ:
return os.path.join(os.environ['APPDATA'], name)
else:
return os.path.expanduser('~/%s' % name)
elif sys.platform == 'darwin':
return os.path.expanduser('~/Library/Application Support/%s' % name)
else: # on *nix, we want it to be lowercase and without spaces (~/.brainworkshop/data)
return os.path.expanduser('~/.%s' % (name.lower().replace(' ', '')))
def get_data_dir():
rtrn = get_argv('--datadir')
if rtrn:
return rtrn
else:
return os.path.join(get_settings_path('Brain Workshop'), FOLDER_DATA)
def get_res_dir():
rtrn = get_argv('--resdir')
if rtrn:
return rtrn
else:
return os.path.join(get_main_dir(), FOLDER_RES)
def edit_config_ini():
if sys.platform == 'win32':
cmd = 'notepad'
elif sys.platform == 'darwin':
cmd = 'open'
else:
cmd = 'xdg-open'
print(cmd + ' "' + os.path.join(get_data_dir(), CONFIGFILE) + '"')
window.on_close()
import subprocess
subprocess.call((cmd + ' "' + os.path.join(get_data_dir(), CONFIGFILE) + '"'), shell=True)
sys.exit(0)
def quit_with_error(message='', postmessage='', quit=True, trace=True):
if message:
sys.stderr.write(message + '\n')
if trace:
sys.stderr.write(_("Full text of error:\n"))
traceback.print_exc()
if postmessage:
sys.stderr.write('\n\n' + postmessage)
if quit:
sys.exit(1)
CONFIGFILE_DEFAULT_CONTENTS = """
######################################################################
# Brain Workshop configuration file
# generated by Brain Workshop """ + VERSION + """
#
# To change configuration options:
# 1. Edit this file as desired,
# 2. Save the file,
# 3. Launch Brain Workshop to see the changes.
#
# Every line beginning with # is ignored by the program.
#
# Please see the Brain Workshop web site for more information:
# http://brainworkshop.net
#
# The configuration options begin below.
######################################################################
[DEFAULT]
# Jaeggi-style interface with default scoring model?
# Choose either this option or JAEGGI_MODE but not both.
# This mode allows access to Manual mode, the extra sound sets, and the
# additional game modes of Brain Workshop while presenting the game in
# the more challenging Jaeggi-style interface featured in the original study.
# With the default BW sequence generation model, the visual and auditory
# sequences are more randomized and unpredictable than they are in Jaeggi
# mode. The only effect of this option is to set the following options:
# ANIMATE_SQUARES = False, OLD_STYLE_SQUARES = True,
# OLD_STYLE_SHARP_CORNERS = True, SHOW_FEEDBACK = False,
# GRIDLINES = False, CROSSHAIRS = True, BLACK_BACKGROUND = True,
# WINDOW_FULLSCREEN = True, HIDE_TEXT = True, FIELD_EXPAND = True
# Default: False
JAEGGI_INTERFACE_DEFAULT_SCORING = False
# Jaeggi mode?
# Choose either this option or JAEGGI_INTERFACE_DEFAULT_SCORING but not both.
# This mode emulates the scoring model used in the original study protocol.
# It counts non-matches with no inputs as correct (instead of ignoring them).
# It also forces 4 visual matches, 4 auditory matches, and 2 simultaneous
# matches per session, resulting in less randomized and more predictable
# sequences than in the default BW sequence generation model.
# Different thresholds are used to reflect the modified scoring system
# (see below). Access to Manual mode, additional game modes and sound sets
# is disabled in Jaeggi mode.
# Default: False
JAEGGI_MODE = False
# The default BW scoring system uses the following formula:
# score = TP / (TP + FP + FN)
# where TP is a true positive response, FN is a false negative, etc. All
# stimulus modalities are summed together for this formula.
# The Jaeggi mode scoring system scores uses the following formula:
# score = (TP + TN) / (TP + TN + FP + FN)
# Each modality is scored separately, and the score for the whole session
# is equal to the lowest score of any modality.
# Default: False
JAEGGI_SCORING = False
# In Jaeggi Mode, adjust the default appearance and sounds of Brain Workshop
# to emulate the original software used in the study?
# If this is enabled, the following options will be set:
# AUDIO1_SETS = ['letters'], ANIMATE_SQUARES = False,
# OLD_STYLE_SQUARES = True, OLD_STYLE_SHARP_CORNERS = True,
# SHOW_FEEDBACK = False, GRIDLINES = False, CROSSHAIRS = True
# (note: this option only takes effect if JAEGGI_MODE is set to True)
# Default: True
JAEGGI_FORCE_OPTIONS = True
# In Jaeggi Mode, further adjust the appearance to match the original
# software as closely as possible?
# If this is enabled, the following options will be set:
# BLACK_BACKGROUND = True, WINDOW_FULLSCREEN = True,
# HIDE_TEXT = True, FIELD_EXPAND = True
# (note: this option only takes effect if JAEGGI_MODE is set to True)
# Default: True
JAEGGI_FORCE_OPTIONS_ADDITIONAL = True
# Allow Mouse to be used for input?
# Only for dual n-back. Automatically disabled in JAEGGI_MODE.
ENABLE_MOUSE = True
# Background color: True = black, False = white.
# Default: False
BLACK_BACKGROUND = False
# Begin in full screen mode?
# Setting this to False will begin in windowed mode.
# Default: False
WINDOW_FULLSCREEN = False
# Window size in windowed mode.
# Minimum recommended values: width = 800, height = 600
WINDOW_WIDTH = 912
WINDOW_HEIGHT = 684
# Skip title screen?
SKIP_TITLE_SCREEN = False
# Display feedback of correct/incorrect input?
# Default: True
SHOW_FEEDBACK = True
# Hide text during game? (this can be toggled in-game by pressing F8)
# Default: False
HIDE_TEXT = False
# Expand the field (squares) to fill the entire height of the screen?
# Note: this should only be used with HIDE_TEXT = True.
FIELD_EXPAND = False
# Show grid lines and crosshairs?
GRIDLINES = True
CROSSHAIRS = True
# Set the color of the square in non-Color N-Back modes.
# This also affects Dual Combination N-Back and Arithmetic N-Back.
# 1 = blue, 2 = cyan, 3 = green, 4 = grey,
# 5 = magenta, 6 = red, 7 = white, 8 = yellow
# Default: [1, 3, 8, 6]
VISUAL_COLORS = [1, 3, 8, 6]
# Specify image sets here. This is a list of subfolders in the res\sprites\
# folder which may be selected in Image mode.
# The first item in the list is the default which is loaded on startup.
IMAGE_SETS = ['polygons-basic', 'national-park-service', 'pentominoes',
'tetrominoes-fixed', 'cartoon-faces']
# This selects which sounds to use for audio n-back tasks.
# Select any combination of letters, numbers, the NATO Phonetic Alphabet
# (Alpha, Bravo, Charlie, etc), the C scale on piano, and morse code.
# AUDIO1_SETS = ['letters', 'morse', 'nato', 'numbers', 'piano']
AUDIO1_SETS = ['letters']
# Sound configuration for the Dual Audio (A-A) task.
# Possible values for CHANNEL_AUDIO1 and CHANNEL_AUDIO2:
# 'left' 'right' 'center'
AUDIO2_SETS = ['letters']
CHANNEL_AUDIO1 = 'left'
CHANNEL_AUDIO2 = 'right'
# In multiple-stimulus modes, more than one visual stimulus is presented at
# the same time. Each of the simultaneous visual stimuli has an ID number
# associated with either its color or its image. Which should we use, by
# default?
# Options: 'color' or 'image'
MULTI_MODE = 'color'
# Animate squares?
ANIMATE_SQUARES = False
# Use the flat, single-color squares like in versions prior to 4.1?
# Also, use sharp corners or rounded corners?
OLD_STYLE_SQUARES = False
OLD_STYLE_SHARP_CORNERS = False
# Start in Manual mode?
# If this is False, the game will start in standard mode.
# Default: False
MANUAL = False
USE_MUSIC_MANUAL = False
# Starting game mode.
# Possible values:
# 2:'Dual',
# 3:'P-C-A',
# 4:'Dual Combination',
# 5:'Tri Combination',
# 6:'Quad Combination',
# 7:'Arithmetic',
# 8:'Dual Arithmetic',
# 9:'Triple Arithmetic',
# 10:'Position',
# 11:'Sound',
# 20:'P-C',
# 21:'P-I',
# 22:'C-A',
# 23:'I-A',
# 24:'C-I',
# 25:'P-C-I',
# 26:'P-I-A',
# 27:'C-I-A',
# 28:'Quad',
# 100:'A-A',
# 101:'P-A-A',
# 102:'C-A-A',
# 103:'I-A-A',
# 104:'P-C-A-A',
# 105:'P-I-A-A',
# 106:'C-I-A-A',
# 107:'P-C-I-A-A' (Pentuple)
# 128+x: Crab mode
# 256+x: Double mode (can be combined with crab mode)
# 512+x: Triple mode
# 768+x: Quadruple mode
# Note: if JAEGGI_MODE is True, only Dual N-Back will be available.
# Default: 2
GAME_MODE = 2
# Default starting n-back levels.
# must be greater than or equal to 1.
# Look above to find the corresponding mode number. Add a line for the mode
# if it doesn't already exist. Modes not specifically listed here will
# use BACK_DEFAULT instead.
#
# Crab and multi-modes will default to the level associated with the modes
# they're based on (if it's listed) or to BACK_DEFAULT (if it's not listed).
BACK_DEFAULT = 2
BACK_4 = 1
BACK_5 = 1
BACK_6 = 1
BACK_7 = 1
BACK_8 = 1
BACK_9 = 1
# N-back level resetting:
# Should we start at the default N-back level for that game mode every
# day, or should we resume at the last day's level?
RESET_LEVEL = False
# Use Variable N-Back by default?
# 0 = static n-back (default)
# 1 = variable n-back
VARIABLE_NBACK = 0
# Number of 0.1 second intervals per trial.
# Must be greater than or equal to 4 (ie, 0.4 seconds)
# Look above to find the corresponding mode number. Add a line for the mode
# if it doesn't already exist. Modes not specifically listed here will
# use TICKS_DEFAULT instead.
#
# Crab and multi-modes will default to the ticks associated with the modes
# they're based on, *plus an optional bonus*, unless you add a line here to
# give it a specific value. Any bonuses will be ignored for specified modes.
TICKS_DEFAULT = 30
TICKS_4 = 35
TICKS_5 = 35
TICKS_6 = 35
TICKS_7 = 40
TICKS_8 = 40
TICKS_9 = 40
# Tick bonuses for crab and multi-modes not listed above. Can be negative
# if you're a masochist.
BONUS_TICKS_CRAB = 0
BONUS_TICKS_MULTI_2 = 5
BONUS_TICKS_MULTI_3 = 10
BONUS_TICKS_MULTI_4 = 15
# The number of trials per session equals
# NUM_TRIALS + NUM_TRIALS_FACTOR * n ^ NUM_TRIALS_EXPONENT,
# where n is the current n-back level.
# Default base number of trials per session.
# Must be greater than or equal to 1.
# Default: 20
NUM_TRIALS = 20
NUM_TRIALS_FACTOR = 1
NUM_TRIALS_EXPONENT = 2
# Thresholds for n-back level advancing & fallback.
# Values are 0-100.
# Set THRESHOLD_ADVANCE to 101 to disable automatic level advance.
# Set THRESHOLD_FALLBACK to 0 to disable fallback.
# FALLBACK_SESSIONS controls the number of sessions below
# the fallback threshold that will trigger a level decrease.
# Note: in Jaeggi mode, only JAEGGI_ADVANCE and JAEGGI_FALLBACK
# are used.
# Defaults: 80, 50, 3, 90, 75
THRESHOLD_ADVANCE = 80
THRESHOLD_FALLBACK = 50
THRESHOLD_FALLBACK_SESSIONS = 3
JAEGGI_ADVANCE = 90
JAEGGI_FALLBACK = 75
# Show feedback regarding session performance.
# If False, forces USE_MUSIC and USE_APPLAUSE to also be False.
USE_SESSION_FEEDBACK = True
# Music/SFX options.
# Volumes are from 0.0 (silent) to 1.0 (full)
# Defaults: True, True, 1.0, 1.0
USE_MUSIC = True
USE_APPLAUSE = True
MUSIC_VOLUME = 1.0
SFX_VOLUME = 1.0
# Specify an alternate stats file.
# Default: stats.txt
STATSFILE = stats.txt
# Specify the hour the stats will roll over to a new day [0-23]
ROLLOVER_HOUR = 4
# Version check on startup (http protocol)?
# Default: False
VERSION_CHECK_ON_STARTUP = False
# The chance that a match will be generated by force, in addition to the
# inherent 1/8 chance. High settings will cause repetitive sequences to be
# generated. Increasing this value will make the n-back task significantly
# easier if you're using JAGGI_SCORING = False.
# The value must be a decimal from 0 to 1.
# Note: this option has no effect in Jaeggi mode.
# Default: 0.125
CHANCE_OF_GUARANTEED_MATCH = 0.125
# The chance that a near-miss will be generated to help train resolution of
# cognitive interference. For example, in 5-back, a near-miss might be
# ABCDE-FGDJK--the "D" comes one trial earlier than would be necessary
# for a correct match. Near-misses can be one trial short of a match,
# one trial late, or N trials late (would have been a match if it was one
# "cycle" ago). This setting will never accidentally generate a correct match
# in the case of repeating stimuli if it can be avoided.
# Default: 0.125
DEFAULT_CHANCE_OF_INTERFERENCE = 0.125
# How often should Brain Workshop panhandle for a donation? After every
# PANHANDLE_FREQUENCY sessions, Brain Workshop will annoy you slightly by
# asking for money. Set this to 0 if you have a clear conscience.
# Default: 100
PANHANDLE_FREQUENCY = 100
# Arithmetic mode settings.
ARITHMETIC_MAX_NUMBER = 12
ARITHMETIC_USE_NEGATIVES = False
ARITHMETIC_USE_ADDITION = True
ARITHMETIC_USE_SUBTRACTION = True
ARITHMETIC_USE_MULTIPLICATION = True
ARITHMETIC_USE_DIVISION = True
ARITHMETIC_ACCEPTABLE_DECIMALS = ['0.1', '0.2', '0.3', '0.4', '0.5', '0.6',
'0.7', '0.8', '0.9', '0.125', '0.25', '0.375', '0.625', '0.75', '0.875',
'0.15', '0.35', '0.45', '0.55', '0.65', '0.85', '0.95',]
# Colors for the color n-back task
# format: (red, green, blue, 255)
# Note: Changing these colors will have no effect in Dual or
# Triple N-Back unless OLD_STYLE_SQUARES is set to True.
# the _BLK colors are used when BLACK_BACKGROUND is set to True.
COLOR_1 = (0, 0, 255, 255)
COLOR_2 = (0, 255, 255, 255)
COLOR_3 = (0, 255, 0, 255)
COLOR_4 = (48, 48, 48, 255)
COLOR_4_BLK = (255, 255, 255, 255)
COLOR_5 = (255, 0, 255, 255)
COLOR_6 = (255, 0, 0, 255)
COLOR_7 = (208, 208, 208, 255)
COLOR_7_BLK = (64, 64, 64, 255)
COLOR_8 = (255, 255, 0, 255)
# text color
COLOR_TEXT = (0, 0, 0, 255)
COLOR_TEXT_BLK = (240, 240, 240, 255)
# input label color
COLOR_LABEL_CORRECT = (64, 255, 64, 255)
COLOR_LABEL_OOPS = (64, 64, 255, 255)
COLOR_LABEL_INCORRECT = (255, 64, 64, 255)
# Saccadic eye movement options.
# Delay = number of seconds to wait before switching the dot
# Repetitions = number of times to switch the dot
SACCADIC_DELAY = 0.5
SACCADIC_REPETITIONS = 60
######################################################################
# Keyboard definitions.
# The following keys cannot be used: ESC, X, P, F8, F10.
# You can find the codes using python "from pyglet.window import key; print(key.A)":
# https://pyglet.readthedocs.io/en/latest/modules/window_key.html#module-pyglet.window.key
######################################################################
# Position match. Default: 97 (A)
KEY_POSITION1 = 97
# Sound match. Default: 108 (L)
KEY_AUDIO = 108
# Sound2 match. Default: 59 (Semicolon ;)
KEY_AUDIO2 = 59
# Color match. Default: 102 (F)
KEY_COLOR = 102
# Image match. Default: 106 (J)
KEY_IMAGE = 106
# Position match, multiple-stimulus mode.
# Defaults: 115 (S), 100 (D), 102 (F)
KEY_POSITION2 = 115
KEY_POSITION3 = 100
KEY_POSITION4 = 102
# Color/image match, multiple-stimulus mode. KEY_VIS1 will be used instead
# of KEY_COLOR or KEY_IMAGE.
# Defaults: 103 (G), 104 (H), 106 (J), 107 (K)
KEY_VIS1 = 103
KEY_VIS2 = 104
KEY_VIS3 = 106
KEY_VIS4 = 107
# These are used in the Combination N-Back modes.
# Visual & n-visual match. Default: 115 (S)
KEY_VISVIS = 115
# Visual & n-audio match. Default: 100 (D)
KEY_VISAUDIO = 100
# Sound & n-visual match. Default: 106 (J)
KEY_AUDIOVIS = 106
# Advance to the next trial in self-paced mode. Default: 65293 (return/enter).
# You may also like space (32).
KEY_ADVANCE = 65293
######################################################################
# This is the end of the configuration file.
######################################################################
"""
class dotdict(dict):
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
def dump_pyglet_info():
from pyglet import info
oldStdout = sys.stdout
pygletDumpPath = os.path.join(get_data_dir(), 'dump.txt')
sys.stdout = open(pygletDumpPath, 'w')
info.dump()
sys.stdout.close()
sys.stdout = oldStdout
print("pyglet info dumped to %s" % pygletDumpPath)
sys.exit()
# parse config file & command line options
if '--debug' in sys.argv:
DEBUG = True
if '--vsync' in sys.argv or sys.platform == 'darwin':
VSYNC = True
if '--dump' in sys.argv:
dump_pyglet_info()
if get_argv('--configfile'):
CONFIGFILE = get_argv('--configfile')
messagequeue = [] # add messages generated during loading here
class Message:
def __init__(self, msg):
if not 'window' in globals():
print(msg) # dump it to console just in case
messagequeue.append(msg) # but we'll display this later
return
self.batch = pyglet.graphics.Batch()
self.label = pyglet.text.Label(msg,
font_name=self.fontlist_serif,
color=cfg.COLOR_TEXT,
batch=self.batch,
multiline=True,
width=(4*window.width)/5,
font_size=calc_fontsize(14),
x=width_center(), y=height_center(),
anchor_x='center', anchor_y='center')
window.push_handlers(self.on_key_press, self.on_draw)
self.on_draw()
def on_key_press(self, sym, mod):
if sym:
self.close()
return pyglet.event.EVENT_HANDLED
def close(self):
return window.remove_handlers(self.on_key_press, self.on_draw)
def on_draw(self):
window.clear()
self.batch.draw()
return pyglet.event.EVENT_HANDLED
def load_last_user(lastuserpath):
path = os.path.join(get_data_dir(), lastuserpath)
if os.path.isfile(path):
debug_msg("Trying to load '%s'" % (path))
try:
f = open(path, 'rb')
p = pickle.Unpickler(f)
options = p.load()
del p
f.close()
except Exception as e:
print("%s\nDue to error, continuing as user 'default'" % e)
# Delete the pickle file, since it wasn't able to be loaded.
os.remove(path)
return
if options['USER'] == '':
print("Last loaded user is an empty string! Setting it to default instead")
options['USER'] = "default"
if not options['USER'].lower() == 'default':
global USER
global STATS_BINARY
global CONFIGFILE
USER = options['USER']
CONFIGFILE = USER + '-config.ini'
STATS_BINARY = USER + '-logfile.dat'
def save_last_user(lastuserpath):
try:
f = open(os.path.join(get_data_dir(), lastuserpath), 'wb')
p = pickle.Pickler(f)
p.dump({'USER': USER})
# also do date of last session?
except Exception as e:
error_msg("Could not save last user", e)
pass
def parse_config(configpath):
if not (CLINICAL_MODE and configpath == 'config.ini'):
fullpath = os.path.join(get_data_dir(), configpath)
if not os.path.isfile(fullpath):
rewrite_configfile(configpath, overwrite=False)
# The following is a routine to overwrite older config files with the new one.
oldconfigfile = open(fullpath, 'r+')
while oldconfigfile:
line = oldconfigfile.readline()
if line == '': # EOF reached. string 'generated by Brain Workshop' not found
oldconfigfile.close()
rewrite_configfile(configpath, overwrite=True)
break
if line.find('generated by Brain Workshop') > -1:
splitline = line.split()
version = splitline[5]
if version < CONFIG_OVERWRITE_IF_OLDER_THAN:
oldconfigfile.close()
os.rename(fullpath, fullpath + '.' + version + '.bak')
rewrite_configfile(configpath, overwrite=True)
break
oldconfigfile.close()
try:
config = ConfigParser.ConfigParser()
config.read(os.path.join(get_data_dir(), configpath))
except Exception as e:
debug_msg(e)
if configpath != 'config.ini':
quit_with_error(_('Unable to load config file: %s') %
os.path.join(get_data_dir(), configpath))
defaultconfig = ConfigParser.ConfigParser()
if sys.version_info >= (3,):
defaultconfig.read_file(StringIO(CONFIGFILE_DEFAULT_CONTENTS))
else:
defaultconfig.readfp(StringIO.StringIO(CONFIGFILE_DEFAULT_CONTENTS))
def try_eval(text): # this is a one-use function for config parsing
try: return eval(text)
except: return text
cfg = dotdict()
if CLINICAL_MODE and CONFIGFILE == 'config.ini': configs = (defaultconfig,)
else: configs = (defaultconfig, config)
for config in configs: # load defaultconfig first, in case of incomplete user's config.ini
config_items = [(k.upper(), try_eval(v)) for k, v in config.items('DEFAULT')]
cfg.update(config_items)
if not 'CHANCE_OF_INTERFERENCE' in cfg:
cfg.CHANCE_OF_INTERFERENCE = cfg.DEFAULT_CHANCE_OF_INTERFERENCE
rtrn = get_argv('--statsfile')
if rtrn:
cfg.STATSFILE = rtrn
return cfg
def rewrite_configfile(configfile, overwrite=False):
global STATS_BINARY
if USER.lower() == 'default':
statsfile = 'stats.txt'
STATS_BINARY = 'logfile.dat' # or cmd-line-opts use non-default files
else:
statsfile = USER + '-stats.txt'
try:
os.stat(os.path.join(get_data_dir(), configfile))
except OSError as e:
debug_msg(e)
overwrite = True
if overwrite:
f = open(os.path.join(get_data_dir(), configfile), 'w')
newconfigfile_contents = CONFIGFILE_DEFAULT_CONTENTS.replace(
'stats.txt', statsfile)
f.write(newconfigfile_contents)
f.close()
# let's hope nobody uses '-stats.txt' in their username
STATS_BINARY = statsfile.replace('-stats.txt', '-logfile.dat')
try:
os.stat(os.path.join(get_data_dir(), statsfile))
except OSError as e:
debug_msg(e)
f = open(os.path.join(get_data_dir(), statsfile), 'w')
f.close()
try:
os.stat(os.path.join(get_data_dir(), STATS_BINARY))
except OSError:
f = open(os.path.join(get_data_dir(), STATS_BINARY), 'w')
f.close()
try:
path = get_data_dir()
os.makedirs(path)
except OSError as e:
if e.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
load_last_user('defaults.ini')
cfg = parse_config(CONFIGFILE)
if CLINICAL_MODE:
cfg.JAEGGI_INTERFACE_DEFAULT_SCORING = False
cfg.JAEGGI_MODE = True
cfg.JAEGGI_FORCE_OPTIONS = True
cfg.JAEGGI_FORCE_OPTIONS_ADDITIONAL = True
cfg.SKIP_TITLE_SCREEN = True
cfg.USE_MUSIC = False
elif cfg.JAEGGI_INTERFACE_DEFAULT_SCORING:
cfg.ANIMATE_SQUARES = False
cfg.OLD_STYLE_SQUARES = True
cfg.OLD_STYLE_SHARP_CORNERS = True
cfg.GRIDLINES = False
cfg.CROSSHAIRS = True
cfg.SHOW_FEEDBACK = False
cfg.BLACK_BACKGROUND = True
cfg.WINDOW_FULLSCREEN = True
cfg.HIDE_TEXT = True
cfg.FIELD_EXPAND = True
if cfg.JAEGGI_MODE and not cfg.JAEGGI_INTERFACE_DEFAULT_SCORING:
cfg.GAME_MODE = 2
cfg.VARIABLE_NBACK = 0
cfg.JAEGGI_SCORING = True
if cfg.JAEGGI_FORCE_OPTIONS:
cfg.AUDIO1_SETS = ['letters']
cfg.ANIMATE_SQUARES = False
cfg.OLD_STYLE_SQUARES = True
cfg.OLD_STYLE_SHARP_CORNERS = True
cfg.GRIDLINES = False
cfg.CROSSHAIRS = True
cfg.SHOW_FEEDBACK = False
cfg.THRESHOLD_FALLBACK_SESSIONS = 1
cfg.NUM_TRIALS_FACTOR = 1
cfg.NUM_TRIALS_EXPONENT = 1
if cfg.JAEGGI_FORCE_OPTIONS_ADDITIONAL:
cfg.BLACK_BACKGROUND = True
cfg.WINDOW_FULLSCREEN = True
cfg.HIDE_TEXT = True
cfg.FIELD_EXPAND = True
if not cfg.USE_SESSION_FEEDBACK:
cfg.USE_MUSIC = False
cfg.USE_APPLAUSE = False
if cfg.BLACK_BACKGROUND:
cfg.COLOR_TEXT = cfg.COLOR_TEXT_BLK
def get_threshold_advance():
if cfg.JAEGGI_SCORING:
return cfg.JAEGGI_ADVANCE
return cfg.THRESHOLD_ADVANCE
def get_threshold_fallback():
if cfg.JAEGGI_SCORING:
return cfg.JAEGGI_FALLBACK
return cfg.THRESHOLD_FALLBACK
# this function checks if a new update for Brain Workshop is available.
update_available = False
update_version = 0
def update_check():
global update_available
global update_version
socket.setdefaulttimeout(TIMEOUT_SILENT)
if sys.version_info >= (3,0):
req = urllib.request.Request(WEB_VERSION_CHECK)
else:
req = urllib.Request(WEB_VERSION_CHECK)
try:
response = urllib.urlopen(req)
version = response.readline().strip()
except Exception as e:
debug_msg(e)
return
if version > VERSION: # simply comparing strings works just fine
update_available = True
update_version = version
if cfg.VERSION_CHECK_ON_STARTUP and not CLINICAL_MODE:
update_check()
try:
# workaround for pyglet.gl.ContextException error on certain video cards.
os.environ["PYGLET_SHADOW_WINDOW"] = "0"
import pyglet
if NOVBO: pyglet.options['graphics_vbo'] = False
from pyglet.window import key
# shapes submodule is available with pyglet >=1.5.4
have_shapes = hasattr(pyglet, 'shapes')
except Exception as e:
debug_msg(e)
quit_with_error(_('Error: unable to load pyglet. If you already installed pyglet, please ensure ctypes is installed. Please visit %s') % WEB_PYGLET_DOWNLOAD)
audio_driver = pyglet.media.get_audio_driver()
debug_msg("Loaded audio driver=" + audio_driver.__class__.__name__)
if audio_driver.__class__.__name__ == "SilentDriver":
quit_with_error(_('No suitable audio driver could be loaded.'))
# Initialize resources (sounds and images)
#
# --- BEGIN RESOURCE INITIALIZATION SECTION ----------------------------------
#
res_path = get_res_dir()
if not os.access(res_path, os.F_OK):
quit_with_error(_('Error: the resource folder\n%s') % res_path +
_(' does not exist or is not readable. Exiting'), trace=False)
if pyglet.version < '1.1':
quit_with_error(_('Error: pyglet 1.1 or greater is required.\n') +
_('You probably have an older version of pyglet installed.\n') +
_('Please visit %s') % WEB_PYGLET_DOWNLOAD, trace=False)
supportedtypes = {'sounds' :['wav'],
'music' :['wav', 'ogg', 'mp3', 'aac', 'mp2', 'ac3', 'm4a'], # what else?
'sprites':['png', 'jpg', 'bmp']}
def test_music():
try:
import pyglet
if pyglet.version >= '1.4':
from pyglet.media import have_ffmpeg
pyglet.media.have_avbin = have_ffmpeg()
if not pyglet.media.have_avbin:
cfg.USE_MUSIC = False
else:
try:
from pyglet.media import avbin
except Exception as e:
debug_msg(e)
pyglet.lib.load_library('avbin')
if pyglet.version >= '1.2': # temporary workaround for defect in pyglet svn 2445
pyglet.media.have_avbin = True
# On Windows with Data Execution Protection enabled (on by default on Vista),
# an exception will be raised when use of avbin is attempted:
# WindowsError: exception: access violation writing [ADDRESS]
# The file doesn't need to be in a avbin-specific format,
# since pyglet will use avbin over riff whenever it's detected.
# Let's find an audio file and try to load it to see if avbin works.
opj = os.path.join
opj = os.path.join
def look_for_music(path):
files = [p for p in os.listdir(path) if not p.startswith('.') and not os.path.isdir(opj(path, p))]
for f in files:
ext = f.lower()[-3:]
if ext in ['wav', 'ogg', 'mp3', 'aac', 'mp2', 'ac3', 'm4a'] and not ext in ('wav'):
return [opj(path, f)]
dirs = [opj(path, p) for p in os.listdir(path) if not p.startswith('.') and os.path.isdir(opj(path, p))]
results = []
for d in dirs:
results.extend(look_for_music(d))
if results: return results
return results
music_file = look_for_music(res_path)
if music_file:
# The first time we load a file should trigger the exception
music_file = music_file[0]
loaded_music = pyglet.media.load(music_file, streaming=False)
del loaded_music
else:
cfg.USE_MUSIC = False
except ImportError as e:
debug_msg(e)
cfg.USE_MUSIC = False
if pyglet.version >= '1.2':
pyglet.media.have_avbin = False
print( _('AVBin not detected. Music disabled.'))
print( _('Download AVBin from: https://avbin.github.io'))