mindaffectBCI package

Subpackages

Submodules

mindaffectBCI.noisetag module

class mindaffectBCI.noisetag.CalibrationPhase(objIDs: int = 8, stimSeq=None, nTrials: int = 10, utopiaController=None, stimulusStateStack: mindaffectBCI.noisetag.GSM = None, *args, **kwargs)[source]

Bases: mindaffectBCI.noisetag.FSM

do a complete calibration phase with nTrials x CalibrationTrial

Raises:
  • ValueError – [description]
  • ValueError – [description]
  • StopIteration – [description]
next(t)[source]

get the next state in the sequence, moving through nTrials calibration trials where each trial has single trail stages of cue->wait->flicker

Parameters:t (int) – current time
Raises:StopIteration – when the whole sequence is complete
class mindaffectBCI.noisetag.Experiment(objIDs, stimSeq=None, nCal=10, nPred=20, selectionThreshold=0.1, cuedprediction=False, utopiaController=None, stimulusStateStack=None, numframes=240.0, calframes=None, predframes=None, interphaseframes=900.0, *args, **kwargs)[source]

Bases: mindaffectBCI.noisetag.FSM

do a complete experiment, with calibration -> prediction

next(t)[source]

get the next state in the sequence, moving through calibration->prediction phases where each trial has single trail stages of cue->wait->flicker->feedback

Parameters:t (int) – current time
Raises:StopIteration – when the whole sequence is complete
class mindaffectBCI.noisetag.FSM[source]

Bases: object

simple finite state machine, using a generator-like pattern

get()[source]

get the current state, for this set of active objects

Returns:
The current display state information as a 4-tuple with structure:
(stimState, target_idx, objIDs, sendEvent) stimState (list-int): the stimulus state for each object as an integer target_idx (int): the index into stimState of the cued target, or -1 if no target set objIDs (list-int): the objectIDs for each of the outputs sendEvent (bool): flag if we should send stimulus events in this state
Return type:tuple
next(t)[source]

update the current state, return the new state, raise StopIteration exception when done

class mindaffectBCI.noisetag.Flicker(stimSeq=None, numframes: int = 0.06666666666666667, tgtidx: int = -1, sendEvents: bool = True, framesperbit: int = 1, permute: bool = False)[source]

Bases: mindaffectBCI.noisetag.FSM

do a normal flicker sequence

get()[source]

return the curent stimulus state info

Returns:the current stimlus state tuple (stimState, target_idx, objIDs, sendEvent)
Return type:StimulusState
next(t)[source]

move to the next state

update_codebook_permutation()[source]

update the permutation randomly mapping between codebook rows and outputs

update_ss()[source]

update the information about the current stimulus state

class mindaffectBCI.noisetag.FlickerWithSelection(stimSeq=None, numframes=0.06666666666666667, tgtidx=-1, utopiaController=None, framesperbit=1, sendEvents=True, permute=False)[source]

Bases: mindaffectBCI.noisetag.Flicker

do a normal flicker sequence, with early stopping selection

next(t)[source]

get the next stimulus state in the sequence – terminate if out of time, or BCI made a selection

Parameters:t (int) – current time
Raises:StopIteration – stop if numframes exceeded or BCI made a selection
class mindaffectBCI.noisetag.GSM[source]

Bases: mindaffectBCI.noisetag.FSM

Generalized state machine with stack of states

clear()[source]

clear the state machine stack

get()[source]

return the current stimulus state

Returns:the current stimulus state tuple (stimState,target_idx,objIDs,sendEvent)
Return type:StimulusState
next(t)[source]

get the next stimulus state to shown

Parameters:t (int) – the current time
Raises:StopIteration – when this state machine has run out of states
pop()[source]

remove and return the currently active state machine

Returns:the current state machine at the stop of the stack
Return type:GSM
push(s)[source]

add a new state machine to the stack

Parameters:s (GSM) – finite-state-machine to add
Returns:current state machine stack
Return type:list
class mindaffectBCI.noisetag.HighlightObject(numframes=0.03333333333333333, tgtidx=-1, tgtState=2, sendEvents=False, numblinkframes=30)[source]

Bases: mindaffectBCI.noisetag.Flicker

‘Highlight a single object for a number of frames

class mindaffectBCI.noisetag.Noisetag(stimFile=None, utopiaController=None, stimulusStateMachineStack: mindaffectBCI.noisetag.GSM = None, clientid: str = None)[source]

Bases: object

noisetag abstraction layer to handle both the sequencing of the stimulus flicker, and the communications with the Mindaffect decoder. Clients can use this class to implement BCI control by:

  1. setting the flicker sequence to use (method: startFlicker, startFlickerWithSelection, startCalibration, startPrediction, startExpt)
  2. getting the current stimulus state (method: getStimulusState), and using that to draw the display
  3. telling Noisetag when exactly the stimulus update took place (method: sendStimulusState)
  4. getting the predictions/selections from noisetag and acting on them. (method: getLastPrediction() or getLastSelection())
addMessageHandler(cb)[source]

add a handler which is called back when a new message is recieved

Parameters:cb (function) – the function to be called for each newly recieved message
addPredictionHandler(cb)[source]

add a handler which is called back when a Prediction is recieved from the decoder/hub

Parameters:cb (function) – the function to be called for each newly recieved Prediction
addSelectionHandler(cb)[source]

add a handler which is called back when a Selection is recieved from the decoder/hub

Parameters:cb (function) – the function to be called for every newly recieved Selection
addSubscription(msgs)[source]

add a set of messageIDs to our current set of subscribed message types.

Parameters:msgs (str) – a list of messageIDs to subscribe to. See mindaffectBCI.utopiaclient for the list of message types and IDs
clearLastPrediction()[source]

clear the information about the last recieved target prediction

clearLastSelection()[source]

clear the last selelction message from the hub/decoder

clearLastSignalQuality()[source]

clear the last signal quality message

connect(host: str = None, port: int = -1, queryifhostnotfound: bool = True, timeout_ms: int = 5000)[source]

connect to the utopia hub

Parameters:
  • host (str, optional) – the hub hostname or ip address. Defaults to None.
  • port (int, optional) – the hub port. Defaults to -1.
  • queryifhostnotfound (bool, optional) – if auto-discovery fails do we query the user for the host IP. Defaults to True.
  • timeout_ms (int, optional) – timeout in milliseconds for host autodiscovery or connection. Defaults to 5000.
Returns:

are we currently connected to the hub

Return type:

bool

getLastPrediction()[source]

get the last prediction recieved from the hub/decoder

Returns:the last recieved PredictedTargetProb message
Return type:PredictedTargetProb
getLastSelection()[source]

return the last selection message recieved from the hub/decoder

Returns:the last Selection message recieved from the hub/decoder
Return type:Selection
getLastSignalQuality()[source]

return the last signal quality message recieved from the hub/decoder

Returns:the last ElectrodeQuality message from the hub/decoder
Return type:ElectrodeQuality
getNewMessages()[source]

get all new messages from the decoder

Returns:a list of all new UtopiaMessages recieved from the hub/decoder
Return type:list-of-UtopiaMessage
getStimulusState(objIDs=None)[source]

return the current stimlus state

Parameters:objIDs (list-of-int, optional) – the set of objectIDs to get the state information for. Defaults to None.
Returns:the current stimulus state tuple (stimState,target_idx,objIDs,sendEvent)
Return type:StimulusState
getTimeStamp()[source]

get the current time stamp

Returns:the timestamp for the curren time in milliseconds
Return type:int
gethostport()[source]

return the hostname:port we are currently connected to

Returns:the hub host:port we are currently connected to
Return type:str
isConnected()[source]

query the hub connection status

Returns:are we connected to the hub
Return type:bool
log(msg)[source]

send a Log message to the decoder/hub

Parameters:msg (str) – the Log message to send
modeChange(newmode)[source]

manually change the decoder mode

Parameters:newmode (str) – the new mode string to send to the hub/decoder
removeSubscription(msgs)[source]

remove a set of messageIDs to our current set of subscribed message types.

Parameters:msgs (str) – a list of messageIDs to unsubscribe from. See mindaffectBCI.utopiaclient for the list of message types and IDs
sendStimulusState(timestamp=None)[source]

send the current stimulus state information to the decoder

Parameters:timestamp (int, optional) – timestamp to use when sending the stimulus state information. Defaults to None.
setActiveObjIDs(objIDs)[source]

update the set of active objects we send info to decoder about

Parameters:objIDs (list-of-int) – the set of objectIDs to register
Returns:the set of active object IDs
Return type:list-of-int
setTimeStampClock(tsclock)[source]

set the clock used by default to timestamp messages sent to the hub/decoder

Parameters:tsclock (TimeStampClock) – the time-stamp clock object to use
set_isi(new_isi: float)[source]
setnumActiveObjIDs(nobj: int)[source]

update to say number active objects

Parameters:nobj (int) – the number of active objects to set
Returns:the current set of active object IDs
Return type:list-of-int
startCalibration(nTrials=10, stimSeq=None, *args, **kwargs)[source]

setup and run a complete calibration phase

Parameters:
  • nTrials (int, optional) – number of calibration trials to run. Defaults to 10.
  • stimSeq (list-of-lists-of-int, optional) – the stimulus sequence to play for the flicker in the calibration phase. Defaults to None.
startExpt(nCal=1, nPred=20, selectionThreshold=0.1, cuedprediction=False, *args, **kwargs)[source]

Start the sequence for a full Calibration->Prediction experiment.

Parameters:
  • nCal (int, optional) – the number of calibration trials. Defaults to 10.
  • nPred (int, optional) – the number of prediction trials. Defaults to 20.
  • selectionThreshold (float, optional) – the Perr threshold for selection. Defaults to .1
  • cuedprediction (bool, optional) – flag if we do cueing before trial starts. Default to False.
startFlicker(numframes=100, tgtidx=-1, *args, **kwargs)[source]

setup and run the just the flicker

Parameters:
  • numframes (int, optional) – the number of frames for the flicker. Defaults to 100.
  • tgtidx (int, optional) – the index in the stimSequence of the target, -1 if no cued target. Default to -1
startFlickerWithSelection(numframes: int = 100, tgtidx: int = -1, *args, **kwargs)[source]

setup and run the just the flicker, with early stopping if the BCI selects an output

Parameters:
  • numframes (int, optional) – the number of frames for the flicker. Defaults to 100.
  • tgtidx (int, optional) – the index in the stimSequence of the target, -1 if no cued target. Default to -1
startPrediction(nTrials=10, stimSeq=None, *args, **kwargs)[source]

setup and run a complete prediction phase

Parameters:
  • nTrials (int, optional) – number of prediction trials to run. Defaults to 10.
  • stimSeq (list-of-lists-of-int, optional) – the stimulus sequence to play for the flicker in the calibration phase. Defaults to None.
startSingleTrial(numframes: int = 100, tgtidx: int = -1, *args, **kwargs)[source]

setup and run a single flicker trial, with (optional)cue->wait->flicker->feedback

Parameters:
  • numframes (int, optional) – the number of frames for the flicker. Defaults to 100.
  • tgtidx (int, optional) – the index in the stimSequence of the target, -1 if no cued target. Default to -1
subscribe(msgs)[source]

tell the hub we will subscribe to this set of message IDs

Parameters:msgs (str) – a list of messageIDs to subscribe to. See mindaffectBCI.utopiaclient for the list of message types and IDs
updateStimulusState(t=None)[source]

update to the next stimulus state from the current sequence

Parameters:t (int, optional) – the current time. Defaults to None.
class mindaffectBCI.noisetag.PredictionPhase(objIDs, stimSeq=None, nTrials=10, utopiaController=None, stimulusStateStack=None, selectionThreshold=0.1, cuedprediction=False, *args, **kwargs)[source]

Bases: mindaffectBCI.noisetag.FSM

do complete prediction phase with nTrials x trials with early-stopping feedback

Parameters:FSM ([type]) – [description]
next(t)[source]

get the next state in the sequence, moving through nTrials calibration trials where each trial has single trail stages of cue->wait->flicker->feedback

Parameters:t (int) – current time
Raises:StopIteration – when the whole sequence is complete
class mindaffectBCI.noisetag.SingleTrial(stimSeq, tgtidx: int, utopiaController, stimulusStateStack, numframes: int = None, framesperbit: int = 1, selectionThreshold: float = None, duration: float = 4, cueduration: float = 1, feedbackduration: float = 1, waitduration: float = 1, cueframes: int = None, feedbackframes: int = None, waitframes: int = None, permute: bool = False)[source]

Bases: mindaffectBCI.noisetag.FSM

do a complete single trial with: cue->wait->flicker->feedback

next(t)[source]

get the next state in the sequence, moving through the single trail stages of cue->wait->flicker->feedback

Parameters:t (int) – current time
Raises:StopIteration – when the whole sequence is complete
class mindaffectBCI.noisetag.WaitFor(numframes)[source]

Bases: mindaffectBCI.noisetag.FSM

state machine which waits for given number of frames to pass

get()[source]

get the current state, for this set of active objects

Returns:
The current display state information as a 4-tuple with structure:
(stimState, target_idx, objIDs, sendEvent) stimState (list-int): the stimulus state for each object as an integer target_idx (int): the index into stimState of the cued target, or -1 if no target set objIDs (list-int): the objectIDs for each of the outputs sendEvent (bool): flag if we should send stimulus events in this state
Return type:tuple
next(t)[source]

stop after the desired number of frames has passed

Parameters:t (int) – current time stamp
Raises:StopIteration – when desired number frames expired
mindaffectBCI.noisetag.doFrame(t, stimState, tgt_idx=-1, objIDs=None, utopiaController=None)[source]

utility function to print a summary of a single frame of a stimulus sequence

Parameters:
  • t (int) – current time
  • stimState (list-of-int) – the current stimulus state for each output.
  • tgt_idx (int, optional) – the index of the cued target (if set), -1 if no target. Defaults to -1.
  • objIDs (list-of-int, optional) – the used object ids for each output. Defaults to None.
  • utopiaController (UtopiaController, optional) – the controller for communcation to the decoder. Defaults to None.
mindaffectBCI.noisetag.mkBlinkingSequence(numframes, tgtidx, tgtState=1)[source]

make a simple on-off blinking sequence

Parameters:
  • numframes (int) – number of frame to blink for
  • tgtidx (int) – the index of the output to blink
  • tgtState (int, optional) – the state to show for the blinking target. Defaults to 1.
Returns:

(numframes,255) stimulus state for each output at each timepoint

Return type:

list-of-lists

class mindaffectBCI.noisetag.sumstats(bufsize: int = 120)[source]

Bases: object

Utility class to record summary stastics for, e.g. frame flip timing

addpoint(x)[source]

add a point to the running buffer of statistics

Parameters:x (float) – the point to add
hist()[source]

get the histogram of statistics

Returns:string summary of the data histogram
Return type:str
update_statistics()[source]

compute updated summary statistics, including: mu=average, med=median, sigma=std-dev, min=min, max=max

mindaffectBCI.online_bci module

class mindaffectBCI.online_bci.NoneProc[source]

Bases: object

tempory class simulating a working null sub-process

is_alive()[source]
join()[source]
terminate()[source]
mindaffectBCI.online_bci.check_is_running(hub=None, acquisition=None, decoder=None)[source]

check if the background processes are still running

Parameters:
  • hub_process ([type], optional) – the hub subprocess. Defaults to hub_process.
  • acquisition_process ([type], optional) – the acquisation subprocess. Defaults to acquisition_process.
  • decoder_process ([type], optional) – the decoder subprocess. Defaults to decoder_process.
Returns:

true if all are running else false

Return type:

bool

mindaffectBCI.online_bci.load_config(config_file)[source]

load an online-bci configuration from a json file

Parameters:config_file ([str, file-like]) – the file to load the configuration from.
mindaffectBCI.online_bci.parse_args()[source]

load settings from the json config-file, parse command line arguments, and merge the two sets of settings.

Returns:the combined arguments name-space
Return type:NameSpace
mindaffectBCI.online_bci.run(label='', logdir=None, block=True, acquisition=None, acq_args=None, decoder='decoder', decoder_args=None, presentation='selectionMatrix', presentation_args=None)[source]

[summary]

Parameters:
  • label (str, optional) – string label for the saved data file. Defaults to ‘’.
  • logdir (str, optional) – directory to save log files / data files. Defaults to None = $installdir$/logs.
  • acquisition (str, optional) – the name of the acquisition driver to use. Defaults to None.
  • acq_args (dict, optional) – dictionary of optoins to pass to the acquisition driver. Defaults to None.
  • decoder (str, optional) – the name of the decoder function to use. Defaults to ‘decoder’.
  • decoder_args (dict, optional) – dictinoary of options to pass to the mindaffectBCI.decoder.run(). Defaults to None.
  • presentation (str, optional) – the name of the presentation function to use. Defaults to: ‘selectionMatrix’
  • presentation_args (dict, optional) – dictionary of options to pass to mindaffectBCI.examples.presentation.selectionMatrix.run(). Defaults to None.
  • block (bool, optional) – return immeadiately or wait for presentation to finish and then terminate all processes. Default to True
Raises:

ValueError – invalid options, e.g. unrecognised acq_driver

mindaffectBCI.online_bci.shutdown(hub=None, acquisition=None, decoder=None)[source]

shutdown any background processes started for the BCI

Parameters:
  • hub (subprocess, optional) – handle to the hub subprocess object. Defaults to hub_process.
  • acquisition (subprocess, optional) – the acquisatin subprocess object. Defaults to acquisition_process.
  • decoder (subprocess, optional) – the decoder subprocess object. Defaults to decoder_process.
mindaffectBCI.online_bci.startDecoderProcess(decoder, decoder_args, label='online_bci', logdir=None)[source]

start the EEG decoder process

Parameters:
  • label (str) – a textual name for this process
  • decoder (str) – the name for the acquisition device to start. One-of: ‘decoder’ - use the mindaffectBCI.decoder.decoder ‘none’ - don’t start a decoder
  • decoder_args (dict) – dictionary of additional arguments to pass to the decoder
  • logdir (str, optional) – directory to save log/save files.
Raises:

ValueError – unrecognised arguments, e.g. acquisition type.

Returns:

sub-process for managing the started decoder

Return type:

Process

mindaffectBCI.online_bci.startHubProcess(label='online_bci', logdir=None)[source]

Start the process to manage the central utopia-hub

Parameters:label (str) – a textual name for this process
Raises:ValueError – unrecognised arguments, e.g. acquisition type.
Returns:sub-process for managing the started acquisition driver
Return type:hub (Process)
mindaffectBCI.online_bci.startPresentationProcess(presentation, presentation_args)[source]
mindaffectBCI.online_bci.startacquisitionProcess(acquisition, acq_args, label='online_bci', logdir=None)[source]

Start the process to manage the acquisition of data from the amplifier

Parameters:
  • label (str) – a textual name for this process
  • acquisition (str) – the name for the acquisition device to start. One-of: ‘none’ - do nothing, ‘brainflow’ - use the mindaffectBCI.examples.acquisition.utopia_brainflow driver ‘fakedata’- start a fake-data streamer ‘eego’ - start the ANT-neuro eego driver ‘lsl’ - start the lsl EEG sync driver
  • acq_args (dict) – dictionary of additional arguments to pass to the acquisition device
Raises:

ValueError – unrecognised arguments, e.g. acquisition type.

Returns:

sub-process for managing the started acquisition driver

Return type:

Process

mindaffectBCI.online_bci_pi module

mindaffectBCI.ssdpDiscover module

mindaffectBCI.ssdpDiscover.discoverOrIPscan(port: int = 8400, timeout_ms: int = 15000)[source]

[summary]

Parameters:
  • port (int, optional) – [description]. Defaults to 8400.
  • timeout_ms (int, optional) – [description]. Defaults to 15000.
Returns:

[description]

Return type:

[type]

mindaffectBCI.ssdpDiscover.get_all_ips()[source]

[summary]

Returns:[description]
Return type:[type]
mindaffectBCI.ssdpDiscover.get_ip_address(NICname)[source]

[summary]

Parameters:NICname ([type]) – [description]
Returns:[description]
Return type:[type]
mindaffectBCI.ssdpDiscover.get_local_ip()[source]

[summary]

Returns:[description]
Return type:[type]
mindaffectBCI.ssdpDiscover.get_remote_ip()[source]

[summary]

Returns:[description]
Return type:[type]
mindaffectBCI.ssdpDiscover.ip_is_local(ip_string)[source]

Uses a regex to determine if the input ip is on a local network. Returns a boolean. It’s safe here, but never use a regex for IP verification if from a potentially dangerous source.

Parameters:ip_string ([type]) – [description]
Returns:[description]
Return type:[type]
mindaffectBCI.ssdpDiscover.ipscanDiscover(port: int, ip: str = None, timeout=0.5)[source]

scan for service by trying all 255 possible final ip-addresses

Parameters:
  • port (int) – [description]
  • ip (str, optional) – [description]. Defaults to None.
  • timeout (float, optional) – [description]. Defaults to .5.
Returns:

[description]

Return type:

[type]

mindaffectBCI.ssdpDiscover.nic_info()[source]

Return a list with tuples containing NIC and IPv4 address

Returns:[description]
Return type:[type]
class mindaffectBCI.ssdpDiscover.ssdpDiscover(servicetype='ssdp:all', discoverytimeout=3)[source]

Bases: object

[summary]

Returns:[description]
Return type:[type]
discover(timeout=0.001, querytimeout=5, v6=False, intf=None)[source]
auto-discover the utopia-hub using ssdp discover messages,
timeout is time to wait for a response. query timeout is time between re-sending the ssdp-discovery query message.
Parameters:
  • timeout (float, optional) – [description]. Defaults to .001.
  • querytimeout (int, optional) – [description]. Defaults to 5.
  • v6 (bool, optional) – [description]. Defaults to False.
  • intf ([type], optional) – [description]. Defaults to None.
Returns:

[description]

Return type:

[type]

initSocket(v6=False, intf=None)[source]

[summary]

Parameters:
  • v6 (bool, optional) – [description]. Defaults to False.
  • intf ([type], optional) – [description]. Defaults to None.
makeDiscoveryMessage(ssdpgroup, servicetype, timeout)[source]

[summary]

Parameters:
  • ssdpgroup ([type]) – [description]
  • servicetype ([type]) – [description]
  • timeout ([type]) – [description]
Returns:

[description]

Return type:

[type]

msearchTemplate = 'M-SEARCH * HTTP/1.1\r\nHOST: {0}:{1}\r\nMAN: "ssdp:discover"\r\nST: {st}\r\nMX: {mx}\r\n\r\n'[source]
ssdpgroup = None[source]
ssdpv4group = ('239.255.255.250', 1900)[source]
ssdpv6group = ('FF08::C', 1900)[source]
wait_msearch_response(timeout, verb=0)[source]

[summary]

Parameters:
  • timeout ([type]) – [description]
  • verb (int, optional) – [description]. Defaults to 0.
Returns:

[description]

Return type:

[type]

mindaffectBCI.ssdpDiscover.testIncrementalScanning()[source]

[summary]

mindaffectBCI.stimseq module

class mindaffectBCI.stimseq.StimSeq(st=None, ss=None, es=None)[source]

Bases: object

[summary]

Raises:
  • Exception – [description]
  • Exception – [description]
Returns:

[description]

Return type:

[type]

convertstimSeq2int(scale=1)[source]

[summary]

Parameters:scale (int, optional) – [description]. Defaults to 1.
eventSeq = None[source]
static float2int(stimSeq, scale=1, minval=None, maxval=None)[source]

convert float list of lists to integer

Parameters:
  • stimSeq ([type]) – [description]
  • scale (int, optional) – [description]. Defaults to 1.
  • minval ([type], optional) – [description]. Defaults to None.
  • maxval ([type], optional) – [description]. Defaults to None.
Returns:

[description]

Return type:

[type]

static fromFile(fname)[source]

read a stimulus-sequence from a file on disk

Parameters:fname ([type]) – [description]
Returns:[description]
Return type:[type]
static fromString(f)[source]

read a stimulus-sequence definition from a string

Parameters:f ([type]) – [description]
Raises:Exception – [description]
Returns:[description]
Return type:[type]
static readArray(f, width=-1)[source]

[summary]

Parameters:
  • f ([type]) – [description]
  • width (int, optional) – [description]. Defaults to -1.
Raises:

Exception – [description]

Returns:

[description]

Return type:

[type]

setStimRate(rate)[source]

rewrite the stimtimes to equal given rate in hz

Parameters:rate ([type]) – [description]
stimSeq = None[source]
stimTime_ms = None[source]
toFile(fname)[source]

[summary]

Parameters:fname ([type]) – [description]
mindaffectBCI.stimseq.mkCodes()[source]

[summary]

mindaffectBCI.stimseq.mkFreqTag(period_phase=((4, 0), (5, 0), (6, 0), (7, 0), (8, 0), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (3, 2), (4, 2), (5, 2), (6, 2), (7, 2), (8, 2), (4, 3), (5, 3), (6, 3), (7, 3), (8, 3), (5, 4), (6, 4), (7, 4), (8, 4), (6, 5), (7, 5), (8, 5), (7, 6), (8, 6), (8, 7)), nEvent=120, isbinary=True)[source]

Generate a frequency tagging stimulus sequence

Parameters:
  • period_phase (list, optional) – List of stimulus periods and phase offsets expressed in events. Defaults to all phases from 2-5 long.
  • nEvent (int, optional) – total length of the sequence to generate. (To avoid steps should be LCM of periods) Defaults to 120.
  • isbinary (bool, optional) – flag if we generate a binary sequence or continuous
mindaffectBCI.stimseq.mkRowCol(width=5, height=5, repeats=10)[source]

Make a row-column stimulus sequence

Parameters:
  • width (int, optional) – width of the matrix. Defaults to 5.
  • height (int, optional) – height of the matrix. Defaults to 5.
  • repeats (int, optional) – number of random row->col repeats. Defaults to 10.
Returns:

The generated stimulus sequence

Return type:

[StimSeq]

mindaffectBCI.stimseq.setStimRate(stimTime_ms, framerate)[source]

rewrite the stim-times to a new frequency

Parameters:
  • stimTime_ms ([type]) – [description]
  • framerate ([type]) – [description]
Returns:

[description]

Return type:

[type]

mindaffectBCI.stimseq.transpose(M)[source]

[summary]

Parameters:M ([type]) – [description]
Returns:[description]
Return type:[type]

mindaffectBCI.utopia2output module

class mindaffectBCI.utopia2output.Utopia2Output(outputPressThreshold=None, outputReleaseThreshold=None, objectID2Action=None)[source]

Bases: object

Example class for a utopia OUTPUT module. Connects to the utopia server and then either, depending on mode:

  1. listens for output which exceed it’s probability threshold before

then printing them and using NEWTARGET to indicated the output has taken place

connect(host=None, port=None, timeout_ms=30000)[source]

[summary]

Parameters:
  • host ([type], optional) – [description]. Defaults to None.
  • port ([type], optional) – [description]. Defaults to None.
  • timeout_ms (int, optional) – [description]. Defaults to 30000.
doOutput(objID)[source]

This function is run when objID has sufficiently low error to mean that and output should be generated for this objID. N.B. Override/Replace this function with your specific output method.

perrModeOutput(msgs)[source]
process a perr-message generating appropriate output.
To avoid ‘key-bounce’ we use a press-release semantics, where the output is ‘Pressed’ so the output is generated when the Perr < outputPressThreshold, then further output is inhibited until Perr > outputReleaseThreshold.
Parameters:msgs ([type]) – [description]
run(timeout_ms=3000)[source]

mainloop of utopia-to-output mapping runs an infinite loop, waiting for new messages from utopia, filtering out those mesages which contain an output prediction (i.e. PREDICTEDTARGETPROB message) and if the output prediction is sufficiently confident forwarding this to the output device and sending a NEWTARGET to the recogniser to indicate the output was sent

Parameters:timeout_ms (int, optional) – [description]. Defaults to 3000.
selectionModeOutput(msgs)[source]

Process selection message to generate output. Basically generate output if the messages objectID is one of the ones we are tasked with generating output for

Parameters:msgs ([type]) – [description]

mindaffectBCI.utopiaController module

class mindaffectBCI.utopiaController.UtopiaController(clientid=None)[source]

Bases: object

controller class to manage the interaction with the Mindaffect decoder, setting up the connection, sending and recieving messages, and firing message event handlers

Raises:ValueError – [description]
Returns:[description]
Return type:[type]
addMessageHandler(cb)[source]

[summary]

Parameters:cb (function) – [description]
addPredictionHandler(cb)[source]

[summary]

Parameters:cb (function) – [description]
addSelectionHandler(cb)[source]

[summary]

Parameters:cb (function) – [description]
addSignalQualityHandler(cb)[source]

[summary]

Parameters:cb (function) – [description]
addSubscription(msgs)[source]

[summary]

Parameters:msgs ([type]) – [description]
autoconnect(host=None, port=8400, timeout_ms=5000, localhostifhostnotfound=True, queryifhostnotfound=True, scanifhostnotfound=False)[source]

[summary]

Parameters:
  • host ([type], optional) – [description]. Defaults to None.
  • port (int, optional) – [description]. Defaults to 8400.
  • timeout_ms (int, optional) – [description]. Defaults to 5000.
  • localhostifhostnotfound (bool, optional) – [description]. Defaults to True.
  • queryifhostnotfound (bool, optional) – [description]. Defaults to True.
  • scanifhostnotfound (bool, optional) – [description]. Defaults to False.
clearLastPrediction()[source]

clear the last predicted target

getLastPrediction()[source]

check for new predictions from the utopia-decoder

Returns:[description]
Return type:[type]
getLastSelection()[source]

check if any object prediction is high enough for it to be selected

Returns:[description]
Return type:[type]
getLastSignalQuality()[source]

[summary]

Returns:[description]
Return type:[type]
getNewMessages(timeout_ms=0)[source]

get new messages from the utopia-hub, and store the list of new

Parameters:timeout_ms (int, optional) – [description]. Defaults to 0.
Returns:[description]
Return type:[type]
getTimeStamp()[source]

get a (relative) wall-time stamp in milliseconds

gethostport()[source]
isConnected()[source]
log(msg)[source]

[summary]

Parameters:msg ([type]) – [description]
mkStimulusEvent(stimulusState, timestamp=None, targetState=None, objIDs=None)[source]

make a valid stimulus event for the given stimulus state

Parameters:
  • stimulusState ([type]) – [description]
  • timestamp ([type], optional) – [description]. Defaults to None.
  • targetState ([type], optional) – [description]. Defaults to None.
  • objIDs ([type], optional) – [description]. Defaults to None.
Raises:

ValueError – [description]

Returns:

[description]

Return type:

[type]

modeChange(newmode)[source]

[summary]

Parameters:newmode ([type]) – [description]
newTarget()[source]

[summary]

removeSubscription(msgs)[source]

[summary]

Parameters:msgs ([type]) – [description]
selection(objID)[source]

[summary]

Parameters:objID ([type]) – [description]
sendStimulusEvent(stimulusState, timestamp=None, targetState=None, objIDs=None)[source]

Send a message to the Utopia-HUB informing of the current stimulus state

Parameters:
  • stimulusState ([type]) – [description]
  • timestamp ([type], optional) – [description]. Defaults to None.
  • targetState ([type], optional) – [description]. Defaults to None.
  • objIDs ([type], optional) – [description]. Defaults to None.
Returns:

[description]

Return type:

[type]

setTimeStampClock(tsclock)[source]

[summary]

Parameters:tsclock ([type]) – [description]
Returns:[description]
Return type:[type]
subscribe(msgs=None)[source]

[summary]

Parameters:msgs ([type], optional) – [description]. Defaults to None.
mindaffectBCI.utopiaController.injectERP(amp, host='localhost', port=8300)[source]

Inject an erp into a simulated data-stream, sliently ignore if failed, e.g. because not simulated

Parameters:
  • amp ([type]) – [description]
  • host (str, optional) – [description]. Defaults to “localhost”.
  • port (int, optional) – [description]. Defaults to 8300.
mindaffectBCI.utopiaController.newMessageHandler(msgs)[source]

[summary]

Parameters:msgs ([type]) – [description]

mindaffectBCI.utopiaclient module

This module contains the message classes for communication with the mindaffect BCI hub and a simple client for connecting to and managing this connection.

class mindaffectBCI.utopiaclient.DataHeader(timestamp=None, fsample=None, nchannels=None, labels=None)[source]

Bases: mindaffectBCI.utopiaclient.UtopiaMessage

the DATAHEADER utopia message class – which is used to give general meta-information about the EEG stream

static deserialize(buf)[source]

Static method to create a HEADER class from a PAYLOAD byte-stream, return created object and the number of bytes consumed from buf

Parameters:buf (bytes) – the message buffer
Returns:the decoded message
Return type:UtopiaMessage
msgID = 65[source]
msgName = 'DATAHEADER'[source]
serialize()[source]
Returns the contents of this event as a byte-stream, ready to send over the network,
or None in case of conversion problems.
Returns:the encoded message
Return type:bytes
class mindaffectBCI.utopiaclient.DataPacket(timestamp=None, samples=None)[source]

Bases: mindaffectBCI.utopiaclient.UtopiaMessage

the DATAPACKET utopia message class — which is used to stream raw (time,channels) EEG data packets.

static deserialize(buf)[source]

Static method to create a STIMULUSEVENT class from a PAYLOAD byte-stream, return created object and the number of bytes consumed from buf

Parameters:buf (bytes) – the message buffer
Returns:the decoded message
Return type:UtopiaMessage
msgID = 68[source]
msgName = 'DATAPACKET'[source]
serialize()[source]
Returns the contents of this event as a byte-stream, ready to send over the network,
or None in case of conversion problems.
Returns:the encoded message
Return type:bytes
class mindaffectBCI.utopiaclient.Heartbeat(timestamp: int = None, statemessage: str = None)[source]

Bases: mindaffectBCI.utopiaclient.UtopiaMessage

the HEARTBEAT utopia message class

static deserialize(buf)[source]

Static method to create a HEARTBEAT class from a PAYLOAD byte-stream, return the number of bytes consumed from buf

Parameters:buf (bytes) – the message buffer
Returns:the decoded message
Return type:Heartbeat
msgID = 72[source]
msgName = 'HEARTBEAT'[source]
serialize()[source]

Returns the contents of this event as a string, ready to send over the network, or None in case of conversion problems.

Returns:the serialized version of this message
Return type:bytes
class mindaffectBCI.utopiaclient.Log(timestamp: int = None, logmsg: str = None)[source]

Bases: mindaffectBCI.utopiaclient.UtopiaMessage

the LOG utopia message class – which is used to send arbitary log messages to the hub

static deserialize(buf)[source]

Static method to create a MODECHANGE class from a PAYLOAD byte-stream, return the number of bytes consumed from buf

Parameters:buf (bytes) – the message buffer
Returns:the decoded message
Return type:UtopiaMessage
msgID = 76[source]
msgName = 'LOG'[source]
serialize()[source]
Returns the contents of this event as a byte-stream, ready to send over the network,
or None in case of conversion problems.
Returns:the encoded message
Return type:bytes
class mindaffectBCI.utopiaclient.ModeChange(timestamp=None, newmode=None)[source]

Bases: mindaffectBCI.utopiaclient.UtopiaMessage

the MODECHANGE utopia message class – which is used to tell the decoder to change system modes, for example to switch to calibration-mode.

static deserialize(buf)[source]

Static method to create a MODECHANGE class from a PAYLOAD byte-stream, return the number of bytes consumed from buf

Parameters:buf (bytes) – the message buffer
Returns:the decoded message
Return type:UtopiaMessage
msgID = 77[source]
msgName = 'MODECHANGE'[source]
serialize()[source]
Returns the contents of this event as a byte-stream, ready to send over the network,
or None in case of conversion problems.
Returns:the encoded message
Return type:bytes
class mindaffectBCI.utopiaclient.NewTarget(timestamp=None)[source]

Bases: mindaffectBCI.utopiaclient.UtopiaMessage

the NEWTARGET utopia message class – which is used to tell other clients that a new target selection round has begun.

static deserialize(buf)[source]

Static method to create a HEARTBEAT class from a PAYLOAD byte-stream, return the number of bytes consumed from buf

Parameters:buf (bytes) – the message buffer
Returns:the decoded message
Return type:UtopiaMessage
msgID = 78[source]
msgName = 'NEWTARGET'[source]
serialize()[source]
Returns the contents of this event as a byte-stream, ready to send over the network,
or None in case of conversion problems.
Returns:the encoded message
Return type:bytes
class mindaffectBCI.utopiaclient.PredictedTargetDist(timestamp=None, objIDs=None, pTgt=None)[source]

Bases: mindaffectBCI.utopiaclient.UtopiaMessage

the PredictedTargetDist utopia message class – which is used to send information about the current predicted target probabilites for the outputs

static deserialize(buf)[source]

Static method to create a PREDICTEDTARGETDIST class from a PAYLOAD byte-stream, return created object and the number of bytes consumed from buf

Parameters:buf (bytes) – the message buffer
Returns:the decoded message
Return type:UtopiaMessage
msgID = 70[source]
msgName = 'PREDICTEDTARGETDIST'[source]
serialize()[source]
Returns the contents of this event as a byte-stream, ready to send over the network,
or None in case of conversion problems.
Returns:the encoded message
Return type:bytes
class mindaffectBCI.utopiaclient.PredictedTargetProb(timestamp=None, Yest: int = -1, Perr: float = 1.0)[source]

Bases: mindaffectBCI.utopiaclient.UtopiaMessage

the PREDICTEDTARGETPROB utopia message class – which is used to communicate the most likely target and the estimate error rate for this prediction.

static deserialize(buf)[source]

Static method to create a MODECHANGE class from a PAYLOAD byte-stream, return the number of bytes consumed from buf

Parameters:buf (bytes) – the message buffer
Returns:the decoded message
Return type:UtopiaMessage
msgID = 80[source]
msgName = 'PREDICTEDTARGETPROB'[source]
serialize()[source]
Returns the contents of this event as a byte-stream, ready to send over the network,
or None in case of conversion problems.
Returns:the encoded message
Return type:bytes
class mindaffectBCI.utopiaclient.RawMessage(msgID, version, payload)[source]

Bases: mindaffectBCI.utopiaclient.UtopiaMessage

Class for a raw utopia message, i.e. decoded header but raw payload

classmethod deserialize(buf)[source]

Read a raw message from a byte-buffer, return the read message and the number of bytes used from the bytebuffer, or None, 0 if message is mal-formed

Parameters:buf (bytes) – the byte buffer to read from
Returns:the decoded raw message
Return type:RawMessage
classmethod deserializeMany(buf)[source]

decode multiple RawMessages from the byte-buffer of data, return the length of data consumed.

Parameters:buf (bytes) – the byte buffer to read from
Returns:the list of decoded raw messages
Return type:list-of-RawMessage
classmethod fromUtopiaMessage(msg: mindaffectBCI.utopiaclient.UtopiaMessage)[source]

Construct a raw-message wrapper from a normal payload message

Parameters:msg (UtopiaMessage) – the message to make to raw
Returns:the raw version of this utopia message
Return type:RawMessage
msgName = 'RAW'[source]
serialize()[source]

convert the raw message to the string to make it network ready

Returns:the byte serialized version of this raw message
Return type:bytes
class mindaffectBCI.utopiaclient.Reset(timestamp=None)[source]

Bases: mindaffectBCI.utopiaclient.UtopiaMessage

the RESET utopia message class – which is used to tell the decoder to reset and clear it’s model information.

static deserialize(buf)[source]

Static method to create a RESET class from a PAYLOAD byte-stream, return the number of bytes consumed from buf

Parameters:buf (bytes) – the message buffer
Returns:the decoded message
Return type:UtopiaMessage
msgID = 82[source]
msgName = 'RESET'[source]
serialize()[source]
Returns the contents of this event as a byte-stream, ready to send over the network,
or None in case of conversion problems.
Returns:the encoded message
Return type:bytes
class mindaffectBCI.utopiaclient.Selection(timestamp=None, objID=None)[source]

Bases: mindaffectBCI.utopiaclient.UtopiaMessage

the SELECTION utopia message class – which is used to inform other clients that a particular output has been selected by this client.

static deserialize(buf)[source]

Static method to create a SELECTION class from a PAYLOAD byte-stream, return the number of bytes consumed from buf

Parameters:buf (bytes) – the message buffer
Returns:the decoded message
Return type:UtopiaMessage
msgID = 83[source]
msgName = 'SELECTION'[source]
serialize()[source]
Returns the contents of this event as a byte-stream, ready to send over the network,
or None in case of conversion problems.
Returns:the encoded message
Return type:bytes
class mindaffectBCI.utopiaclient.SignalQuality(timestamp: int = None, signalQuality=None)[source]

Bases: mindaffectBCI.utopiaclient.UtopiaMessage

the SIGNALQUALITY utopia message class – which is used to send information about the estimated signal to noise for each channel in the data stream

static deserialize(buf)[source]

Static method to create a SIGNALQUALIYT class from a PAYLOAD byte-stream, return the number of bytes consumed from buf

Parameters:buf (bytes) – the message buffer
Returns:the decoded message
Return type:UtopiaMessage
msgID = 81[source]
msgName = 'SIGNALQUALITY'[source]
serialize()[source]
Returns the contents of this event as a byte-stream, ready to send over the network,
or None in case of conversion problems.
Returns:the encoded message
Return type:bytes
class mindaffectBCI.utopiaclient.StimulusEvent(timestamp=None, objIDs=None, objState=None)[source]

Bases: mindaffectBCI.utopiaclient.UtopiaMessage

the STIMULUSEVENT utopia message class – which is used to send information about the current stimulus state of this client to other clients

static deserialize(buf)[source]

Static method to create a STIMULUSEVENT class from a PAYLOAD byte-stream, return created object and the number of bytes consumed from buf

Parameters:buf (bytes) – the message buffer
Returns:the decoded message
Return type:UtopiaMessage
msgID = 69[source]
msgName = 'STIMULUSEVENT'[source]
serialize()[source]

Converts this message to a string representation to send over the network

Returns:the encoded message
Return type:bytes
class mindaffectBCI.utopiaclient.Subscribe(timestamp=None, messageIDs=None)[source]

Bases: mindaffectBCI.utopiaclient.UtopiaMessage

the SUBSCRIBE utopia message class – which is used to tell the hub which messages IDs to forward to this client.

static deserialize(buf)[source]

Static method to create a SIGNALQUALITY class from a PAYLOAD byte-stream, return the number of bytes consumed from buf

Parameters:buf (bytes) – the message buffer
Returns:the decoded message
Return type:UtopiaMessage
msgID = 66[source]
msgName = 'SUBSCRIBE'[source]
serialize()[source]
Returns the contents of this event as a byte-stream, ready to send over the network,
or None in case of conversion problems.
Returns:the encoded message
Return type:bytes
class mindaffectBCI.utopiaclient.TimeStampClock[source]

Bases: object

Base class for time-stamp sources. Match this prototype to replace the default timestamp source

getTimeStamp()[source]

get the time-stamp in milliseconds ! N.B. must fit in an int32!

Returns:the timestamp
Return type:int
class mindaffectBCI.utopiaclient.UtopiaClient(clientstate=None)[source]

Bases: object

Class for managing a client connection to a UtopiaServer.

DEFAULTHOST = 'localhost'[source]
DEFAULTPORT = 8400[source]
HEARTBEATINTERVALUDP_ms = 200[source]
HEARTBEATINTERVAL_ms = 1000[source]
MAXMESSAGESIZE = 1048576[source]
UTOPIA_SSDP_SERVICE = 'utopia/1.1'[source]
autoconnect(hostname=None, port=None, timeout_ms=5000, queryifhostnotfound=False, localhostifhostnotfound=True, scanifhostnotfound=False)[source]

connect to the hub/decoder, auto-discover if explict IP address is not given

Parameters:
  • hostname (str, optional) – hostname or IP where the hub resides. Defaults to None.
  • port (int, optional) – port where the host is listening. Defaults to 8400.
  • timeout_ms (int, optional) – timeout in milliseconds for discovery. Defaults to 5000.
  • queryifhostnotfound (bool, optional) – query the user for autodiscover fails. Defaults to False.
  • localhostifhostnotfound (bool, optional) – try localhost if autodiscovery fails. Defaults to True.
  • scanifhostnotfound (bool, optional) – scan all local IP addresses if autodiscovery fails. Defaults to False.
Raises:

socket.error – if there is a socket error ;)

connect(hostname=None, port=8400)[source]

connect([hostname, port]) – make a connection, default host:port is localhost:1972

Parameters:
  • hostname (str, optional) – hostname or IP where the hub resides. Defaults to None.
  • port (int, optional) – port where the host is listening. Defaults to 8400.
Returns:

the current connection status

Return type:

bool

disableHeartbeats()[source]

‘ stop sending hearbeat messages. Use, e.g. when you want to use your own time-stamp clock.

disconnect()[source]

disconnect() – close a connection.

enableHeartbeats()[source]

start sending heartbeat messages every few seconds

getNewMessages(timeout_ms=250)[source]

Wait for new messages from the utopia-server (with optional timeout), decode them and return the list of new messages

Parameters:timeout_ms (int, optional) – timeout in milliseconds to wait for the new messages. Defaults to 250.
Returns:the list of recieved messages
Return type:list-of-UtopiaMessage
getTimeStamp()[source]

Get the time-stamp for the current time

Returns:the current timestamp
Return type:int
gethostport()[source]

[summary]

Returns:[description]
Return type:[type]
initClockAlign(delays_ms=[50, 50, 50, 50, 50, 50, 50, 50, 50, 50])[source]

Send some initial heartbeat messages to seed the alignment of the server clock with our local clock

Parameters:delays_ms (list-of-int, optional) – delay in milliseconds between sending the heartbeat messages. Defaults to [50]*10.
messagePingPong(timeout_ms=500)[source]

Testing system sending 20 messages and printing any responses

Parameters:timeout_ms (int, optional) – delay when waiting for messages. Defaults to 1000.
messagelogger(timeout_ms=1000)[source]

Simple message logger, infinite loop waiting for and printing messages from the server

Parameters:timeout_ms (int, optional) – delay when waiting for messages. Defaults to 1000.
recvall(timeout_ms=0)[source]

Read all the data from the socket immeaditely or block for timeout_ms if nothing to do.

Parameters:timeout_ms (int, optional) – timeout in milliseconds for the read. Defaults to 0.
Returns:the raw stream of bytes from the socket
Return type:bytes
sendHeartbeatIfTimeout(timestamp=None)[source]

send a heartbeat message if the timeout since the last such message has passed.

Parameters:timestamp (int, optional) – The current timestamp. Defaults to None.
sendMessage(msg: mindaffectBCI.utopiaclient.UtopiaMessage)[source]

send a UtopiaMessage to the hub

Parameters:msg (UtopiaMessage) – the message to send
sendMessages(msgs)[source]

sends single or multiple utopia-messages to the utopia server

Parameters:msgs (list-of-UtopiaMessage) – list of messages to send
sendRaw(request)[source]

Send all bytes of the string ‘request’ out to the connected hub/decoder

Parameters:request (bytes) – the raw stream to send
Raises:IOError – if the send fails
sendRawUDP(request)[source]

send a raw byte stream over a UDP socket

Parameters:request (bytes) – the raw stream to send
setTimeStampClock(tsClock)[source]

set the clock to use for timestamping outgoing messages

Parameters:tsClock (TimeStampClock) – the timestamp clock to use
Raises:ValueError – if the tsClock does not have a getTimeStamp method
try_connect(hostname, port=None, timeout_ms=5000)[source]

try to connect to the hub

Parameters:
  • hostname (str, optional) – hostname or IP where the hub resides. Defaults to None.
  • port (int, optional) – port where the host is listening. Defaults to 8400.
  • timeout_ms (int, optional) – timeout in milliseconds for discovery. Defaults to 5000.
class mindaffectBCI.utopiaclient.UtopiaMessage(msgID=0, msgName=None, version=0)[source]

Bases: object

Class for a generic UtopiaMessage, i.e. the common structure of all messages

mindaffectBCI.utopiaclient.decodeRawMessage(msg)[source]

decode utopia RawMessages into actual message objects

Parameters:msg (RawMessage) – the raw message whose payload should be decoded
Returns:the decoded specific message type
Return type:StimulusEvent|Heartbeat|….
mindaffectBCI.utopiaclient.decodeRawMessages(msgs)[source]

decode utopia RawMessages into actual message objects

Parameters:msgs (list-of-RawMessage) – list of RawMessages to decode the payload of
Returns:list of the fully decoded messages
Return type:list-of-messages
mindaffectBCI.utopiaclient.ssdpDiscover(servicetype=None, timeout=3, numretries=1)[source]

auto-discover the utopia-hub using ssdp discover messages

Parameters:
  • servicetype (str, optional) – the SSDP service type to search for. Defaults to None.
  • timeout (int, optional) – timeout in seconds for the discovery. Defaults to 3.
  • numretries (int, optional) – number of times to retry discovery. Defaults to 1.
Returns:

list of the IP addresses of the discovered servers

Return type:

list-of-str

mindaffectBCI.utopiaclient.testSending()[source]

test object sending by connecting and sending a set of test messages to the server

mindaffectBCI.utopiaclient.testSerialization()[source]

test object serialization and deserialization by encoded and decoding messages

Module contents