See also docs for the stateInfo file.

Useful Task Methods

The state machine (stateMachine class) defines states and the connections between them. The state machine can run cell arrays of methods (@() anonymous functions) when states are entered (run once), within (repeated on every screen redraw) and exited (run once). In addition there are ways to transition out of a state if some condition is met. For example if we are in [STATE 1] and the eyetracker tells us the subject has fixated for the correct time, then transition functions can jump us to another state to e.g. show a stimulus.

╔════════════════════════════════════════════════════════════════════════════════════════════════╗
║                  ┌─────────┐                                       ┌─────────┐                 ║
║                  │ STATE 1 │                                       │ STATE 2 │                 ║
║       ┌──────────┴─────────┴───────────┐                ┌──────────┴─────────┴──────────┐      ║
║  ┌────┴────┐      ┌────────┐      ┌────┴───┐       ┌────┴────┐      ┌────────┐     ┌────┴───┐  ║
╚═▶│  ENTER  │─────▶│ WITHIN │─────▶│  EXIT  │══════▶│  ENTER  │─────▶│ WITHIN │────▶│  EXIT  │══╣
   └────┬────┘      └────────┘      └────┬───┘       └────┬────┘      └────────┘     └────┬───┘  ║
        │          ┌──────────┐          │                │          ┌──────────┐         │      ║
        └──────────┤TRANSITION├──────────┘                └──────────┤TRANSITION├─────────┘      ║
                   └─────╦────┘                                      └──────────┘                ║
                         ║                  ┌─────────┐                                          ║
                         ║                  │ STATE 3 │                                          ║
                         ║       ┌──────────┴─────────┴───────────┐                              ║
                         ║  ┌────┴────┐      ┌────────┐      ┌────┴───┐                          ║
                         ╚═▶│  ENTER  │─────▶│ WITHIN │─────▶│  EXIT  │══════════════════════════╝
                            └────┬────┘      └────────┘      └────┬───┘
                                 │          ┌──────────┐          │
                                 └──────────┤TRANSITION├──────────┘
                                            └──────────┘

These various methods control the logic and flow of experiments. This document lists the most important ones used in flexible behavioural task design. It is better for methods to evaluate properties (properties are the variables managed by the class object). Because of this we choose to create methods that alter the properties of each class. For example, show(stims) is a method that allows the stimulus manager to show all stimuli in the list; it does this by setting each stimulus’ isVisible property to true. hide(stims) hides all stimuli by setting isVisible property to false, or you could just hide the 3rd stimulus in the list: hide(stims, 3).

For those unfamiliar with object-oriented design, a CLASS (e.g. stateMachine) is initiated as an OBJECT variable (named sM during the experiment run, it is an instance of the class). ALL Opticka classes are handle classes; this means if we assign sM2 = sMboth of these named instances point to the same object.

As experiments are run inside the runExperiment.runTask() method, this class refers to itself as me, so methods that belong to runExperiment can be called by using me.myMethod() or myMethod(me) (both forms are equivalent to MATLAB). Other important object instances, for example the screenManager class is called via s, so to call the method drawSpot from our screenManager instance s, we can use drawSpot(s) (or s.drawSpot()). You will see below the object names that are available as we run the experiment from runExperiment. The runExperiment object me keeps most of the objects as properties: so s is actually also stored in the property me.screen, sM is stored in the property me.stateMachine etc.

Available Object Instances

Object Class Description
me runExperiment Principal experiment runner
s screenManager PTB screen management
sM stateMachine State machine controller
task taskSequence Trial/block randomisation
stims metaStimulus Stimulus group manager
eT eyetrackerCore subclass Eye tracker interface
io ioManager Digital I/O (strobe/TTL)
rM rewardManager Reward delivery
bR behaviouralRecord Behavioural performance plot
aM audioManager Audio playback
tL timeLogger Frame timing and event logging
uF userFunctions Custom user functions

Similar named methods?

In some cases runExperiment manages an object with similar named methods. For example runExperiment.updateTask() will manage the call to taskSequence.updateTask(), this is often so that runExperiment can co-ordinate among objects and maintain state (when information needs to be shared between objects). If this is not required then we just call the object methods directly, e.g. drawBackground(s) uses screenManager to run the PTB Screen() functions to draw a background colour (the property s.backgroundColour) to the screen. See DefaultStateInfo.m and other CoreProtocols state info files for examples of their use.

User Functions Files

If you want to write your own functions to be called by the stateMachine, then you can add them to a userFunctions.m file, see the docs for details.


Common State Function Patterns

The following table shows the typical function arrays used in each standard state across most CoreProtocols. Use this as a reference when building your own state info files.

prefix — Pre-trial setup

Phase Typical Functions
Entry needFlip(me,true,N), needEyeSample(me,true), hide(stims), resetAll(eT), updateFixationValues(eT,fixX,fixY,[],fixTime), getStimulusPositions(stims), trackerTrialStart(eT,getTaskIndex(me)), trackerMessage(eT,['UUID ' UUID(sM)])
Within drawPhotoDiodeSquare(s,[0 0 0])
Transition — (time-based, moves to fixate after state time)
Exit logRun(me,'INITFIX'), trackerMessage(eT,'MSG:Start Fix')

fixate — Fixation acquisition

Phase Typical Functions
Entry show(stims,2) (show fixation stimulus only)
Within draw(stims), drawPhotoDiodeSquare(s,[0 0 0])
Transition testSearchHoldFixation(eT,'stimulus','breakfix')
Exit updateFixationValues(eT,[],[],[],stimFixTime), show(stims), trackerMessage(eT,'END_FIX')

stimulus — Stimulus presentation

Phase Typical Functions
Entry doSyncTime(me), doStrobe(me,true)
Within draw(stims), drawPhotoDiodeSquare(s,[1 1 1]), animate(stims)
Transition testHoldFixation(eT,'correct','incorrect')
Exit setStrobeValue(me,255), doStrobe(me,true)

correct — Correct response / reward

Phase Typical Functions
Entry trackerTrialEnd(eT,tS.CORRECT), needEyeSample(me,false), hide(stims), giveReward(rM), beep(aM,tS.correctSound), logRun(me,'CORRECT')
Within drawPhotoDiodeSquare(s,[0 0 0])
Exit updatePlot(bR,me), updateTask(me,tS.CORRECT), updateVariables(me), update(stims), getStimulusPositions(stims), resetAll(eT), plot(bR,1), checkTaskEnded(me)

incorrect / breakfix — Error feedback

Phase Typical Functions
Entry trackerTrialEnd(eT,tS.INCORRECT), needEyeSample(me,false), hide(stims), beep(aM,tS.errorSound), logRun(me,'INCORRECT')
Within drawPhotoDiodeSquare(s,[0 0 0])
Exit If tS.includeErrors: updatePlot(bR,me), updateTask(me,tS.INCORRECT), updateVariables(me), update(stims), resetAll(eT), plot(bR,1), checkTaskEnded(me). Otherwise: resetRun(task) instead of updateTask.

pause / calibrate / drift — Utility states

Phase Typical Functions
Entry (pause) hide(stims), drawBackground(s), drawTextNow(s,'PAUSED'), setOffline(eT), stopRecording(eT,true), needFlip(me,false,0), needEyeSample(me,false)
Exit (pause) startRecording(eT,true)
Entry (calibrate) drawBackground(s), stopRecording(eT), setOffline(eT), trackerSetup(eT)
Entry (drift) drawBackground(s), stopRecording(eT), setOffline(eT), driftCorrection(eT)

List of Methods

We highlight the main classes and methods that are most useful when building your paradigm:

runExperiment (“me” in the state file)

The principal class object that runs the experiment. It coordinates all other manager objects and maintains the experimental state.


stateMachine (“sM” in the state file)

The state machine controller that manages the current state, timing, and transitions between states.


Task sequence manager (“task” in the state file)


The eye tracker (“eT” in the state file)

Opticka provides a unified eye tracker API through eyetrackerCore subclasses (eyelinkManager, tobiiManager, iRecManager). All share the same methods. In dummy mode (eT.isDummy = true), the mouse position simulates the eye.

Fixation window management

Fixation testing (transition functions)

Eye sample acquisition

Tracker communication

Tracker display drawing

Recording control


metaStimulus (“stims” in the state file)

This class manages groups of stimuli as a single object. Each stimulus can be shown or hidden and metaStimulus can also manage masking stimuli if needed.

Accessing individual stimuli

Use cell indexing to access the underlying stimulus objects directly:

stims{1}.angleOut    % read the runtime angle of stimulus 1
stims{2}.filePath    % read the image path of stimulus 2
stims{3}.resetTicks  % reset frame counters for stimulus 3

Key properties

Property Description
stims.choice Which stimulus index to use for randomisation (default: random)
stims.stimulusTable Randomisation table for non-task variables
stims.controlTable Arrow-key control table for live variable adjustment
stims.tableChoice Which control table entry to use
stims.stimulusSets Cell array of stimulus index sets for showSet()
stims.setChoice Default set index for showSet()
stims.fixationChoice Which stimuli return fixation positions
stims.exclusionChoice Which stimuli return exclusion positions
stims.n Number of stimuli in the group

Screen Manager (“s” in the state file)


IO Manager (“io” in the state file)

The ioManager class provides a unified interface for digital I/O hardware (strobe words, TTL pulses). In the default configuration it is a dummy that simply logs values. Real hardware subclasses (plusplusManager, labJack, dPixxManager, arduinoManager) provide actual implementations.


Behavioural Record (“bR” in the state file)

The behaviouralRecord class creates a live performance plot showing success rates, response times, eye positions, and pupil size.


Audio Manager (“aM” in the state file)

The audioManager class manages audio playback via PsychPortAudio. It supports WAV file playback and generated beep tones with click-suppression ramping.


Reward Manager (“rM” in the state file)

The rewardManager class provides reward delivery. In the default configuration it is a stub. Actual reward delivery is typically handled via the IO manager or a hardware subclass.


Time Logger (“tL” in the state file)

The timeLogger class logs frame timing (VBL, show, flip, miss, stimTime) and timestamped event annotations with optional HED tags.


Touch Manager (“tM” in the state file)

The touchManager class manages touch screen input, providing a similar API to the eye tracker for touch-based experiments. It wraps PTB’s TouchQueue* functions and supports dummy mode (mouse simulation).

Touch window management

Touch testing (transition functions)

Touch event processing


Communication (brief reference)

Opticka provides two network communication classes for remote control and telemetry:

dataConnection (TCP/UDP)

A PNET-based TCP/UDP socket manager. Key methods: open(), close(), read(), write(), readVar(), writeVar(), checkData(), sendCommand() (supports ping, echo, put, eval, get, close commands). Supports auto-server mode for remote evaluation.

jzmqConnection (ZeroMQ)

A JeroMQ-based ZeroMQ connection supporting REQ/REP, PUB/SUB, PUSH/PULL socket types with JSON serialisation. Key methods: open(), close(), poll(), sendCommand(), receiveCommand(), sendObject(), receiveObject(), sendViaProxy().


FAQ










Definitions

Class
A class is a way to combine a set of related variables (properties) and functions (methods) in a unified object. In MATLAB we use classdef to build a class.
Object
A class is a kind of thing, but when we want to use that thing, we instantiate it into a ‘real’ object. So calling s = screenManager instantiates the screenManager class as an object called s.
Method
The name given by MATLAB to a function contained in a class.
Handle class
A MATLAB class that inherits from handle. All instances of a handle class that point to the same object share the same data. If a = screenManager and b = a, then changing a.someProperty also changes b.someProperty — they are the same object.
Anonymous function
A function defined inline using @(), e.g. @()draw(stims). These are used extensively in state info files because they can be stored in cell arrays and called by the state machine. Note: you cannot directly modify object properties inside anonymous functions — use setter methods instead.
Dynamic property (*Out)
At runtime, each stimulus property (e.g. size) gets a dynamic copy (sizeOut). The *Out version holds the pixel-converted, task-variable-modified value. When using edit(stims, N, property, value), use the *Out property name.