Experiment functions
The experiment
object controls the flow of the experiment. If you are writing Python inline code, there are a few functions in the experiment object that may be useful, mostly to get
and set
variables, and to retrieve files from the file pool. The experiment
object is a property of the inline_script
object, so you can access it as self.experiment
in an inline_script. For convenience, you can also refer to it simply as exp
. For example, the following script retrieves the full path to a file from the pool, shows it using a canvas, and stores the timestamp of the display presentation as canvas_timestamp
, so it can be logged:
from openexp.canvas import canvas
my_canvas = canvas(exp)
my_canvas.image(exp.get_file('my_image.png'))
timestamp = my_canvas.show()
exp.set('canvas_timestamp', timestamp)
For OpenSesame 2.8.3
class experimentFunction overview:
__init__
auto_type
color_check
eval_text
file_in_pool
flush_log
get
get_check
get_file
get_refs
has
log
resolution
sanitize
set
set_response
set_subject
sleep
time
unistr
unset
Keyword arguments:
name → The name of the experiment. (default=u'experiment')
string → A string containing the experiment definition. (default=None)
pool_folder → A specific folder to be used for the file pool. (default=None)
experiment_path → The path of the experiment file. (default=None)
fullscreen → Indicates whether the experiment should be executed in fullscreen. (default=False)
auto_response → Indicates whether auto-response mode should be enabled. (default=False)
logfile → The logfile path. (default=u'defaultlog.csv')
subject_nr → The subject number. (default=0)
Converts a value into the 'best fitting' or 'simplest' type that is compatible with the value.
Arguments:
val → A value.
Returns:
The same value converted to the 'best fitting' type.
Example:
print(type(self.auto_type('1'))) # Prints 'int'
print(type(self.auto_type('1.1'))) # Prints 'float'
print(type(self.auto_type('some text'))) # Prints 'unicode'
# Note: Boolean values are converted to 'yes' / 'no' and are
# therefore also returned as unicode objects.
print(type(self.auto_type(True))) # Prints 'unicode'
Checks whether a string is a valid color name.
Arguments:
col → The color to check.
Exceptions:
Raises a osexception if col is not a valid color.
Example:
# Ok
print(self.color_check('red'))
# Ok
print(self.color_check('#FFFFFF'))
# Raises osexception
print(self.color_check('this is not a color'))
Evaluates a string of text, so that all variable references (e.g., '[var]') are replaced by values.
Arguments:
text → The text to be evaluated.
Keyword arguments:
round_float → A Boolean indicating whether float values should be rounded to a precision of [round_decimals]. round_decimals is an OpenSesame variable that has a default value of 2. (Default=False)
soft_ignore → A Boolean indicating whether missing variables should be ignored, rather than cause an exception (default=False).
quote_str → A Boolean indicating whether string variables should be surrounded by single quotes (default=False).
Returns:
The evaluated text.
Example:
exp.set('var', 'evaluated')
# Prints 'This string has been evaluated
print(self.eval_text('This string has been [var]'))
Returns:
A Boolean indicating if the file is in the pool.
Example:
if not exp.file_in_pool('my_image.png'):
print('my_image.png could not be found!')
else:
image_path = exp.get_file('my_image.png')
my_canvas = exp.offline_canvas()
my_canvas.image(image_path)
Forces any pending write operations to the log file to be written to disk.
Example:
self.log('TRIAL FINISHED')
self.flush_log()
Returns the value of an OpenSesame variable. Checks first if the variable exists 'locally' in the item and, if not, checks if the variable exists 'globally' in the experiment.
The type of the returned value can be int, float, or unicode (string). The appropriate type is automatically selected, e.g. '10' is returned as int, '10.1' as float, and 'some text' as unicode.
The _eval parameter is used to specify whether the value of the variable should be evaluated, in case it contains references to other variables. This is best illustrated by example 2 below.
Arguments:
var → The name of an OpenSesame variable.
_eval → Indicates whether the variable should be evaluated, i.e. whether containing variables should be processed (default=True).
Exceptions:
A osexception is raised if the variable is not found.
Returns:
The value.
Example:
if self.get('cue') == 'valid':
print('This is a validly cued trial')
Example 2:
exp.set('var1', 'I like [var2]')
exp.set('var2', 'OpenSesame')
print(self.get('var1')) # prints 'I like OpenSesame'
print(self.get('var1', _eval=False)) # prints 'I like [var2]'
Similar to get(), but falls back to a default if the variable has not been set. It also raises an error if the value is not part of the valid list.
Arguments:
var → The name of an OpenSesame variable
default → A default 'fallback' value or None for no fallback, in which case an exception is rased if the value does not exist.
valid → A list of allowed values (or None for no restrictions). An exception is raised if the value is not an allowed value.
_eval → Indicates whether the variable should be evaluated, i.e. whether containing variables should be processed (default=True).
Exceptions:
Raises a osexception if the variable is not defined and there is no default value, or if the variable value is not part of the 'valid' list.
Returns:
The value
Example:
if self.get_check('cue', default='invalid') == 'valid':
print('This is a validly-cued trial')
Arguments:
path → The filename.
Returns:
The full path to the file.
Example:
image_path = exp.get_file('my_image.png')
my_canvas = exp.offline_canvas()
my_canvas.image(image_path)
Returns a list of variables that are referred to by a string of text.
Arguments:
text → A string of text.
Returns:
A list of variable names or an empty list if the string contains no references.
Example:
print(self.get_refs('There are [two] [references] here'))
# Prints ['two', 'references']
Checks if an OpenSesame variable exists, either in the item or in the experiment.
Arguments:
var → The name of an OpenSesame variable.
Returns:
True if the variable exists, False if not.
Example:
if not self.has('response'):
print('No response has been collected yet')
Writes a message to the log file. Note that using the log() function in combination with a logger item may result in messy log files.
msg → A message. This can be any type and will we be converted to a unicode string using the logic described in `unistr()`.
Example:
self.log('TIMESTAMP = %s' % self.time())
Returns the display resolution and check whether the resolution is valid.
Note: The meaning of 'resolution' depends on the back-end. For example, the legacy and OpenGL back-ends change the actual resolution of the display, whereas the other back-ends do not alter the actual display resolution, but create a 'virtual display' with the requested resolution that is presented in the center of the display.
Returns:
A (width, height) tuple
Removes invalid characters (notably quotes) from the string.
Arguments:
s → The string (unicode or str) to be sanitized.
Keyword arguments:
strict → If True, all except underscores and alphanumeric characters are
stripped (default=False).
allow_vars → If True, square brackets are not sanitized, so you can use
variables (default=True).
Returns:
A sanitized unicode string
Example:
# Prints 'Universit Aix-Marseille'
print(self.sanitize('\"Université Aix-Marseille\"'))
# Prints 'UniversitAixMarseille'
print(self.sanitize('\"Université Aix-Marseille\""', strict=True))
Sets an OpenSesame variable.
If you want to set a variable so that it is available in other items as well (such as the logger item, so you can log the variable), you need to use the set() function from the experiment. So, in an inline_script item you would generally set a variable with exp.set(), rather than self.set().
Please note that you can only set simple variable types (str, unicode, float, and int). If you use the set function to save an object, it will be converted to a string representation. To make complex variables globally accessible in your experiment, please use the global keyword.
The type of the value can be anything. However, see get() for an explanation of how data-types are handled.
Arguments:
var → The name of an OpenSesame variable.
val → The value.
Example:
exp.set('my_timestamp', self.time())
Processes a response in such a way that feedback variables are updated as well.
Keyword arguments:
response → The response value. (default=None)
response_time → The response time. (default=None)
correct → The correctness value. (default=None)
Example:
from openexp.keyboard import keyboard
my_keyboard = keyboard(exp)
t1 = self.time()
button, timestamp = my_keyboard.get_key()
if button == 'left':
correct = 1
else:
correct = 0
rt = timestamp - t1
self.set_response(response=button, response_time=rt, \
correct=correct)
Arguments:
nr → The subject nr.
Example:
exp.set_subject(1)
print('Subject nr = %d' % exp.get('subject_nr'))
print('Subject parity = %s' % exp.get('subject_parity'))
Sleeps for a specified duration.
Arguments:
ms → An integer value specifying the duration in milliseconds.
Example:
self.sleep(1000) # Sleeps one second
Returns the current time.
Returns:
A timestamp of the current time.
Example:
print('The time is %s' % self.time())
Converts a value to a unicode string. This function is mostly necessary to make sure that normal strings with special characters are correctly encoded into unicode, and don't result in TypeErrors.
The conversion logic is as follows:
- unicode values are returned unchanged.
- str values are decoded using utf-8.
- all other types are typecast to unicode, assuming utf-8 encoding where applicable.
Arguments:
val → A value of any type.
Returns:
A unicode string.
Unsets (forgets) an OpenSesame variable.
Arguments:
var → The name of an OpenSesame variable.
Example:
self.set('var', 'Hello world!')
print(self.get('var')) # Prints 'Hello world!'
self.unset('variable_to_forget')
print(self.get('var')) # Gives error!