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

OpenSesame 3.0.0 will bring amazing new features! Curious? Take it for a test spin, and help us iron out the kinks.

Experiment functions

class experiment

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:

Example:

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)

Function list:

function experiment.__init__(auto_response=False, fullscreen=False, name=u’experiment’, pool_folder=None, items=None, workspace=None, experiment_path=None, subject_nr=0, logfile=u’defaultlog.csv’, resources={}, string=None)

Constructor. The experiment is created automatically be OpenSesame and you will generally not need to create it yourself.

Keywords:

  • auto_response – Indicates whether auto-response mode should be enabled.
    • Default: False
    • Type: bool
  • fullscreen – Indicates whether the experiment should be executed in fullscreen.
    • Default: False
    • Type: bool
  • name – The name of the experiment.
    • Default: u’experiment’
    • Type: str, unicode
  • pool_folder – A specific folder to be used for the file pool, or None to use a new temporary folder.
    • Default: None
    • Type: str, unicode, NoneType
  • items – An item_store object to be used for storing items internally, or None to create a new item store.
    • Default: None
    • Type: item_store, NoneType
  • experiment_path – The path of the experiment file. This will need to be specified even if a filename was passed using the string keyword.
    • Default: None
    • Type: str, unicode, NoneType
  • workspace – A python_workspace object to be used for executing custom Python code, or None to create a new workspace.
    • Default: None
    • Type: python_workspace, NoneType
  • subject_nr – The subject number.
    • Default: 0
    • Type: int
  • logfile – The logfile path.
    • Default: u’defaultlog.csv’
    • Type: unicode, str
  • resources – A dictionary with names as keys and paths as values. This serves as a look-up table for resources.
    • Default: {}
    • Type: dict
  • string – A string containing the experiment definition, the name of an OpenSesame experiment file, or None to create a blank experiment.
    • Default: None
    • Type: str, unicode, NoneType

function experiment.auto_type(val)

Converts a value into the ‘best fitting’ or ‘simplest’ type that is compatible with the value.

Arguments:

  • val – A value. This can be any type.

Returns:

The same value converted to the ‘best fitting’ type.

  • Type: unicode, int, float

function experiment.color_check(col)

Checks whether a string is a valid color name. Raises an exception 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'))

Arguments:

  • col – The color to check.

function experiment.eval_text(text, soft_ignore=False, round_float=False, quote_str=False)

Evaluates a string of text, so that all variable references (e.g., ‘[var]’) are replaced by values.

Example:

exp.set('var', 'evaluated')
print(self.eval_text('This string has been [var]'))
# Prints 'This string has been evaluated

Arguments:

  • text – The text to be evaluated. This can be any type, but only str and unicode types will be evaluated.

Keywords:

  • soft_ignore – A Boolean indicating whether missing variables should be ignored, rather than cause an exception.
    • Default: False
    • Type: bool
  • 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
    • Type: bool
  • quote_str – A Boolean indicating whether string variables should be surrounded by single quotes (default=False).
    • Default: False
    • Type: bool

Returns:

The evaluated text.

  • Type: unicode, int, float

function experiment.file_in_pool(path)

Checks if a file is in the file 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)

Arguments:

  • path – No description

Returns:

A bool indicating if the file is in the pool.

  • Type: bool

function experiment.flush_log()

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

Example:

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

function experiment.get(var, _eval=True)

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.

Example:

# Example 1
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]'

Arguments:

  • var – The name of an OpenSesame variable.
    • Type: str, unicode

Keywords:

  • _eval – Indicates whether the variable should be evaluated, i.e. whether containing variables should be processed.
    • Default: True
    • Type: bool

Returns:

The value.

  • Type: unicode, int, float

function experiment.get_check(var, default=None, _eval=True, valid=None)

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.

Example:

if self.get_check('cue', default='invalid') == 'valid':
        print('This is a validly-cued trial')

Arguments:

  • var – The name of an OpenSesame variable
    • Type: unicode, str

Keywords:

  • default – A default ‘fallback’ value or None for no fallback, in which case an exception is rased if the variable does not exist.
    • Default: None
    • Type: unicode, float, int
  • _eval – Indicates whether the variable should be evaluated, i.e. whether containing variables should be processed.
    • Default: True
    • Type: bool
  • valid – A list of allowed values (or None for no restrictions). An exception is raised if the value is not an allowed value.
    • Default: None
    • Type: list, NoneType

Returns:

The value

  • Type: unicode, float, int

function experiment.get_file(path)

Returns the full path to a file. The logic is as follows:

  1. First checks if path is a file in the file pool.
  2. If not, check if path is a file in the folder of the current experiment (if any).
  3. If not, check if path is a file in the __pool__ subfolder of the current experiment.
  4. If not, simply return path.

Example:

image_path = exp.get_file('my_image.png')
my_canvas = exp.offline_canvas()
my_canvas.image(image_path)

Arguments:

  • path – A filename. This can be any type, but will be coerced to unicode if it is not unicode.

Returns:

The full path to the file.

  • Type: unicode

function experiment.get_refs(text)

Returns a list of variables that are referred to by a string of text.

Arguments:

  • text – A string of text. This can be any type, but will coerced to unicode if it is not unicode.

Returns:

A list of variable names or an empty list if the string contains no references.

  • Type: list

function experiment.has(var)

Checks if an OpenSesame variable exists, either in the item or in the experiment.

Example:

if not self.has('response'):
        print('No response has been collected yet')

Arguments:

  • var – The name of an OpenSesame variable.
    • Type: str, unicode

Returns:

True if the variable exists, False if not.

  • Type: bool

function experiment.log(msg)

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.

Example:

self.log('TIMESTAMP = %s' % self.time())

Arguments:

  • msg – A message. This can be any type and will we be converted to a unicode string using the logic described in unistr.

function experiment.reset()

Resets all item variables to their default value.

function experiment.resolution()

Returns the display resolution and checks whether the resolution is valid.

Important note:

The meaning of ‘resolution’ depends on the back-end. For example, the legacy back-end changes 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

  • Type: tuple

function experiment.sanitize(s, strict=False, allow_vars=True)

Removes invalid characters (notably quotes) from the string.

Example:

# Prints 'Universit Aix-Marseille'
print(self.sanitize('"Université Aix-Marseille"'))
# Prints 'UniversitAixMarseille'
print(self.sanitize('"Université Aix-Marseille""', strict=True))

Arguments:

  • s – The string to be sanitized. This can be any type, but if it is not unicode, it will be coerced to unicode.

Keywords:

  • strict – If True, all except underscores and alphanumeric characters are stripped.
    • Default: False
    • Type: bool
  • allow_vars – If True, square brackets are not sanitized, so you can use variables.
    • Default: True
    • Type: bool

Returns:

A sanitized string.

  • Type: unicode

function experiment.save(path, update_path=True, overwrite=False)

Saves the experiment to file. If no extension is provided, .opensesame.tar.gz is chosen by default.

Arguments:

  • path – The target file to save to.
    • Type: str, unicode

Keywords:

  • update_path – Indicates if the experiment_path attribute should be updated.
    • Default: True
    • Type: bool
  • overwrite – Indicates if existing files should be overwritten.
    • Default: False
    • Type: bool

Returns:

The path on successful saving or False otherwise.

  • Type: unicode, bool

function experiment.set(var, val)

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

Important note:

You can only set simple variable types (unicode, float, and int). If you use the set function to save another type of variable, it will be converted to a unicode representation.

Example:

exp.set('my_timestamp', self.time())

Arguments:

  • var – The name of an experimental variable.
    • Type: str, unicode
  • val – A value.

function experiment.set_response(response=None, response_time=None, correct=None)

Processes a response in such a way that feedback variables are updated as well.

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)

Keywords:

  • response – The response value.
    • Default: None
  • response_time – The response time, or None.
    • Default: None
    • Type: int, float, NoneType
  • correct – The correctness value, which should be 0, 1, True, False, or None.
    • Default: None
    • Type: int, bool, NoneType

function 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.

Example:

exp.set_subject(1)
print('Subject nr = %d' % exp.get('subject_nr'))
print('Subject parity = %s' % exp.get('subject_parity'))

Arguments:

  • nr – The subject nr.
    • Type: int

function experiment.sleep(ms)

Sleeps for a specified duration.

Example:

self.sleep(1000) # Sleeps one second

Arguments:

  • ms – An value specifying the duration in milliseconds.
    • Type: int, float

function experiment.time()

Returns a timestamp for the current time. This timestamp only has a relative meaning, i.e. you can use it to determine the interval between two moments, but not the actual time. Whether the timestamp is a float or int depends on the back-end.

Example:

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

Returns:

A timestamp of the current time.

  • Type: int, float

function experiment.unistr(val)

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.

  • Type: unicode

function experiment.unset(var)

Unsets (forgets) 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!

Arguments:

  • var – The name of an OpenSesame variable.
    • Type: str, unicode

function experiment.usanitize(s, strict=False)

Converts all non-ASCII characters to U+XXXX notation, so that the resulting string can be treated as plain ASCII text.

Arguments:

  • s – A unicode string to be santized
    • Type: unicode

Keywords:

  • strict – If True, special characters are ignored rather than recoded.
    • Default: False
    • Type: bool

Returns:

A regular Python string with all special characters replaced by U+XXXX notation or ignored (if strict).

  • Type: str