Tutorial - Using Matlab With OpenViBE - OpenViBE PDF
Tutorial - Using Matlab With OpenViBE - OpenViBE PDF
Downloads
Features
Documentation
Forum
FAQ
Contact
Search...
BrowseBurst
Related Searches
Note: V0.16.x has a bug that Matlab working directory path can not contain spaces, preventing running Matlab
tutorial scenarios from their default install location on Windows in Program Files (x86). To use the scenarios,
please move them to a folder with no spaces in the path. (This issue has been fixed in the git version.)
Note: On V0.17.0 and Linux, the presence of matlab plugin .so can cause crashes in seemingly unrelated Simple
?
Interface Design
3D Virtual World
DSP box as the two may use different versions of boost which are then wrongly exposed to the other party due to
the dlopen() flag RTLD_GLOBAL. Unfortunately this flag is needed or we get other issues with third-party libraries,
for example that the imports done inside Python plugin scripts no longer work. The compromise solution is that
Matlab plugin compilation is currently by default DISABLED in the main CMakeLists.txt. You may enable the Matlab
Brain Control
Cognitive
plugin compilation and possibly set the flag to RTLD_LOCAL to avoid issues in ovCKernelLoader.cpp, but be aware
of the consequences.
Neuroscience
Neurofeedback
Training
Biofeedback Therapy
EEG Neurofeedback
Biofeedback Therapist
Introduction
OpenViBE is currently compatible with MATLAB through a box:
Matlab Scripting: a general-purpose box with unlimited inputs, outputs and settings. User writes the Matlab functions that will be
called by the box.
This box is developed and supported by the Inria team. It relies on the Matlab Engine, and requires a valid installation of Matlab to be
compiled and to run. To be precise, the Matlab documentation states :
Brain Function
Virtual Reality World
The MATLAB engine library contains routines that allow you to call MATLAB software from your own programs, thereby
employing MATLAB as a computation engine. You must use an installed version of MATLAB; you cannot run the MATLAB
engine on a machine that only has the MATLAB Compiler Runtime (MCR).
The Matlab Scripting box is included in the official release packages, and thus can be used directly in any scenario, as long as you have
a valid Matlab installation on your computer.
Requirements
The Matlab box has been tested on Windows 7 32 bits + MATLAB R2011a 32 bits. Unfortunately Matlab R2011a is not compatible with
Ubuntu 11.04 and superior versions. The official ubuntu support page says : MATLAB R2011a was released on April 8, 2011. Please
note that this is prior to the release of Ubuntu 11.04. Consequently Ubuntu 11.04 is not a supported operating system for MATLAB
R2011a. MATLAB R2011a users are strongly encouraged to install R2011a on Ubuntu 10.04 LTS or Ubuntu 10.10 for best results..
http://openvibe.inria.fr/tutorial-using-matlab-with-openvibe/
1/14
12/30/2014
For your information, the latest Matlab Release (R2012a) is currently compatible with Ubuntu 10.04 LTS, 11.04, 11.10, as stated in the
Matlab support page.
The boxes are not compatible with MATLAB 64 bits on Windows.
Please contact us to inform us of any compatibility issue. We will update this section with your feedback !
If the build process does not find a valid MATLAB installation, the boxes wont be built with the project. An empty dynamic library will be
produced, which will result in the following message in the console when executing the OpenViBE Designer :
[WARNING] No 'plugin object descriptor' found from [../bin/openvibe-plugins-matlab.dll]
even if it looked like a plugin module
When building OpenViBE with an invalid MATLAB installation (i.e. MATLAB 64 bits on Windows) the build process will find MATLAB but
not the libs resulting in the following build log :
Build fails on Windows with MATLAB 64 bits
2/14
12/30/2014
If you are using the same workspace for several boxes, they will share this workspace. For example a global variable could be modified
by all the boxes of the same workspace.
Then it calls a function that will create several global variables for all the OpenViBE stimulation codes:
OV_defines()
The name of the variables and their values are strictly the same as in OpenViBE. For example:
global OVTK_StimulationId_Label_00;
OVTK_StimulationId_Label_00 = uint64(hex2dec('00008100')); // 33024
Thus you can directly compare a stimulation identifier received on an input to these global variables.
> box.inputs
> box.outputs
> box.user_data
The box clock and clock frequency are very useful when your script needs to generate an output, but lacks an input to synchronize with.
The setting structures are filled according to the openvibe box settings defined in the scenario. Default settings are not stored in the
structure.
STRUCT setting :
> setting.name : STRING (name of the setting in the openvibe box).
> setting.type : UINT64 openvibe code of the setting type.
http://openvibe.inria.fr/tutorial-using-matlab-with-openvibe/
3/14
12/30/2014
The input and output structures are defined by particular headers, and are meant to be filled at run time. When the Matlab Scripting box
receives the headers on its inputs it forwards the information to Matlab, and modify the box representation accordingly.
The output headers structure must be set by the user in the Matlab script. Once the header is set, the Matlab Scripting box is able to get
this information from the matlab structure and construct the corresponding OpenViBE header.
The IO structures also contains a buffer for the incoming chunk of data.
STRUCT input/output :
> io.header : STRUCT containing the stream description (e.g. for a signal: channel names, sampling rate, etc).
> io.buffer : CELL ARRAY of chunk structure(s).
The different header structures are listed below, along with the corresponding functions to set it in a convenient way (i.e. you wont miss a
field). Manually setting the header structures of your output is of course also possible (e.g. if your output stream has the same structure as
an input, input.header = output.header is the simplest way to set it).
NB: A corresponding Getter function also exists for each header type. These functions are called by the Matlab Scripting box to get all the
information in one call to the Matlab engine.
STRUCT header : STREAMED MATRIX
> header.type
> header.nb_dimensions
> header.dimension_sizes : 1xN DOUBLE ARRAY of dimension sizes (one size per dimension)
> header.dimension_labels : 1xN CELL ARRAY of STRING
> header.nb_channels
> header.sampling_rate
> header.nb_channels
http://openvibe.inria.fr/tutorial-using-matlab-with-openvibe/
4/14
12/30/2014
> header.band_names
> header.bands
> header.nb_channels
As you can see all the setter functions take a box structure as input, and output the modified box structure. A typical call is thus:
box = OV_setXXXXXOutputHeader(box, ...)
% ... continue using the 'box' variable ...
The chunk structure stored in the IO buffers can be either a matrix (for Stramed Matrix stream and its child streams) or a stimulation set.
STRUCT chunk : MATRIX CHUNK
> chunk.start_time : DOUBLE translation of the openvibe timestamp in seconds, precision 0.0001 sec.
> chunk.end_time
: DOUBLE
: DOUBLE
The buffers may contains any number of chunks. The buffers can be manipulated through convenient matlab functions:
% To get the current count of pending chunk in buffer:
nb_pending = OV_getNbPendingInputChunk(box_in, input_index)
out DOUBLE nb_pending : the number of pending chunk in the buffer.
in STRUCT box_in
% To pop the oldest chunk in a buffer (i.e. the first chunk to process)
http://openvibe.inria.fr/tutorial-using-matlab-with-openvibe/
5/14
12/30/2014
out ARRAY matrix_data : the data, type and structure depends on the stream type.
in STRUCT box_in
= -1
> matrix_data = []
When you need to output a new buffer, you can do so by calling the following function:
% To add a new chunk in an output buffer:
[box_out] = OV_addOutputBuffer(box_in,output_index,start_time,end_time,matrix_data);
out DOUBLE box_out
in STRUCT box_in
in DOUBLE end_time
in ARRAY matrix_data : the data, type and structure depends on the stream type
6/14
12/30/2014
Initialization script
Open the Matlab function file tuto1_signal_filter_Initialize.m.
tuto1_signal_filter_Initialize.m
This function add a field in the user_data structure in the box : a boolean indicating the current state of the trigger. Please note that we
must output the modified box to be able to use it afterwards. This function will be called once, when pressing play in the scenario.
Process script
Open the Matlab function file tuto1_signal_filter_Process.m.
tuto1_signal_filter_Process.m
As we set the box clock frequency to 64 Hz, this function will be called 64 time per second. It works in two steps. First we check the
stimulation input for new triggers, and switch the box field accordingly. Note that every time we pop a new input chunk, we use the current
box instance as output, to continue the processing on an updated box structure. In this case, the pop functions remove the last input
chunk from the buffer.
As we only modify the samples values of the input signal, we set the output header as a copy of the input header. This will be done with
every process but it is only needed once (prior to the first buffer ever sent).
Uninitialization script
Open the Matlab function file tuto1_signal_filter_Uninitialize.m.
tuto1_signal_filter_Uninitialize.m
We dont need to do anything when stopping the scenario, we just display a message.
Execution
The result can be found below. The signal is set to 0 when the stimulation OVTK_StimulationId_Label_01 (33024) is received.
7/14
12/30/2014
Console output
Initialization script
Open the Matlab function file tuto2_FFT_filter_Initialize.m.
tuto2_FFT_filter_Initialize.m
This function prints the box settings and add fields in the user_data structure in the box : a boolean indicating if we need to set the output
header, and the variables we need to compute the mean spectrum. Please note that we must output the modified box to be able to use it
afterwards. This function will be called once, when pressing play in the scenario.
Process script
Open the Matlab function file tuto2_FFT_filter_Process.m.
tuto2_FFT_filter_Process.m
The header is set once, and hes just the input header with one constraint : one channel only.
The FFT is plotted on every input chunk. If your input stream has a high frequency, you wont be able to see something. In our scenario, we
compute a 2 second window before passing it to Matlab, using Time Based Epoching. Therefore you will have one figure updated every
2 seconds of signal.
http://openvibe.inria.fr/tutorial-using-matlab-with-openvibe/
8/14
12/30/2014
The figure plotted has 3 subfigures : the pure noise signal, the signal corrupted with this noise, and the amplitude spectrum.
Uninitialization script
Open the Matlab function file tuto2_FFT_filter_Uninitialize.m.
tuto2_FFT_filter_Uninitialize.m
The Uninitialize function plots the mean spectrum amplitude matrix and pauses the execution for 10 seconds. After the pause, the
scenario is stopped and the Matlab engine closed (so it closes any figure automatically).
Execution
http://openvibe.inria.fr/tutorial-using-matlab-with-openvibe/
9/14
12/30/2014
We added 4 new settings in the box : the channel count (integer), the samples per buffer count (integer), the amplitude of signal (float),
and the stimulation sent every second.
In the current configuration, the box clock frequency is set to 32Hz. With 16 samples per buffer, we thus have a sampling frequency of
32*16 = 512Hz.
The signal is simply a different sinusoid for each channel, the frequency being a multiple of 10Hz (10Hz for first channel, 20Hz for second,
etc.).
Initialization script
http://openvibe.inria.fr/tutorial-using-matlab-with-openvibe/
10/14
12/30/2014
This function prints the box settings and add fields in the user_data structure in the box : the end time of the last data chunk sent, a
sample and a chunk counters. As we produce ourselves the signal and stimulation streams, we can set the headers in the initialization
phase. For this purpose we use the functions of the openvibe toolbox.
Please note that we use the same variable box_in as output of these functions so we keep working on an updated box structure.
Process script
Open the Matlab function file tuto3_sinus_generator_Process.m.
tuto3_sinus_generator_Process.m
We produce a N-by-M signal matrix. One channel per line, samples_per_buffer columns. Along with each chunk of signal, we also
produce a stimulation set. Most of the time its an empty set, but its still important as the other box after our generator may need to know
if there is no stimulation is the last time range. As you notice, a stimulation set is made of N columns, one stimulation per column (stim
identifier, date then duration). This matrix structure allows the box to parse all the stimulations in a set directly, as the matrix is indexed
column after column.
Uninitialization script
Open the Matlab function file tuto3_sinus_generator_Uninitialize.m.
tuto3_sinus_generator_Uninitialize.m
Execution
The box generates some sinusoidal signal automatically, along with stimulations (one every second see the red lines):
Sinus Generator
In the console, you can see the corresponding output :
Console output
http://openvibe.inria.fr/tutorial-using-matlab-with-openvibe/
11/14
12/30/2014
This box is still flagged as deprecated, is not displayed in the Designer and is not recommended for use.
The Matlab Filter box has fixed inputs (1 streamed Matrix and 1 stimulation inputs), and fixed outputs (same). The box has to be
configured with the path or command to launch Matlab on your computer, the working directory in which you created the initialize
and process functions.
The Process function will be called every time a chunk is available on both inputs. It means that you absolutely need a Streamed Matrix
input (or derivated, e.g. signal) and a stimulation input. If you dont need one of them, you can use a dummy input using Clock stimulator
or Sinus Oscillator boxes on the useless input.
A simple example is provided with the Matlab Filter box documentation page.
The main difference between the 2 boxes is the data structure for the matrices: in the Matlab Filter box, the signal matrix is oriented as
N(channels)columns for N(samples)lines.
Troubleshooting
In this section, we review the most common errors and mistakes and what they can cause.
Please contact us on the regular channels if you find any unexpected behavior or bugs so we can either correct the Matlab boxes or add
new items in this section.
Failed to Load Matlab Engine at first try
With the Windows Installer version, we identified an incorrect behavior of the box : when pressing play for the first try, the scenario wont
find Matlab and the box will fail to execute correctly. When re-playing the scenario by pressing play once again, the Matlab Engine (if
everything is correctly set) should successfully run.
This bug does not happen with an OpenViBE built from sources. Investigations are in progress.
On Linux, MATLAB filter keeps saying Cant start MATLAB engine, what do I do ?
In order to get MATLAB filter to work properly on Linux, you need cshto be installed. This is not always the case, notably on Ubuntu
distributions.
On Linux, loading the Matlab plugin says error:libmx.so: cannot open shared object file: No such file or directory?
Before launching Designer, you must export LD_LIBRARY_PATH to include the path where the Matlab .so files are installed.
Matlab License
The Matlab Engine can be launched in background only if it can access a valid Matlab License.
If the Matlab License Manager cant get a valid License, it will output an error window. The OpenViBE Designer would then be still waiting
for the Matlab Engine to respond: you can expect the application to freeze for about 30 seconds. After this timeout, the call to Matlab
engine fails and the following message would be printed in the console:
[ ERROR ] At time 0.000 sec <Box algorithm::Matlab Scripting> Could not open Matlab engine
[WARNING] Box algorithm <Matlab Scripting> has been deactivated because initialization phase returned bad status
The box being deactivated, it does not process any data but the scenario would keep running without it.
Output Headers : be sure to set it right !
If you try to send a new buffer on an output and you get this message for example :
[ ERROR ] At time 0.094 sec <Box algorithm::Signal filter> Error calling [OV_getSignalOutputHeader]. Did you correctly set
the output header in the matlab structure ?
http://openvibe.inria.fr/tutorial-using-matlab-with-openvibe/
12/14
12/30/2014
It means that you didnt set the header (here its a signal output) correctly. The box is not able to construct the OpenViBE output stream.
Solution : set the header before the very first buffer sent. You can either use an existing header, as it is done in tutorial 1, or the
dedicated Matlab functions as in tutorial 3.
If you construct a somehow corrupted header or a header that does not match the theoretical stream structure, the application has a
good chance of crash.
For example, if you omit a field or use a field incorrectly (e.g. header.sampling_rate = 'plop') the Designer can just randomly
crash during execution. We are aware of this problem and we will try to improve error handling in the following updates.
Be sure to save your OpenViBE scenarios often.
Manually closing the Matlab engine
The Matlab Scripting box opens the Matlab Engine on initialization (play) and closes it when uninitializing (stop). If an error occurs the
Matlab Engine may not be closed correctly. This means that when you will run a scenario with a Matlab Scripting box once again, it will
use the previous engine, still in the state you left it ! This can lead to unexpected behavior (e.g. if you have some global variables you are
using in your script, they will still be there).
The simplest way to check the state of the Matlab Engine is by looking at the matlab window running in background. When opening the
engine, Matlab launch a specific window called Matlab Command Window. This window is a basic Matlab interpreter in which you can
type Matlab commands. When closing the Engine, this window should be closed automatically. If such window is still alive when there is
no Matlab scenario running in the OpenViBE Designer, close it manually before playing such scenario.
Performance issues
Depending on the processing you implemented the Matlab scripting boxes may take some time to do the process. If a box spends too
much time its process loop, a message would be printed in the console:
[WARNING] <Player::can not reach realtime> 1 second(s) late...
[WARNING] <Player::can not reach realtime> 2 second(s) late...
[WARNING] <Player::can not reach realtime> 3 second(s) late...
[WARNING] <Player::can not reach realtime> 4 second(s) late...
[WARNING] <Player::can not reach realtime> 5 second(s) late...
Meaning that the OpenViBE Player, that schedules the process of every boxes, is not able to process the data in real-time. For example,
if you set the Matlab scripting box clock frequency to 32Hz, one process call should be less than 1/32 th second long. Otherwise, the
process loop accumulates a delay.
Try to lower the clock frequency to extend the period of time between 2 process calls. The Matlab process function may have to process
more chunk of data at a time (internal buffers are filled continuously), but you will save the interface time, between the C++ code and the
Matlab engine.
This entry was posted in Tutorials and tagged Matlab, Tutorial. Bookmark the permalink.
Quick Access
OpenViBE World
Development
Community
Downloads
Contact
How to contribute
Forum
Source Repository
Publications
Bugtracker
Contributors
License
Made With
Inria gForge
Community Website
Features
Related Projects
Build status
Documentation
Inria Homepage
http://openvibe.inria.fr/tutorial-using-matlab-with-openvibe/
13/14
12/30/2014
T witter: @openvibebci
All logos and tradem arks belong to their respective copyright owners.
Hosted by
powered by WordPress
http://openvibe.inria.fr/tutorial-using-matlab-with-openvibe/
14/14