SPM and Python
Getting started
Cheat sheet
SPM-python implements types that are fully equivalent with MATLAB types.
This is a short reminder of conversion rules – more details are available
at the data types page.
General rules
MATLAB
cell
struct
single, double
Python
spm.Cell
spm.Struct
spm.Array, numpy.ndarray
Examples
MATLAB
A = cell(1, 3);
B = {"VTA", "M1", "vmPFC"};
C = struct;
C.A = A;
C.array = [1 2; 3 4];
Python
A = spm.Cell(1, 3)
B = spm.Cell.from_any(["VTA", "M1", "vmPFC"])
C = spm.Struct()
C.A = A
C.array = np.array([[1, 2], [3, 4]])
Minimal example
Here is a minimal set of examples showcasing changes to do to use existing
Matlab code in Python (taken from the OPM tutorial).
1. Importing and setting up SPM
Python
from spm import *
spm('defaults', 'eeg')
2. Constructing object
MATLAB
S = [];
S.data = 'OPM_meg_001.cMEG';
S.positions = 'OPM_HelmConfig.tsv';
D = spm_opm_create(S);
Python
S = Struct()
S.data = 'OPM_meg_001.cMEG'
S.positions = 'OPM_HelmConfig.tsv'
D = spm_opm_create(S)
Here, D will be a meeg object which contains a virtual representation
of the Matlab object. Class methods should work as expected, e.g.:
>>> D.fullfile()
'./OPM_meg_001.mat'
Note that the alternative call that exist in Matlab
(i.e., fullfile(D)) will not work.
3. Creating and handling figures
MATLAB
S = [];
S.triallength = 3000;
S.plot = 1;
S.D = D;
S.channels = 'MEG';
spm_opm_psd(S);
ylim([1,1e5])
Python
S = Struct()
S.triallength = 3000
S.plot = 1
S.D = D
S.channels = 'MEG'
spm_opm_psd(S)
This opens a Matlab figure, but we do not have the possibility of
manipulating it yet (e.g., calling ylim). As of now, we can view the
figures, have GUI interactions, but cannot manipulate figures with Python code.
4. Variable number of output arguments
MATLAB
S = [];
S.triallength = 3000;
S.plot = 1;
S.D = mD;
[~,freq] = spm_opm_psd(S);
Python
S = Struct()
S.triallength = 3000
S.plot = 1
S.D = mD
[_, freq] = spm_opm_psd(S, nargout=2)
In Python, the number of output arguments must be specified by the
nargout keyword argument.
5. Other examples
MATLAB
S = [];
S.D = D;
S.freq = [10];
S.band = 'high';
fD = spm_eeg_ffilter(S);
Python
S = Struct()
S.D = D
S.freq = 10
S.band = 'high'
fD = spm_eeg_ffilter(S)
MATLAB
S = [];
S.D = fD;
S.freq = [70];
S.band = 'low';
fD = spm_eeg_ffilter(S);
Python
S = Struct()
S.D = fD
S.freq = 70
S.band = 'low'
fD = spm_eeg_ffilter(S)