-
Notifications
You must be signed in to change notification settings - Fork 11
/
brainworkshop.pyw
4352 lines (3846 loc) · 176 KB
/
brainworkshop.pyw
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
#------------------------------------------------------------------------------
# Brain Workshop: a Dual N-Back game in Python
#
# Tutorial, installation instructions & links to the dual n-back community
# are available at the Brain Workshop web site:
#
# http://brainworkshop.sourceforge.net/
#
# Also see Readme.txt.
#
# Copyright (C) 2009-2010: Paul Hoskinson ([email protected])
#
# The code is GPL licensed (http://www.gnu.org/copyleft/gpl.html)
#------------------------------------------------------------------------------
VERSION = '4.8.1'
import random, os, sys, imp, socket, urllib2, webbrowser, time, math, ConfigParser, StringIO, traceback
import cPickle as pickle
from decimal import Decimal
from time import strftime
from datetime import date
import gettext
gettext.install('brainworkshop', localedir='.', 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.sourceforge.net/'
WEB_TUTORIAL = 'http://brainworkshop.sourceforge.net/#tutorial'
CLINICAL_TUTORIAL = WEB_TUTORIAL # FIXME: Add tutorial catered to clinical trials
WEB_DONATE = 'http://brainworkshop.sourceforge.net/donate.html'
WEB_VERSION_CHECK = 'http://brainworkshop.sourceforge.net/version.txt'
WEB_PYGLET_DOWNLOAD = 'http://pyglet.org/download.html'
WEB_FORUM = 'http://groups.google.com/group/brain-training'
WEB_MORSE = 'http://en.wikipedia.org/wiki/Morse_code'
TIMEOUT_SILENT = 3
TICKS_MIN = 3
TICKS_MAX = 50
TICK_DURATION = 0.1
# some functions to assist in path determination
def main_is_frozen():
return (hasattr(sys, "frozen") or # new py2exe
hasattr(sys, "importers") # old py2exe
or imp.is_frozen("__main__")) # tools/freeze
def get_main_dir():
if main_is_frozen():
return os.path.dirname(sys.executable)
return sys.path[0]
def get_data_dir():
try:
return sys.argv[sys.argv.index('--datadir') + 1]
except:
return os.path.join(get_main_dir(), FOLDER_DATA)
def get_res_dir():
try:
return sys.argv[sys.argv.index('--resdir') + 1]
except:
return os.path.join(get_main_dir(), FOLDER_RES)
def quit_with_error(message='', postmessage='', quit=True, trace=True):
if message: print >> sys.stderr, message + '\n'
if trace:
print >> sys.stderr, _("Full text of error:\n")
traceback.print_exc()
if postmessage: print >> sys.stderr, '\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.sourceforge.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
# 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
# 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: True
VERSION_CHECK_ON_STARTUP = True
# 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. 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.
# Look up the key codes here:
# http://pyglet.org/doc/api/pyglet.window.key-module.html
######################################################################
# 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
######################################################################
# 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
sys.stdout = open(os.path.join(get_data_dir(), 'dump.txt'), 'w')
info.dump()
sys.stdout.close()
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()
try: CONFIGFILE = sys.argv[sys.argv.index('--configfile') + 1]
except: pass
def load_last_user(lastuserpath):
if os.path.isfile(os.path.join(get_data_dir(), lastuserpath)):
f = file(os.path.join(get_data_dir(), lastuserpath), 'r')
p = pickle.Unpickler(f)
options = p.load()
del p
f.close()
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 = file(os.path.join(get_data_dir(), lastuserpath), 'w')
p = pickle.Pickler(f)
p.dump({'USER': USER})
# also do date of last session?
except:
pass
def parse_config(configpath):
if CLINICAL_MODE and configpath == 'config.ini':
pass
else:
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:
if configpath != 'config.ini':
quit_with_error(_('Unable to load config file: %s') %
os.path.join(get_data_dir(), configpath))
defaultconfig = ConfigParser.ConfigParser()
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
try: cfg.STATSFILE = sys.argv[sys.argv.index('--statsfile') + 1]
except:
pass
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:
overwrite = True
if overwrite:
f = file(os.path.join(get_data_dir(), configfile), 'w')
newconfigfile_contents = CONFIGFILE_DEFAULT_CONTENTS.replace('stats.txt', statsfile)
f.write(newconfigfile_contents)
f.close()
STATS_BINARY = statsfile.replace('-stats.txt', '-logfile.dat') # let's hope nobody uses '-stats.txt' in their username
try:
os.stat(os.path.join(get_data_dir(), statsfile))
except OSError:
f = file(os.path.join(get_data_dir(), statsfile), 'w')
f.close()
try:
os.stat(os.path.join(get_data_dir(), STATS_BINARY))
except OSError:
f = file(os.path.join(get_data_dir(), STATS_BINARY), 'w')
f.close()
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)
req = urllib2.Request(WEB_VERSION_CHECK)
try:
response = urllib2.urlopen(req)
version = response.readline().strip()
except:
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
import pyglet
from pyglet.gl import *
if NOVBO: pyglet.options['graphics_vbo'] = False
from pyglet.window import key
except:
quit_with_error(_('Error: unable to load pyglet. If you already installed pyglet, please ensure ctypes is installed. Please visit %s') % WEB_PYGLET_DOWNLOAD)
try:
pyglet.options['audio'] = ('directsound', 'openal', 'alsa', )
# use in pyglet 1.2: pyglet.options['audio'] = ('directsound', 'pulse', 'openal', )
import pyglet.media
except:
quit_with_error(_('No suitable audio driver could be loaded.'))
try:
from pyglet.media import avbin
if pyglet.version >= '1.2': # temporary workaround for defect in pyglet svn 2445
pyglet.media.have_avbin = True
except:
cfg.USE_MUSIC = False
if pyglet.version >= '1.2':
pyglet.media.have_avbin = False
print _('AVBin not detected. Music disabled.')
print _('Download AVBin from: http://code.google.com/p/avbin/')
# 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']}
if pyglet.media.have_avbin: supportedtypes['sounds'] = supportedtypes['music']
elif cfg.USE_MUSIC: supportedtypes['music'] = supportedtypes['sounds']
else: del supportedtypes['music']
supportedtypes['misc'] = supportedtypes['sounds'] + supportedtypes['sprites']
resourcepaths = {}
for restype in supportedtypes.keys():
res_sets = {}
for folder in os.listdir(os.path.join(res_path, restype)):
contents = []
if os.path.isdir(os.path.join(res_path, restype, folder)):
contents = [os.path.join(res_path, restype, folder, obj)
for obj in os.listdir(os.path.join(res_path, restype, folder))
if obj[-3:] in supportedtypes[restype]]
contents.sort()
if contents: res_sets[folder] = contents
if res_sets: resourcepaths[restype] = res_sets
sounds = {}
for k in resourcepaths['sounds'].keys():
sounds[k] = {}
for f in resourcepaths['sounds'][k]:
sounds[k][os.path.basename(f).split('.')[0]] = pyglet.media.load(f, streaming=False)
sound = sounds['letters'] # is this obsolete yet?
if cfg.USE_APPLAUSE:
applausesounds = [pyglet.media.load(soundfile, streaming=False)
for soundfile in resourcepaths['misc']['applause']]
applauseplayer = pyglet.media.ManagedSoundPlayer()
musicplayer = pyglet.media.ManagedSoundPlayer()
def sound_stop():
global applauseplayer
global musicplayer
musicplayer.volume = 0
applauseplayer.volume = 0
def fade_out(dt):
global applauseplayer
global musicplayer
if musicplayer.volume > 0:
if musicplayer.volume <= 0.1:
musicplayer.volume -= 0.02
else: musicplayer.volume -= 0.1
if musicplayer.volume <= 0.02:
musicplayer.volume = 0
if applauseplayer.volume > 0:
if applauseplayer.volume <= 0.1:
applauseplayer.volume -= 0.02
else: applauseplayer.volume -= 0.1
if applauseplayer.volume <= 0.02:
applauseplayer.volume = 0
if (applauseplayer.volume == 0 and musicplayer.volume == 0) or mode.trial_number == 3:
pyglet.clock.unschedule(fade_out)
#
# --- END RESOURCE INITIALIZATION SECTION ----------------------------------
#
# The colors of the squares in Triple N-Back mode are defined here.
# Color 1 is used in Dual N-Back mode.
def get_color(color):
if color in (4, 7) and cfg.BLACK_BACKGROUND:
return cfg['COLOR_%i_BLK' % color]
return cfg['COLOR_%i' % color]
def default_nback_mode(mode):
if ('BACK_%i' % mode) in cfg:
return cfg['BACK_%i' % mode]
elif mode > 127: # try to use the base mode for crab, multi
return default_nback_mode(mode % 128)
else:
return cfg.BACK_DEFAULT
def default_ticks(mode):
if ('TICKS_%i' % mode) in cfg:
return cfg['TICKS_%i' % mode]
elif mode > 127:
bonus = ((mode & 128)/128) * cfg.BONUS_TICKS_CRAB
if mode & 768:
bonus += cfg['BONUS_TICKS_MULTI_%i' % ((mode & 768)/256+1)]
if DEBUG: print "Adding a bonus of %i ticks for mode %i" % (bonus, mode)
return bonus + default_ticks(mode % 128)
else:
return cfg.TICKS_DEFAULT
#Create the game window
caption = []
if CLINICAL_MODE:
caption.append('BW-Clinical ')
else:
caption.append('Brain Workshop ')
caption.append(VERSION)
if USER != 'default':
caption.append(' - ')
caption.append(USER)
if cfg.WINDOW_FULLSCREEN:
style = pyglet.window.Window.WINDOW_STYLE_BORDERLESS
else:
style = pyglet.window.Window.WINDOW_STYLE_DEFAULT
class MyWindow(pyglet.window.Window):
def on_key_press(self, symbol, modifiers):
pass
def on_key_release(self, symbol, modifiers):
pass
window = MyWindow(cfg.WINDOW_WIDTH, cfg.WINDOW_HEIGHT, caption=''.join(caption), style=style, vsync=VSYNC)
#if DEBUG:
# window.push_handlers(pyglet.window.event.WindowEventLogger())
if sys.platform == 'darwin': # and cfg.WINDOW_FULLSCREEN:
window.set_exclusive_keyboard()
if sys.platform == 'linux2':
window.set_icon(pyglet.image.load(resourcepaths['misc']['brain'][0]))
# set the background color of the window
if cfg.BLACK_BACKGROUND:
glClearColor(0, 0, 0, 1)
else:
glClearColor(1, 1, 1, 1)
if cfg.WINDOW_FULLSCREEN:
window.maximize()
window.set_mouse_visible(False)
# All changeable game state variables are located in an instance of the Mode class
class Mode:
def __init__(self):
self.mode = cfg.GAME_MODE
self.back = default_nback_mode(self.mode)
self.ticks_per_trial = default_ticks(self.mode)
self.num_trials = cfg.NUM_TRIALS
self.num_trials_factor = cfg.NUM_TRIALS_FACTOR
self.num_trials_exponent = cfg.NUM_TRIALS_EXPONENT
self.num_trials_total = self.num_trials + self.num_trials_factor * \
self.back ** self.num_trials_exponent
self.short_mode_names = {2:'D',
3:'PCA',
4:'DC',
5:'TC',
6:'QC',
7:'A',
8:'DA',
9:'TA',
10:'Po',
11:'Au',
12:'TCC',
20:'PC',
21:'PI',
22:'CA',
23:'IA',
24:'CI',
25:'PCI',
26:'PIA',
27:'CIA',
28:'Q',
100:'AA',
101:'PAA',
102:'CAA',
103:'IAA',
104:'PCAA',
105:'PIAA',
106:'CIAA',
107:'P'
}
self.long_mode_names = {2:_('Dual'),
3:_('Position, Color, Sound'),
4:_('Dual Combination'),
5:_('Tri Combination'),
6:_('Quad Combination'),
7:_('Arithmetic'),
8:_('Dual Arithmetic'),
9:_('Triple Arithmetic'),
10:_('Position'),
11:_('Sound'),
12:_('Tri Combination (Color)'),
20:_('Position, Color'),
21:_('Position, Image'),
22:_('Color, Sound'),
23:_('Image, Sound'),
24:_('Color, Image'),
25:_('Position, Color, Image'),
26:_('Position, Image, Sound'),
27:_('Color, Image, Sound'),
28:_('Quad'),
100:_('Sound, Sound2'),
101:_('Position, Sound, Sound2'),
102:_('Color, Sound, Sound2'),
103:_('Image, Sound, Sound2'),
104:_('Position, Color, Sound, Sound2'),
105:_('Position, Image, Sound, Sound2'),
106:_('Color, Image, Sound, Sound2'),
107:_('Pentuple')
}
self.modalities = { 2:['position1', 'audio'],
3:['position1', 'color', 'audio'],
4:['visvis', 'visaudio', 'audiovis', 'audio'],
5:['position1', 'visvis', 'visaudio', 'audiovis', 'audio'],
6:['position1', 'visvis', 'visaudio', 'color', 'audiovis', 'audio'],
7:['arithmetic'],
8:['position1', 'arithmetic'],
9:['position1', 'arithmetic', 'color'],
10:['position1'],
11:['audio'],
12:['visvis', 'visaudio', 'color', 'audiovis', 'audio'],
20:['position1', 'color'],
21:['position1', 'image'],
22:['color', 'audio'],
23:['image', 'audio'],
24:['color', 'image'],
25:['position1', 'color', 'image'],
26:['position1', 'image', 'audio'],
27:['color', 'image', 'audio'],
28:['position1', 'color', 'image', 'audio'],
100:['audio', 'audio2'],
101:['position1', 'audio', 'audio2'],
102:['color', 'audio', 'audio2'],
103:['image', 'audio', 'audio2'],
104:['position1', 'color', 'audio', 'audio2'],
105:['position1', 'image', 'audio', 'audio2'],
106:['color', 'image', 'audio', 'audio2'],
107:['position1', 'color', 'image', 'audio', 'audio2']
}
self.flags = {}
# generate crab modes
for m in self.short_mode_names.keys():
nm = m | 128 # newmode; Crab DNB = 2 | 128 = 130
self.flags[m] = {'crab':0, 'multi':1}# forwards
self.flags[nm] = {'crab':1, 'multi':1}# every (self.back) stimuli are reversed for matching
self.short_mode_names[nm] = 'C' + self.short_mode_names[m]
self.long_mode_names[nm] = _('Crab ') + self.long_mode_names[m]
self.modalities[nm] = self.modalities[m][:] # the [:] at the end is
# so we take a copy of the list, in case we want to change it later
# generate multi-stim modes
for m in self.short_mode_names.keys():
for n, s in [(2, _('Double-stim')), (3, _('Triple-stim')), (4, _('Quadruple-stim'))]: