You are viewing unmaintained documentation for an older version of OpenSesame. Click here to view the current documentation. Your version of OpenSesame:

Test the next generation of OpenSesame: 2.9.0 Hesitant Heisenberg!

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 experiment

Function 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

experiment.__init__(name=u'experiment', string=None, pool_folder=None, experiment_path=None, fullscreen=False, auto_response=False, logfile=u'defaultlog.csv', subject_nr=0)
Constructor. The experiment is created automatically be OpenSesame and you will generally not need to create it yourself.

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)
experiment.auto_type(val)
Inherited from item

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'

experiment.color_check(col)
Inherited from item

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'))

experiment.eval_text(text, round_float=False, soft_ignore=False, quote_str=False)
Inherited from item

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]'))

experiment.file_in_pool(path)
Checks if a file is in the file pool.

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)

experiment.flush_log()
Inherited from item

Forces any pending write operations to the log file to be written to disk.

Example:
self.log('TRIAL FINISHED')
self.flush_log()

experiment.get(var, _eval=True)
Inherited from item

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]'

experiment.get_check(var, default=None, valid=None, _eval=True)
Inherited from item

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')

experiment.get_file(path)
Returns the path to a file. First checks if the file is in the file pool and then the folder of the current experiment (if any), or in the `__pool__` subfolder of the current experiment. Otherwise, simply returns the path.

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)

experiment.get_refs(text)
Inherited from item

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']

experiment.has(var)
Inherited from item

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')

experiment.log(msg)
Inherited from item

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())

experiment.resolution()
Inherited from item

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
experiment.sanitize(s, strict=False, allow_vars=True)
Inherited from item

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))

experiment.set(var, val)
Inherited from item

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())

experiment.set_response(response=None, response_time=None, correct=None)
Inherited from item

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)

experiment.set_subject(nr)
Sets the subject number and parity (even/ odd). This function is called automatically when an experiment is started, so you do not generally need to call it yourself.

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'))

experiment.sleep(ms)
Inherited from item

Sleeps for a specified duration.

Arguments:
ms → An integer value specifying the duration in milliseconds.

Example:
self.sleep(1000) # Sleeps one second

experiment.time()
Inherited from item

Returns the current time.

Returns:
A timestamp of the current time.

Example:
print('The time is %s' % self.time())

experiment.unistr(val)
Inherited from item

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.
experiment.unset(var)
Inherited from item

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!