-
Notifications
You must be signed in to change notification settings - Fork 1
/
agents.py
1534 lines (1350 loc) · 74.1 KB
/
agents.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
import pygaze
from pygaze import libtime
# from constants import *
from threading import Thread, Event
from framework.stuff import colored_text, encapsulate_text, print_threads
import os.path
from numpy.random import normal as gauss
from numpy.random import poisson, choice, uniform, lognormal
from numpy import exp
from scipy.stats import exponnorm
import time
class AgentMacroBehavior(Thread):
""" A class to "play through" the agents's behavioral macro state sequence by looping over a list defined in
individual study file (in sub dir studies). It handles the start current macro state of the current trial,
sets behavioral parameters, as well as presentation of intructions and rewards.
:param wait_4_instr: Event to wait for instruction screens to finish
:type wait_4_instr: :class:`threading.Event`
:param draw: Event to send a message to main thread handling display visualization
:type draw: :obj:`msrresearch_helpers.pygaze_framework.MyEvent`
:param draw_lock: Create an event that is fired when screen needs to be updated on the display.
:type draw_lock: :obj:`msrresearch_helpers.pygaze_framework.MyEvent`
:param agent_finished_event: An event to tell this agent that a sub agent is finished
:type agent_finished_event: :obj:`threading.Event`
:param finished_event: An event for signaling that current macro state is finished
:type finished_event: :obj:`threading.Event`
:param list_behavior_always_on: List of macro states that are always expressed (BlinkingAgent)
:type list_behavior_always_on: list
:param behavioral_sequence: Sequence of macro states with correspoding parameters
:type behavioral_sequence: dictionary
:param startgaze: Gaze direction at the beginning of a macro state
:type startgaze: string
:param trans_dict: Translating between gaze directions of the agent and AOI names
:type trans_dict: dictionary
:param age_group: Age group, defining which instruction text used later on
:type age_group: string
:param accept_key_input: Indicating whether a trial can be terminated via a button press
:type accept_key_input: Boolean
:param save_trigger: ???
:type save_trigger: ??? tobii logger
:param gamehub: Keeps track of scores gained via successful JA
:type gamehub: :class:`jap_pygaze_framework`
:param accumulative_agents: All macro states that are possible in the given study
:type accumulative_agents: list item ??
:param *agents: EMOTISK_agent agent objects
"""
def __init__(self, wait_4_instr, draw, draw_lock, agent_finished_event, finished_event, list_behavior_always_on,
point_scr_dur, behavioral_sequence, baseline, startgaze, start_gaze_dur, trans_dict, age_group,
accept_key_input, save_trigger, gamehub, nirs_stuff, accumulative_agents, *agents):
Thread.__init__(self, name='AgentMacroBehavior')
# TOCHECK
import pygaze
print('Initializing AgentMacroBehavior...')
# ASSIGNED STUFF
# -- EVENTS to communicate across threads
self.wait_4_instr = wait_4_instr # Wait for instruction screens to finish (if presented)
self.draw = draw # Send a message to main thread handling display visualization via PsychoPy
self.draw_lock = draw_lock # ?? (BJFRGN)
self.agent_finished_event = agent_finished_event # Check if trial has finished through its running time
self.finished_event = finished_event # Signal that the entire behavioral sequence is finished
# -- MACRO BEHAVIOR STUFF
self.macrostates_always_on = list_behavior_always_on # List of macro states that are always expressed (blinks)
self.point_scr_dur = point_scr_dur # Interval from which duration of point screen is drawn uniformly
self.behavioral_sequence = behavioral_sequence # List containing sequence of macro behavioral states
# -- HI stuff
self.age_group = age_group # Age group of HI to select correct screens for instructions and avatar selection
# Set the accepted key inputs to break the run() lopp of the currently running marco state (agent)
self.accept_key_input_default = accept_key_input
self.accept_key_input = self.accept_key_input_default
self.nirs_stuff = nirs_stuff # Shall a basline screen be shown at start and end?
# -- AGENT MECHANIC STUFF
# Set start gaze for the beginning of each trial
if 'no_obj' in startgaze:
self.first_shift = 'straight_no_obj'
else:
self.first_shift = 'straight'
self.trans_dict = trans_dict # Dictionary translating between AOIs and agent's gaze directions
# MISC
self.save_trigger = save_trigger # function to save exe tracker data
self.gamehub = gamehub # Add game hub for keeping track of scores
# -- AGENT STUFF
self.accumulative_agents = accumulative_agents # List of all accumulative agents (BJFRGN)
self.agents = {} # dict for macro states
# add dictionary for behavioral states (only one will be running at any given time)
for agent in agents:
self.agents[agent['name']] = agent
# Prepare logging
self.list_macro_states = [] # list where all macro states will be appended
self.behavioral_sequence_history = [] # history of macro states
self.time_gaze_lag = []
self.all_states = self.macrostates_always_on + self.list_macro_states
self.time_agent_started = None
self.daemon = True # set necessary variables for running as a threading.Thread
self.correct_object = None # Variable to set correct object position
self.show_wait_screen = False # Show a screen indicating to participant that she should "wait" for her partner
self.trials_done = 0
self.total_trials_done = 0
self.show_baseline = baseline # Whether a baseline should be shown (for fNIRS recording)
self.start_gaze_dur = int(start_gaze_dur/100) # Compute duration of start gaze (used for stimtracker signal)
print('... AgentMacroBehavior initialized.')
def run(self):
"""
Method "playing through" macro state sequence. Will create necessary macro states (agents) with adapted trial
parameters as defined in study file.
"""
print(encapsulate_text('Starting macro state sequence...', color='green'))
self.gamehub.event.set('dummy') # Fire dummy event to start correct gamehub logging
# Make sure correct screens are used in very first trial (don't know why it does not work when first in loop)
if self.behavioral_sequence[0]['trial_type']:
self.draw_lock.acquire()
self.draw.set_micro_state('__change_screens__', self.behavioral_sequence[0]['trial_type'],
time=libtime.get_time())
self.draw.clear()
# Loop over macro state sequence
for macro_state in self.behavioral_sequence:
# Set correct screens if defined
if macro_state['trial_type']:
self.draw_lock.acquire()
self.draw.set_micro_state('__change_screens__', macro_state['trial_type'], time=libtime.get_time())
self.draw.clear()
# MACRO STATE CREATION
# Assign agent object for current macro state
if macro_state["agent"] in self.accumulative_agents:
agent = self.agents[macro_state["agent"]]['class'](self.agents[macro_state["agent"]], macro_state[3])
else:
agent = self.agents[macro_state["agent"]]['class'](self.agents[macro_state["agent"]])
print(encapsulate_text('New macro state running: ' + agent.name, color='green'))
# define place to save a gaze lag
# is this still used? (??)
if agent.name == 'IJA_Agent':
self.time_gaze_lag = agent.gaze_lag
# If given, change agent parameters
if macro_state["trial_param"]:
for key, value in macro_state["trial_param"].items():
if key == 'run_time':
value = value*1000 # Convert run_time to [ms]
agent.change_parameter(key, value) # Set other values
# Set macro state parameters
self.show_vid = agent.show_vid # Set whether to present score/reward video
self.show_points = agent.show_points #(??)
self.point2score = agent.point2view # Set who many points are needed to display reward
self.trials2view = agent.trials2view # Set who many trials are needed to display reward
print_threads() # Print running threads
# Wait if something is being drawn right now
while self.draw.is_set():
pass
# Create screens
self.draw_lock.acquire()
self.draw.set_micro_state('__new_screens__', msg2='empty', time=libtime.get_time()) # Create new screens
# self.draw.set_micro_state('__new_screens__', msg2=' ', time=libtime.get_time()) # Create new screens
# Set all events correctly
self.wait_4_instr.wait()
self.wait_4_instr.clear()
self.draw.clear()
#############################
# Begin screen presentation #
#############################
# If set, show (age-adapted) instruction screen
show_instructions = False
if macro_state['instr']:
if len(macro_state['instr']) > 1:
if macro_state['instr'][self.age_group]:
instr = macro_state['instr'][self.age_group]
show_instructions = True
elif len(macro_state['instr']) == 1 and macro_state['instr'] is not None:
instr = macro_state['instr']
show_instructions = True
if show_instructions:
self.draw_lock.acquire()
self.draw.set_micro_state('__instruction_screen__', instr, time=libtime.get_time())
self.draw.clear()
self.wait_4_instr.wait(timeout=300) # Wait for a key press by participant
self.wait_4_instr.clear()
# Set correct fNIRS trigger for block type
if self.nirs_stuff['use']:
if agent.gaze_down:
trig_msg = 'trigger_' + agent.name[0:3] + 'c_start'
else:
trig_msg = 'trigger_' + agent.name[0:3] + '_start'
self.draw_lock.acquire()
self.draw.set_micro_state('__send_trigger__', msg2=trig_msg, time=libtime.get_time())
self.draw.clear()
# -- Begin agent presentation
# Show start gaze screen five times (total ~500ms) with stimtracker trigger pixel in 100 ms intervals to
# mark the start of a trial
for i in range(self.start_gaze_dur):
self.draw_lock.acquire()
self.draw.set(msg='startgaze'+str(i), time=libtime.get_time())
self.draw.clear()
time.sleep(0.1)
# Make agent gaze in initial gaze direction
self.draw_lock.acquire()
self.draw.set_micro_state(self.first_shift, self.first_shift, time=libtime.get_time())
self.draw.clear()
time.sleep(0.1)
# If set, try to take a screenshot (not functional)
if False:
self.draw_lock.acquire()
self.draw.set('__screenshot__')
self.draw.clear()
time.sleep(0.1)
# Create always on agents (i.e. blinking agent)
agents_always_on = []
for a in self.macrostates_always_on:
agents_always_on.append(self.agents[a]['class'](self.agents[a]))
# Inform current macro state about its start time to determine max duration
agent.change_parameter('time_start', libtime.get_time())
agent.start() # Start macro state thread
self.time_agent_started = libtime.get_time() # Get time when agent is started
# Start always on agents
for a in agents_always_on:
a.start()
self.behavioral_sequence_history.append(macro_state['agent']) # log state
# Wait until time in macro state is up (BJFRGN)
self.agent_finished_event.wait(timeout=agent.run_time+10)
print('Macro state ' + macro_state['agent'] + ' finished')
self.draw.do_blink = False # Make sure that not a blink will finish the trial
# stop all always on agents (i.e. BlinkingAgent.
for a in agents_always_on:
a.stop()
a.force_finish_event.set()
a.stop_blinking()
print('Blinking agent finished')
# Wait for all agents to finish
all_finished = False
while not all_finished:
all_finished = True
for a in agents_always_on:
if a.is_alive():
all_finished = False
break
print('All finished')
self.trials_done += 1
self.total_trials_done += 1
# Send fNIRS signal that block has ended
if self.nirs_stuff['use']:
if agent.gaze_down:
trig_msg = 'trigger_' + agent.name[0:3] + 'c_end'
else:
trig_msg = 'trigger_' + agent.name[0:3] + '_end'
self.draw_lock.acquire()
self.draw.set_micro_state('__send_trigger__', msg2=trig_msg, time=libtime.get_time())
self.draw.clear()
# -- REWARD PRESENTATION
# If set, present number of correct objects
# TOCHECK: eigener parameter (??)
if self.show_points:
msg = 'points_' + str(self.gamehub.score_correct_objects)
if self.draw.msg4:
msg = msg + '_correct'
else:
msg = msg + '_wrong'
self.draw_lock.acquire()
self.draw.set_micro_state(msg, time=libtime.get_time())
if self.point_scr_dur:
time.sleep(uniform(self.point_scr_dur[0], self.point_scr_dur[1]))
self.draw.clear()
# IF set AND enough points are reached, present reward video stimulus
# and reset points
if self.show_vid and (self.gamehub.score_correct_objects >= self.point2score or
self.trials_done >= self.trials2view):
self.draw_lock.acquire()
self.draw.set_micro_state('video', 'correct', time=libtime.get_time())
self.draw.clear()
self.gamehub.score_correct_objects = 0
self.trials_done = 0
if self.nirs_stuff['baseline'] and self.show_baseline:
if self.total_trials_done == len(self.behavioral_sequence):
bl_min = self.nirs_stuff['baseline_duration'][0]
bl_max = self.nirs_stuff['baseline_duration'][1]
else:
bl_min = self.nirs_stuff['baseline_duration_2'][0]
bl_max = self.nirs_stuff['baseline_duration_2'][1]
self.draw_lock.acquire()
self.draw.set_micro_state('__baseline__', msg2=bl_min, msg3=bl_max, time=libtime.get_time())
self.draw.clear()
# IF set, show a questionnaire at the end of the agent's run
questionnaire_event = Event()
self.draw_lock.acquire()
if agent.did_key_press:
self.draw.set_micro_state('__questionnaire__', questionnaire_event)
else:
self.draw.set_micro_state('__initial_questionnaire__', questionnaire_event)
self.draw.clear()
questionnaire_event.wait()
# IF set, present a waiting screen
if self.show_wait_screen:
self.draw_lock.acquire()
self.draw.set_micro_state('__wait_screen__', time=libtime.get_time())
self.draw.clear()
# SAVE EYETRACKING DATA
print(encapsulate_text("Don't panic! Just saving data.", color='red'))
save_start = libtime.get_time()
self.save_trigger.set()
self.save_trigger.clear()
self.save_trigger.wait()
print(encapsulate_text('Done saving. Took ' + str(round((libtime.get_time()-save_start)/1000, 2))+'s',
color='green'))
time.sleep(.1) # (??) Warum solange? (used to be 2)
self.agent_finished_event.clear()
# add a muCap marker to end the last block
self.draw_lock.acquire()
self.draw.set_micro_state('__instruction_screen__', ' ')
self.draw.clear()
self.finished_event.set() # set event singaling that the entire behavioral sequence is completed
print(encapsulate_text('Macro state sequence finished.'))
def add_object(self, objct, name):
setattr(self, name, objct)
class Agent(Thread):
"""A generic class to manage general aspects of agent's microbehavior.
Only acts as a parent class to specific child classes for the currently implemented macro states collecting
pan-state methods() for agent behavior.
:param cur_agt: Current gaze direction of agent (use start gaze direction)
:type cur_agt: str
:param draw: Event to fire when agent will send a messge to update screen to main thread
:type draw: :obj:`msrresearch_helpers.pygaze_framework.MyEvent`
:param draw_lock: Event to make sure that no two or more thread are trying to send a draw message to change the
screen
:type draw_lock: :obj:`msrresearch_helpers.pygaze_framework.MyEvent`
:param blinking: Event to check wheter agent is currently blinking
:type blinking: :obj:`threading.Event`
:param trans_matrix: Macro state's specific probabilitic transition matrix among micro states
:type trans_matrix: dictionary
:param questionnaire: questionnaire to be shown when a button is pressed (if active)
:type questionnaire: dictionary
:param finished_event: Event to signal AgentMacroBehavior when this agent has finished
:type finished_event: :obj:`threading.Event`
:param break_event: Pauses agent
:type break_event: :obj:`threading.Event`
:param name: Name for thread of running agent
:type name: str
"""
def __init__(self, cur_agt, draw, draw_lock, blinking, trans_matrix=None, questionnaire=None, finished_event=None,
break_event=Event(), name='NullAgent'):
Thread.__init__(self, name=name)
self.time_start = libtime.get_time() # Get agent start time
# EVENTS to communicate across threads
self.draw = draw
self.draw_lock = draw_lock
self.blinking = blinking
self.finished_event = finished_event
self.break_event = break_event
# -- Agent stuff
self.name = name
print('Initializing Basic Agent class for ' + self.name)
self.cur_agt = cur_agt # Set current agent's appearance
self.trans_matrix = trans_matrix # Transition probability dictionary
self.getting_attention = False # Will the agent try to get the HI's attention by rapid gaze shifts?
self.does_know_correct = False
self.gaze_down = False
# -- Participant stuff
# General stuff
self.did_key_press = True
self.daemon = True
self.is_running = False
self.paused = Event()
# Boolean indicating whether agent has some knowledge on what
# object to gaze at
self.questionnaire = questionnaire # ??
# DEFAULT VALUES (used by specific macro states (agents))
self.correct_aoi = None
self.wrong_aoi = None
self.knows_correct_aoi = False
self.point2view = float('Inf')
self.draw.do_blink = True
self.draw.aoi = None # According AOI to draw
self.draw.correct_aoi_fixed = None
print('... initialized Basic Agent Class')
def change_micro_state(self):
"""
Method to change the agent's current micro state (i.e. visual appearance a_x) via returning a simple message as
str.
New micro state is dicided on whether the agent has knowledge about the correct object
(self.does_know_correct):
(i) If True: Gaze with probability self.p_correct_object at correct object, otherwise randonly gaze at any
other randomnly sampled AOI in self.possible_aois.
Returns a string used by another method to be send to the main thread handling display visualization.
"""
rand_num = uniform() # Sample a random number for a behavioral decision
if self.does_know_correct: # Behavior if agent has knowledge about correct object location
if rand_num < self.p_correct_object:
return self.correct_aoi
else: # Get a wrong gaze direction
return self.get_wrong_gaze_direction()
else: # If not, change gaze direction according to transition probability matrix
cum_prob = 0.0
for gaze_direc, gaze_prob in self.trans_matrix[self.cur_agt].iteritems():
cum_prob += gaze_prob
if rand_num < cum_prob:
print(colored_text(gaze_direc, 'red') + ' | ' + colored_text(str(gaze_prob), 'green'))
print(colored_text('New gaze direction: ' + gaze_direc))
return gaze_direc
def get_wrong_gaze_direction(self):
""" Returns a gaze direction that is defined in self.possible_aois but not currently gazed at by the HI
"""
temp_aois = list(self.possible_aois)
if self.cur_agt in temp_aois:
temp_aois.remove(self.cur_agt)
return choice(temp_aois)
def get_new_waiting_time(self, param):
"""
Method to sample a micro state duration
:raises: NotImplementedError
"""
if param[3] == 'gauss':
l_bound = param[0] - param[4]*param[1]
u_bound = param[0] + param[4]*param[1]
while True:
value = gauss(loc=param[0], scale=param[1])
if (value > l_bound) and (value < u_bound):
return value
elif param[3] == 'lognormal':
l_bound = exp(param[0]-param[4]*param[1])
u_bound = exp(param[0]+param[4]*param[1])
while True:
value = lognormal(param[0], param[1])
if value > l_bound and value < u_bound:
return value
elif param[3] == 'exgauss':
mu, sigma, lam = param[0], param[1], param[2]
mean_ex = mu + lam
var_ex = sigma ** 2 + (1 / lam ** 2)
K = 1./(sigma*lam)
l_bound = mean_ex-param[4]*var_ex
u_bound = mean_ex+param[4]*var_ex
while True:
value = exponnorm.rvs(K, loc=mu, scale=sigma)
if value > l_bound and value < u_bound:
return value
elif param[3] == 'nonrandom':
return param[0]
else:
print('Error in get_new_waiting_time() for distribution type:')
print(param[3])
raise(NotImplementedError('Defined random distribution not implemented'))
def change_parameter(self, name, value):
"""
Method to change a parameter from agent's default value
:param name: Name of parameter stored in self. to change
:type name: str
:param value: new variable
:type value: depends on name
"""
setattr(self, name, value)
print('Parameter ' + name + ' set to ' + str(value))
def check_if_finished(self):
"""
Check whether time in macro state has expired to set condition for running while loop to False
"""
if (libtime.get_time() - self.time_start > self.run_time) or self.break_event.is_set():
self.is_running = False
print('Done with block of macro behavior')
def stop(self):
"""
Stop the running agent
"""
print('MacroState stopped')
self.is_running = False
def pause(self):
"""
Pause the running agent
"""
self.paused.clear()
def unpause(self, runs=None):
"""
Unpause the running agent
:param runs: ??
:type runs: Booleans
"""
self.paused.set()
def wait_for_event(self, timeout=None):
"""
Makes agent wait for a event
:param timeout: Time to max wait for in ???
:type timeout: double
"""
self.break_event.wait(timeout=timeout)
class RJA_Agent(Agent):
"""A class to manage the agent's behavior in RJA macro state: It will follow the HI's fixation after a certain
delay, and, if it starts to get bored, begin to explore the objects around it on its own (for details see methods
paper and run() method).
:param fixation_detector: Fixation dector for registering relevant fixation events
:type fixation_detector: :obj:'pygaze_framework.EventHandler'
:param cur_agt: Current gaze direction of agent (use start gaze direction)
:type cur_agt: str
:param draw: event to fire when redrawing screen on display to participant
:type draw: :obj:`msrresearch_helpers.pygaze_framework.MyEvent`
:param draw_lock: Create an event that is fired when screen needs to be updated on the display.
:type draw_lock: :obj:`msrresearch_helpers.pygaze_framework.MyEvent`
:param blinking: event to check whether agent is currently blinking
:type blinking: :obj:`threading.Event`
:param trans_dic: Dictionary containing translation
:type trans_dic: dict
:param follow_lag: Mean time and variance of agent gaze following in [ms]
:type follow_lag: list
:param follow_prob: Probalility of agent following gaze
:type follow_prob: double in the interval [0,1]
:param reset_lag: ??
:type reset_lag: double
:param straight_agent: ?? not used instead it says start gaze
:type straight_agent: ??
:param wait_eye: ??
:type wait_eye: Boolean
:param gazes_wrong: ??
:type gazes_wrong: Boolean
:param possible_aois: ??
:type possible_aois: list
:param bored_parameters: ??
:type bored_parameters: Dictionary
:param show_vid: Show a video when participants fixates an object (terminates current agent)
:type show_vid: list
:param highlight_obj: Draw a red rectangle around fixated object
:type highlight_obj: Boolean
:param questionnaire: questionnaire to be shown when a button is pressed (if active)
:type questionnaire: dictionary
:param log_event: ??
:type log_event: dictionary
:param finished_event: An event for signaling that time for current macro state is up
:type finished_event: :obj:`threading.Event`
:param break_event: Pauses agent
:type break_event: :obj:`threading.Event`
:param game_event:
:type game_event: :obj:`jap_pygaze_framework.gamehub`
:param name: Name for thread of running agent
:type name: str
"""
def __init__(self, fixation_detector, cur_agt, draw, draw_lock, blinking, trans_dic, follow_lag, follow_prob,
reset_lag, straight_agent, wait_eye, ja_init_waiting_time, gazes_wrong, possible_aois,
break_trial_if_no_mg, single_chance, bored_parameters, show_vid, show_vid_always, show_points,
highlight_obj=False, correct_feedback=False, questionnaire=None, log_event=None, finished_event=None,
break_event=None, game_event=None, name='RJA_Agent'):
super(RJA_Agent, self).__init__(cur_agt, draw, draw_lock, blinking,
trans_matrix=bored_parameters['trans_matrix'], questionnaire=questionnaire,
finished_event=finished_event, break_event=break_event, name=name)
print('Initializing RJA Agent... ')
self.fixation_detector = fixation_detector # Fixation detector object for gaze-contingency
self.trans_dict = trans_dic # Dict translation between AOIs and gaze directions
self.follow_lag = follow_lag # Time after which agent will gaze at object fixated by HI (to establish JA)
self.follow_prob = follow_prob # Probability of agent to follow HI's gaze (to establish JA)
self.break_trial_if_no_mg = break_trial_if_no_mg
self.single_chance = single_chance
self.reset_lag = reset_lag
self.straight_agent = straight_agent
self.wait_eye = wait_eye
self.get_bored = bored_parameters['get_bored']
self.time_to_bore = bored_parameters['time_to_bore']
self.time_to_look_around = bored_parameters['time_to_look_around']
self.gazes_wrong = gazes_wrong # If agents decides not to respond to a JA bid, shall it gaze at a wrong AOI?
self.possible_aois = possible_aois # Names of wrong AOIs to choose from when gazing wrong
self.log_event = log_event
self.game_event = game_event
self.highlight_obj = highlight_obj[0] # Object AOI will be highlighted if fixated by HI
self.HL_time = highlight_obj[1] / 1000.
self.show_vid = show_vid[0] # Inidicats if video is shown when HI fixated an object and trial is terminated
self.point2view = show_vid[1]
self.show_points = show_points
self.show_vid_always = show_vid_always[0]
self.trials2view = show_vid_always[1]
self.p_correct_feedback = correct_feedback
self.last_aoi = None
self.run_time = []
self.ja_init_waiting_time = ja_init_waiting_time
self.max_wait_4_eyecontact = True
self.max_wait_4_eyecontact_time = 5000.
print('...initialized RJA Agent.')
def run(self):
print('RJA Agent running...')
self.log_event.set([libtime.get_time(), 'start']) # Start RJA recorder
# Clean AOI list and message to make agent only respond to new fixations
self.fixation_detector.fixation_list = []
self.fixation_detector.aoi_event.msg = None
self.draw.msg4 = None # Clear message for display event
self.is_running = True
reset_time_to_wait = True
reset_time = libtime.get_time()
is_bored = False # When set to True agent is bored and starts to explore objects
mg = False # Set to true when mututal gaze detected
# Loop handling gaze shifts
while self.is_running:
self.paused.wait() # wait, if the agent is paused
# Wait for the next activated AOI
if reset_time_to_wait:
if is_bored:
waiting_time = self.get_new_waiting_time(self.time_to_look_around)
else:
waiting_time = self.get_new_waiting_time(self.time_to_bore)
reset_time = libtime.get_time()
time_to_wait = reset_time + waiting_time
reset_time_to_wait = False
# Get some sort of fixation timeout for waiting time and the fixation detector
fixation_timeout = waiting_time - reset_time + libtime.get_time() - \
self.fixation_detector.tracker.fixtimetresh
# Get currently fixated AOI
active_aoi = self.fixation_detector.aoi_event.wait(timeout=fixation_timeout/1000.)
self.fixation_detector.aoi_event.clear()
# If set, wait for eyecontact
if self.wait_eye and not mg:
t_ja_waiting = self.get_new_waiting_time(self.ja_init_waiting_time)
t_ja_waiting_start = libtime.get_time()
print('RJA agent is waiting for eye contact')
while active_aoi is not 'AOI_agent_eyes' and libtime.get_time() < t_ja_waiting + t_ja_waiting_start:
active_aoi = self.fixation_detector.aoi_event.wait(timeout=fixation_timeout/1000)
time.sleep(.1)
print('HI looking at ' + str(active_aoi))
self.fixation_detector.aoi_event.clear()
if active_aoi is 'AOI_agent_eyes':
mg = True
print('Eye contact established')
else:
print('No eye contact established')
self.is_running = False
if not self.wait_eye or mg:
# check whether last and current AOIs are different to indicate new JA attempt
if active_aoi != self.last_aoi:
if self.log_event and active_aoi:
self.log_event.set([libtime.get_time(), 'JA_initiated', active_aoi])
# wait if the agent is currently blinking
self.blinking.acquire()
self.blinking.release()
# Check whether agent is following,and if, whether to gaze at correct or wrong AOI
rand_num = uniform() # Sample number [0,1] to make behavioral decision whether to follow or not
if self.gazes_wrong or self.follow_prob > rand_num:
# Trigger drawing of the current agent
if active_aoi in self.trans_dict:
# print('active aoi: ' + active_aoi) # Print currently fixated AOI
self.cur_agt = self.trans_dict[active_aoi] # Get correspoding gaze direction
# Wait time JAP_AGT_FOLLOW_LAG
self.break_event.wait(self.get_new_waiting_time(self.follow_lag)/1000.)
# Change micro state
self.draw_lock.acquire() # Make sure only this agent tries to draw
if not self.gaze_down:
if self.follow_prob > rand_num or active_aoi is 'AOI_agent_eyes': # Is following
print(colored_text('FOLLOWS CORRECT', 'green'))
agt2draw = self.cur_agt
else: # Gazes at wrong AOI
print(colored_text('FOLLOWS WRONG', 'red'))
agt2draw = self.get_wrong_gaze_direction()
else:
if active_aoi is 'AOI_agent_eyes':
agt2draw = self.cur_agt
else:
agt2draw = 'down'
# print('New agents gaze direction: ' + agt2draw)
self.draw.set_micro_state(agt2draw, agt2draw, time=libtime.get_time())
self.log_event.set([libtime.get_time(), 'Agent_followed', agt2draw]) # Log gaze following
self.draw.clear() # Allow other agents to draw
# print(colored_text('followed', 'green'))
# If set, set draw() message to highlight currently fixated object
if self.highlight_obj and active_aoi is not None and active_aoi is not 'AOI_agent_eyes':
if active_aoi == self.trans_dict[self.correct_aoi]:
if uniform() <= self.p_correct_feedback:
correct_aoi_fixed = True
else:
correct_aoi_fixed = False
else:
if uniform() <= self.p_correct_feedback:
correct_aoi_fixed = False
else:
correct_aoi_fixed = True
msg3 = [self.fixation_detector.aois[active_aoi].pos[0],
self.fixation_detector.aois[active_aoi].pos[1],
self.fixation_detector.aois[active_aoi].size[0],
self.fixation_detector.aois[active_aoi].size[1]]
self.blinking.acquire()
self.blinking.release()
self.draw_lock.acquire()
time.sleep(self.HL_time * 2.)
self.draw.set_micro_state(agt2draw, agt2draw, msg3, correct_aoi_fixed,
libtime.get_time())
time.sleep(self.HL_time)
self.draw.clear()
else:
msg3 = None
correct_aoi_fixed = False
# log a successful JA to the game log
self.game_event.set('success')
self.break_event.wait(self.get_new_waiting_time(self.reset_lag)/1000.)
reset_time_to_wait = True
# Behavior if agent does not follow
elif active_aoi:
# Give info that the agent did not follow gaze
self.log_event.set([libtime.get_time(), 'Agent_not_followed', active_aoi])
print(colored_text('did not follow', 'red'))
self.game_event.set('failure') # log a failed JA to the game log
self.last_aoi = active_aoi
is_bored = False
if active_aoi not in {'AOI_agent_eyes', None}:
if correct_aoi_fixed: # If correct AOI was fixated
self.game_event.set('correct_object', time=libtime.get_time())
correct_aoi_fixed = None
else:
pass
#if self.single_chance:
# self.is_running = False
self.get_bored = False
# If there is now new AOI and the agent is supposed to show boredom, start showing it
elif self.get_bored and libtime.get_time() > time_to_wait:
print(encapsulate_text("I'm bored...", color='blue', background='white'))
is_bored = True
# Draw a new micro state for the agent, who is looking around bored.
self.blinking.acquire()
self.blinking.release()
self.draw_lock.acquire() # Make sure only this agent tries to draw
self.cur_agt = self.change_micro_state()
self.draw.set_micro_state(self.cur_agt, self.cur_agt, time=libtime.get_time())
self.draw.clear() # Allow other agents to draw
reset_time_to_wait = True
# If there was no AOI activated, reset everything to straight agent
# if not active_aoi and not self.get_bored:
# self.cur_agt = self.straight_agent
# self.blinking.acquire()
# self.blinking.release()
# self.draw_lock.acquire()
# self.draw.set(self.cur_agt, libtime.get_time())
# print('==========')
# print(self.cur_agt)
# print('==========')
# blubb
# self.draw.clear()
self.check_if_finished()
# Finishing up agent
self.log_event.set([libtime.get_time(), 'stop'])
if not self.break_event.is_set():
self.did_key_press = False
self.break_event.clear()
self.finished_event.set()
print self.correct_aoi
print('RJA_Agent finished')
class RJA_Agent_Dict(RJA_Agent):
"""
A derivative of RJA_Agent to create an agent with its parameters in a dictionary
:param Parameter: ??
:type parameter: dictionary
"""
def __init__(self, parameter):
super(RJA_Agent_Dict, self).__init__(parameter['fixation_detector'], parameter['cur_agt'],
parameter['draw_event'], parameter['draw_lock'], parameter['blink_event'],
parameter['translation_dict'], parameter['follow_lag'],
parameter['follow_prob'], parameter['reset_lag'], parameter['start_gaze'],
parameter['wait_eye'], parameter['ja_init_waiting_time'],
parameter['gazes_wrong'], parameter['possible_aois'],
parameter['break_trial_if_no_mg'], parameter['single_chance'],
parameter['bored_parameters'], parameter['show_vid'],
parameter['show_vid_always'], parameter['show_points'],
parameter['highlight_obj'], parameter['correct_feedback'],
parameter['questionnaire'], parameter['log_event'],
parameter['finished_event'], parameter['break_event'],
parameter['game_event'])
self.paused.set()
print(parameter['break_event'])
print(encapsulate_text(str(self.break_event), color='green'))
class IJA_Agent(Agent):
"""A class to manage avatar's behavior: In this mode, the avatar will explore the items presented on the screen.
:param fixation_detector: Fixation detector to fire AOI events
:type fixation_detector: :obj:'pygaze_framework.EventHandler'
:param cur_agt: Current gaze direction of agent (use start gaze direction)
:type cur_agt: str
:param draw: Event that fires when display shall be updated to participant
:type draw: :obj:`msrresearch_helpers.pygaze_framework.MyEvent`
:param draw_lock: Create an event that is fired when screen needs to be updated on the display.
:type draw_lock: :obj:`msrresearch_helpers.pygaze_framework.MyEvent`
:param blinking: :param blinking: Event to check wheter agent is currently blinking
:type blinking: :obj:`threading.Event`
:param trans_matrix: Martix containing transition probabilities amoung microstates
:type trans_matrix: dictionary
:param agt_straight: Time of agent looking straight before fixating object
:type agt_straight: list
:param t_gaze_at_obj_ija: Time in [ms] after which agent will start trying to get participant's attention
:type t_gaze_at_obj_ija: double
:param t_gaze_straight: Mean time to change microstate in [ms]
:type t_gaze_straight: float
:param subj_fix_t: Part will be looked at while agent is trying to get attention
:type subj_fix_t: list (double)
:param t_2_look_straight_again: Time after succ. IJA before agent looks straight again
:type t_2_look_straight_again: list (double)
:param ja_init_waiting_time: Time to wait before initaitong joint attention
:type ja_init_waiting_time: list
:param ja_init_aois: AOI to wait for before initiating joint attention
:type ja_init_aois: list (str)
:param trans_dict: ??? translating between gaze directions of the agent and AOI names
:type trans_dict: dictionary
:param p_correct_object: Probalility that IJA agent will select correct object, set to *None* to turn off
:type p_correct_object: double
:param possible_aois: ??
:type possible_aois: list
:param get_attention_parameters: IJA get_attention() method parameters
:type get_attention_parameters: dictionary
:param show_vid: Show a video when participants fixates an object (terminates current agent)
:type show_vid: list
:param highlight_obj: Draw a red rectangle around fixated object
:type highlight_obj: Boolean
:param questionnaire: questionnaire to be shown when a button is pressed (if active)
:type questionnaire: dictionary
:param log_event: ??
:type log_event: dictionary
:param finished_event: An event for signaling that time for current macro state is up
:type finished_event: :obj:`threading.Event`
:param break_event: Pauses agent
:type break_event: :obj:`threading.Event`
:param game_event: ??
:type game_event: :obj:`jap_pygaze_framework.gamehub`
:param name: Name for thread of running agent
:type name: str
"""
class AOI_Checker(Thread):
"""Class to check whether fixation_detector is in any given AOI
:param fixation_detector: Objecct sending messages of a fixation events
:type fixation_detector: :obj:'pygaze_framework.EventHandler'
:param name: Name of thread
:type name: str
"""
def __init__(self, fixation_detector, name='AOI_Checker'):
super(IJA_Agent.AOI_Checker, self).__init__(name=name)
self.fixation_detector = fixation_detector
self.name = name
self.running = False
self.unpaused = Event()
self.unpaused.set()
self.daemon = True
self.cur_aoi = []
self.aoi_fixed = []
print('AOI Checker Agent initialized...')
def run(self):
"""
The function running in once AOI_Checker.start() is executed.
Don't run this function by hand, but only by starting the thread!
"""
# set the bool to keep the while loop running
print('Fixation detector running...')
self.running = True
while self.running:
# wait at this point if AOI_Checker is paused
self.unpaused.wait()
# wait for the aoi_event to trigger and get name of fixated AOI
next_aoi = self.fixation_detector.aoi_event.wait(timeout=1.)
if next_aoi and next_aoi not in self.aoi_fixed:
self.aoi_fixed.append(next_aoi)
print(colored_text(self.aoi_fixed, 'red'))
# Make this run method wait again
self.fixation_detector.aoi_event.clear()
def set_aoi(self, aoi):
"""
Set the AOI to be detected.
:param aoi: A existing AOI
:type aoi: string
"""
self.cur_aoi = aoi
def unpause(self):
"""
Unpause the AOI_Checker
"""
if not self.unpaused.is_set():
self.unpaused.set()
def pause(self):
"""
Pause the AOI_Checker
"""
if self.unpaused.is_set():
self.unpaused.clear()
def stop(self):
"""
Stop a running AOI_Checker
"""
self.running = False
self.fixation_detector.aoi_event.set(None)
def __init__(self, fixation_detector, cur_agt, draw, draw_lock, blinking, trans_matrix, agt_straight,
t_gaze_at_obj_ija, t_gaze_straight, subj_fix_t, t_2_look_straight_again, ja_init_waiting_time,
ja_init_aois, trans_dict, p_correct_object, possible_aois, break_trial_if_no_mg=False,
single_chance=False, get_attention_parameters=None, show_vid=False, show_vid_always=False,
show_points=False, highlight_obj=False, correct_feedback=False, questionnaire=None, log_event=None,
finished_event=None, break_event=None, game_event=None, name='IJA_Agent'):
super(IJA_Agent, self).__init__(cur_agt, draw, draw_lock, blinking, trans_matrix=trans_matrix,
questionnaire=questionnaire, finished_event=finished_event,
break_event=break_event, name=name)
print('Initializing IJA Agent...')
# print(subj_fix_t)