Skip to content

Commit 403a661

Browse files
committed
Added print_variables function to pyControl.utility which prints variables to the log as a JSON formatted string.
Modified reversal_learning example to use print_variables function.
1 parent 0328579 commit 403a661

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

pyControl/utility.py

+13
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
# Module imported by the user into their task file which contains the
22
# functions, classes and variables used in task files.
33

4+
import sys
45
import pyb
56
import math
7+
import ujson
8+
from ucollections import OrderedDict
69
from . import timer
710
from . import framework as fw
811
from . import state_machine as sm
@@ -51,6 +54,16 @@ def print(print_string):
5154
if fw.data_output:
5255
fw.data_output_queue.put((fw.current_time, fw.print_typ, str(print_string)))
5356

57+
def print_variables(variables='all'):
58+
# Print specified variables to data log as a json string.
59+
if variables=='all':
60+
var_dict = {k:v for k,v in v.__dict__.items() if not hasattr(v, '__init__')}
61+
elif sys.implementation.version >= (1,12):
62+
var_dict = OrderedDict([(k, getattr(v,k)) for k in variables if not hasattr(getattr(v,k), '__init__')])
63+
else: # old versions of ujson don't support OrdereDict.
64+
var_dict = {k:getattr(v,k) for k in variables if not hasattr(getattr(v,k), '__init__')}
65+
print(ujson.dumps(var_dict))
66+
5467
def publish_event(event):
5568
# Put event with specified name in the event queue.
5669
fw.event_queue.put((fw.current_time, fw.event_typ, sm.events[event]))

tasks/example/reversal_learning.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,7 @@ def trial_outcome(choice):
8585
# Print trial information.
8686
v.n_trials +=1
8787
v.n_rewards += outcome
88-
print('T#:{} R#:{} B#:{} C:{:d} O:{:d} S:{:d} A:{:.2f}'.format(
89-
v.n_trials, v.n_rewards, v.n_blocks, choice, outcome, v.state, v.mov_ave.value))
88+
print_variables(['n_trials', 'n_rewards', 'n_blocks', 'choice', 'outcome', 'state'])
9089

9190
return outcome
9291

0 commit comments

Comments
 (0)