M/EEG preprocessing - SPM Documentation (2024)

In this chapter we will describe the function and syntax of all SPM/MEEGpreprocessing and display functions. This will be the most detaileddescription of the functions in this manual. Our goal is to provide acomprehensive description of how the software can be used to preprocessM/EEG data up to the point where one would use one of the sourcereconstruction techniques or statistical analysis of M/EEG channel data.

These functions can be called either from the MATLAB command line andscripts, or via the batch input system. The batch input system isdesigned for repetitive analyses of data (eg. from multiple subjects) .Once the user becomes familiar with the batch tools necessary for theiranalysis it is very easy to chain them using batch dependencies and runthem as one pipeline. The principles of using the batch tool aredescribed in [Chap:batch:tutorial]. Thecommand line facilities are very useful for writing scripts, or usingSPM’s history-to-script functionality to generate scripts automatically.

For scripts we follow the concept of providing only one input argumentto each function. This input argument is usually a structure (struct)that contains all input arguments as fields. This approach has theadvantage that the input does not need to follow a specific inputargument order. For some arguments default values can be provided. Whenan obligatory argument is missing, this will cause an error.

Below we will describe the parameters available in the batch tool andthe names of the corresponding low-level SPM functions. The interfacefor calling these functions from a script is described in functionheaders.

We will go through the conversion of the data, specifics of the M/EEGformat in SPM, how to properly enter additional information about thechannels, how to call FieldTrip-functions from SPM, a complete referenceof all methods and functions, how to use the display, and finally how toscript and batch the preprocessing.

Conversion of data

The first step of any analysis is the conversion of data from its nativemachine-dependent format to a MATLAB-based, common SPM format. Thisformat stores the data in a *.dat file and all other information in a*.mat file. The *.mat file contains the data structure D and the*.dat is the M/EEG data. The conversion facility of SPM is based onthe “fileio” toolbox1, which is shared between SPM, FieldTrip andEEGLAB toolboxes and jointly developed by the users of these toolboxes.At the moment most common EEG and MEG data formats are supported. Forsome cases, it might be necessary to install additional MATLABtoolboxes. In this case an error message will be displayed with a linkwhere the appropriate toolbox can be downloaded. If your data format isnot recognized by “fileio”, you can extend the “fileio” toolbox andcontribute your code to us. See “fileio” page for details.

After selecting on the Convert from theConvert dropdown menu of the M/EEG GUIyou will be asked (“Define settings?”) to choose whether to define somesettings for the conversion or “just read”. The latter option wasintroduced to enable a simple and convenient conversion of the data withno questions asked. The resulting SPM M/EEG data file can then beexplored with SPM’s reviewing tool to determine the appropriateconversion parameters for the future. If the “just read” option ischosen, SPM will try to convert the whole dataset preserving as muchdata as possible. The other option - “yes” - opens the batch tool forconversion

In either case you will need to select the file to be converted. As arule of thumb, if the dataset consists of several files, the filecontaining the data (which is usually the largest) should be selected.SPM can usually automatically recognize the data format and apply theappropriate conversion routine. However, in some cases there is notenough information in the data file for SPM to recognize the format.This will typically be the case for files with non-specific extensions(*.dat, *.bin, *.eeg, etc). In these cases the header-, and notthe data-, file should be chosen for conversion and if it is recognized,SPM will locate the data file automatically. In some rare casesautomatic recognition is not possible or there are several possiblelow-level readers available for the same format. For these cases thereis an option to force SPM to use a particular low-level reader availablewith the batch tool or in a script (see below).

The other options in the conversion batch are as follows:

  • Reading mode - a file can be read either as continuous or epoched. In the continuous case either the whole file or a contiguous time window can be read. In the epoched case trials should be defined (see ‘Epoching’ below). The advantage of defining trials at conversion is that only the necessary subset of the raw data is converted. This is useful when the trials of interest are only a small subset of the whole recording (e.g. some events recorded during sleep). Note that some datasets do not contain continuous data to begin with. These datasets should usually be converted with the “Epoched” option. There is also a possibility to only convert the header without the data. This can be useful if the information of interest is in the header (e.g. sensor locations).

  • Channel selection - a subset of channels can be selected. There are several options for defining this subset that can be combined: by channel type, by names or using a .mat file containing a list of channel labels. Note that channel selection branch is available in many batch tools and its functionality is the same everywhere.

  • Output filename - the name for the output dataset. Note that here any name can be given whereas in other preprocessing tools the user can only define a prefix to be appended to the existing name (this limitation can be circumvented using the ‘Copy’ tool). By default SPM will append ’spmeeg_ prefix to the raw data file name.

  • Event padding - usually when epoching at conversion only events occurring within trials are included with the trials. This option makes it possible to also include events occurring earlier and later within the specified time window.

  • Block size - this is size of blocks used internally to read large files. Does not usually need to be modified unless you have an old system with memory limitations.

  • Check trial boundaries - SPM will not usually read data as continuous if it is clear from the raw data file that it is not the case and will give an error. In some rare cases this might need to be circumvented (e.g. if truly continuous data are stored in chunks (pseudo-epoched) and SPM does not recognise it automatically).

  • Save original header - the generic fileio interface does not let through all the possible header fields available for specific formats. Sometimes those missing header fields are necessary for particular functionality and this option allows to keep the complete original header as a subfield of the converted header. A particular case where this is useful is processing of continuous head localisation data in CTF MEG system which requires some information from the original header to interpret it.

  • Input data format - this option allows to force a particular low-level reader to convert the data. It is not usually necessary. Power users can find possible values for this field in the code of ft_read_header function.

Converting arbitrary data

It might be the case that your data is not in any standard format but isonly available as an ASCII or Excel file or as a variable in the MATLABworkspace. Then you have two options depending on whether you would bewilling to use a MATLAB script or want to only use the GUI.

‘Prepare’ interface in SPM has an option to convert a variable in theMATLAB workspace to SPM format. Only a few question will be asked todetermine the dimensions of the data and the time axis. The otherinformation (e.g. channel labels) can be provided via the SPM reviewingtool.

If you are willing to write a simple MATLAB script, the moststraightforward way to convert your data would be to create a quitesimple FieldTrip raw data structure (MATLAB struct) and then use SPM’sspm_eeg_ft2spm.m function to convert this structure to SPM dataset.Missing information can then be supplemented using meeg methods andSPM functions.

FieldTrip raw struct must contain the following fields:

  • .trial - cell array of trials containing matrices with identical dimensions (channels \(\times\) time).

  • .time - cell array of time vectors (in sec) - one cell per trial, containing a time vector the same length as the second dimension of the data. For SPM, the time vectors must be identical.

  • .label - cell array of strings, list of channel labels. Same length as the first dimension of the data.

If your data only has one trial (e.g. it is already an average or it israw continuous data) you should only have one cell in .trial and.time fields of the raw struct.

An example script for converting LFP data can be found underman\(\backslash\)examplel_scripts\(\backslash\)spm_eeg_convert_arbitrary_data.m.

As some of third party toolboxes whose format SPM can convert alsosupport converting arbitrary data via GUI (e.g. EEGLAB), it is alsopossible to use one these toolboxes first to build a dataset and thenconvert it to SPM.

The M/EEG SPM format

SPM8 introduced major changes to the initial implementation of M/EEGanalyses in SPM5. The main change was a different data format that usedan object to ensure internal consistency and integrity of the datastructures and provide a consistent interface to the functions usingM/EEG data. The use of the object substantially improved the stabilityand robustness of SPM code. The changes in data format and objectdetails from SPM8 to SPM12 were relatively minor. The aims of thosechanges were to rationalise the internal data structures and objectmethods to remove some ‘historical’ design mistakes and inconsistencies.

SPM M/EEG format consists of two files: header file with extension .matand data file with extension .dat. The header is saved in the mat fileas a struct called ‘D’. Description of the struct fields can be found inthe header of meeg.m . When a dataset is loaded into memory by SPM usingthe spm_eeg_load function (see below) the header is converted to @meegobject and the data are linked to the object using memory mapping sothey are not actually kept in memory unnecessarily. The object can onlybe manipulated using standardized functions (called methods), whichmakes it very hard to introduce any inconsistency into SPM M/EEG data.Also, using methods simplifies internal book-keeping, which makes itmuch easier to program functions operating on the M/EEG object. SPMfunctions only access the header data via the object interface and westrongly encourage the power users to become faimilar with thisinterface and also use it in their own code. Using the object can makeyour code simpler as many operations requiring multiple commands whenworking with the struct directly are already implemented in @meegmethods. When converting from struct to an object an automatic integritycheck is done. Many problems can be fixed on the fly and there will onlybe an error if SPM does not know how to fix a problem. Messages from theautomatic consistency checks will sometimes appear during conversion orother processing steps. They do not usually indicate a problem, unlessan error is generated.

Preparing the data after conversion and specifying batch inputs

SPM does its best to extract information automatically from the variousdata formats. In some cases it can also supplement the converted datasetwith information not directly present in the raw data. For instance, SPMcan recognize common EEG channel setups (extended 1020, Biosemi, EGI)based on channel labels and assigns ‘EEG’ channel type and defaultelectrode locations for these cases. However, there are data types whichare either not yet supported in this way or do not contain sufficientinformation for SPM to make the automatic choices. Also the channellabels do not always correctly describe the actual electrode locationsin an experiment. In these cases, further information needs to besupplied by the user. Reading and linking this additional informationwith the data was the original purpose of the Prepare interface. InSPM12 with removal of interactive GUI elements from all preprocessingfunctions some of those elements were added to ‘Prepare’ so that theusers will be able to prepare inputs for batch tool using interactiveGUI. These tools can be found in the ‘Batch inputs menu’.

‘Prepare’ interface is accessed by selecting Prepare from theConvert drop-down menu in the GUI. A menu (easily overlooked) willappear at the top of SPM’s interactive window. The same functionalitycan also be accessed by pressing “Prepare SPM file” in the SPM M/EEGreviewing tool. Note that in the latest Mac OS versions the menu canappear at the top of the screen when clicking on the interactive windowrather than in the window itself.

In this menu, an SPM M/EEG file can be loaded and saved using the “File”submenu. ‘Load header’ option makes it possible to only load the headerinformation from a raw data file without converting any data. This isuseful to subsequently use this header information (e.g. channel labels)for specifying batch inputs. ‘Import from workspace’ is a basic GUIfunctionality for converting any data to SPM M/EEG format. It will scanthe workspace for any numeric arrays and list them for the user tochoose the right one. It will then ask to choose the number of channelsand trials to correctly identufy the dimensions of the data and also tospecify the time axis by providing the sampling rate and time of thefirst sample (in ms). Finally it will ask the user to name the dataset.Then the dataset will be created and opened in SPM reviewing tool (seebelow) where the rest of the information (e.g. channel labels) can besupplemented.

The ‘Batch inputs’ submenu contains tools to interactively specify andsave some pieces of information that can be then used as inputs todifferent batch tools.
‘Channel selection’ as the name suggests is for making channel lists. Alist of all channels in the dataset is shown and the user can select asubset of them and save in a mat-file. Channel set selection isnecessary in many batch tools and choosing a pre-saved list is aconvenient way of doing it.
‘Trial definition’ tool makes it possible to interactively define trialsbased on the events in the dataset. You will first need to specify thetime window (in ms) to be cut around the triggers and the number ofdifferent conditions you want to have. A list will then pop up, andpresent the found triggers with their type and value entries. These cansometimes look strange, but if you want to run a batch or script to dothe epoching, you have to first find out what the type and value of yourevent of interest are. Fortunately, these tend to be the same overscanning sessions, so that you can batch multi-subject epoching usingthe types and values found in one subject. You also have to come up witha “condition label” for each trial type, which can be anything youchoose. This is the label that SPM will use to indicate the trial typeof a trial at later processing stages. It is possible to use severaltypes of triggers for defining trials with the same label - in the GUI,just select several events using Shift or Ctrl key. Finally, you canspecify a shift for each condition so that the zero time of the trialwill be shifted with respect to the trigger (e.g. to account forprojector delay). When all conditions are specified, you can choose toreview a list of epochs and can edit the list by unselecting some ofthem. Note that for such manual tweaking to work you must define trialson the same dataset that you will later epoch. You can then save thecompleted trial definition.
‘Montage’ menu allows one to specify custom montages. The most genericway to do it is via ‘Custom montage’ option which brings up montageediting GUI. On the left hand side, you will find the montage-matrix,where each row stands for a new channel. This means the labels in theleft column describe the new labels. The old labels are on top, thatmeans, each row contains weights for how the old channels must beweighted to produce new channels in the montage. On the right hand side,you see a graphical representation of the current matrix. The default isthe identity matrix, i.e., the montage will not change anything. Theconcept is very general. For example, if you want to remove channelsfrom the data, just delete the corresponding row from the montagematrix. To re-reference to a particular channel the column for thischannel should be -1 for all rows, except the row corresponding toitself which should be 0, whereas the other channels should have 1 inthe intersection of their column and row (the diagonal of the matrix)and 0 elsewhere. For average reference the matrix should have \((N-1)/N\)(where \(N\) is number of channels) at the diagonal and \(-1/N\) elsewhere.In principle, any montage can be represented this way. The specificationwill only need to be done once for your setup and then you can save themontage and use it routinely. After changing the weights of the matrix,you can visualise the montage by pressing the button in the lower rightbelow the figure.

Simpler way to specify some common montages is via ‘Re-reference’ and‘ROI’ options. ‘Re-reference’ is for rereferencing montage specified bychoosing one or more (possibly all) channels as reference from the EEGchannel list. ‘ROI’ is for averaging across channel groups (e.g.reducing the data to ‘Frontal channels’, ‘Occipital channels’ etc.).
In many cases in SPM the order of the conditions in the file isimportant (for instance in 3D source reconstruction and in DCM). The‘Sort conditions’ functionality makes it possible to change thespecification of the order (without actually changing the data file).Subsequently every time the order of the conditions is important, theorder thereby specified will be used. For instance, if you sortconditions in an epoched file and then average it, the conditions in theaverage file will be ordered as you specified. If you originally definedthe trials by selecting events from a list then the order in which youmade the selection will be preserved. You can see the present order in afile using the condlist method (condlist(D)). The specified order canbe saved in a mat-file and used for batch processing (in batch versionof ‘Prepare’, see below).
The “Channel types” submenu allows reviewing and changing the channeltypes. Use the “Review” option to examine the presently set channeltypes. During conversion, SPM will make an informed guess at thecorrect channel types but this can sometimes go wrong, especiallly forEEG data. To set a particular channel group to some channel type, selectthis type from the menu. A list of all channels will appear. Select thesubset whose type you would like to set. Ctrl and Shift buttons canbe used to refine the selection. Press OK to apply your choice. It isespecially important to correctly specify which are the EEG channels.MEG types are assigned automatically by SPM and cannot be modified usingthe GUI.

The “Sensors” submenu can be used to supply information about the sensorpositions to the file. This information is needed to perform 3D sourcereconstruction and DCM analysis for EEG and MEG data. Sensor positionsfor MEG are extracted from the raw data automatically and are alreadypresent. For EEG, sensor positions are usually measured by a specialdevice (such as Polhemus) and are not part of the dataset. Even if youdo not measure electrode positions routinely in your lab, we recommendto perform at least one initial measurement with the electrode cap youuse and use the result as your standard template. In order for SPM toprovide a meaningful interpretation of the results of sourcereconstruction, it should link the coordinate system in which sensorpositions are originally represented to the coordinate system of astructural MRI image (MNI coordinates). In general to link between twocoordinate systems you will need a set of at least 3 points whosecoordinates are known in both systems. This is a kind of Rosetta stonethat can be used to convert a position of any point from one system tothe other. These points are called “fiducials” and the process ofproviding SPM with all the necessary information to create the Rosettastone for your data is called “coregistration”. The most commonly usedfiducials are the nose bridge and the two pre-auricular points. Thecoordinates of these points for SPM’s standard template image arehard-coded in SPM code. So if you provide the coordinates of thesespecific points with your sensor positions, it will be enough for SPM.If you do not have these fiducials but have other anatomical landmarks(for instance 3 EEG electrodes whose positions can be easily marked on astructural image) it will be possible to use them for coregistration aswell, but that will require additional input from you. In addition, oras a replacement of fiducials a headshape measurement may be used. Thismeasurement is done by an operator moving his digitizer pen around onthe subject’s scalp and generates many more data points than just 3fiducials. EEG sensor and fiducial positions can be added to an SPM fileusing the “Load EEG sensors” menu. There are 3 options:

  • “Assign default” - assigning default sensor positions. If this is possible, it will be done automatically at conversion but this option can be used to revert to default sensor positions after making some changes.

  • “From a *.mat file” - this option is for the kind of files that were used in SPM5 and can also be used for any kind of locations without trying to get them into one of the standard formats. SPM will ask for two files. The sensors file should contain an \(N \times 3\) matrix, where \(N\) is the same as the number of channels whose type is set to “EEG” and the order of the rows matches the order of these channels in the SPM file. The fiducials file should contain a \(K \times 3\) matrix, where \(K\) (usually 3) is the number of fiducials. You will then be asked to provide labels for these fiducials. They should appear in the same order as the rows in the file.

  • “Convert locations file” - this option uses a function from the internal “fileio” toolbox that supports several common formats for EEG channel position specification such as *.sfp and BESA’s *.elp. It can also read Polhemus files from FIL and FCDC. In general Polhemus devices do not have a standard data format so if you are using Polhemus at a different site is is most likely that your Polhemus file will not be recognized by SPM directly. You will need to convert it to another format. An *.sfp file is the easiest to create (for instance in Excel). It is just an ASCII file containing a column of channel labels and 3 columns of cartesian coordinates. Check “fileio” website2 for a complete list of supported formats. The file you are importing can also contain positions of fiducial points or any other named points that do not necessarily correspond to channels. You can also include multiple headshape points with the label “headshape”. The important thing is that there are coordinates for each channel that was assigned “EEG” type.

The fiducials for MEG are automatically loaded from the dataset.However, in some MEG setups the situation is more complicated. Forinstance, it might be convenient to attach the coils marking MEGfiducials to the top of the head, where there are no clear anatomicallandmarks. In this case there should be an additional file measured witha Polhemus-like device that contains the positions of MEG fiducials andsomething that can be linked to a structural image (either anatomicallandmarks or a headshape) in the same coordinate system. The way SPMhandles this situation is in two steps. First, this additional file isconverted into the same coordinate system in which MEG sensors arerepresented and it replaces the original MEG fiducials. At a later stagehaving MEG sensors and fiducials/headshape in the same coordinatesystem, SPM uses the fiducials/headshape for coregistration withstandard MRI template or subject’s own structural image. If you can markthe points where your MEG fiducial coils were located on a structuralimage, the step described below is not necessary. It is also possiblethat the digitizer measurement is stored with the raw data. Then SPMwill read it automatically. Otherwise, the additionalfiducials/headshape file can be loaded using the “Load MEGFiducials/Headshape” menu. The supported formats are the same as forelectrode locations. It is also possible to create a fiducials/headshapeMATLAB struct and store it in a *.mat file. This file will also berecognized by SPM. The struct should be called shape and it shouldcontain the following fields: shape.pnt - a \(K \times 3\) matrix(possibly empty) with headshape points i.e. points that are on thesurface of the head and have no labels, shape.fid.pnt - \(M \times 3\)matrix with fiducial points i.e. points that have labels,shape.fid.label - \(M \times 1\) cell array of strings with the labelsof the points in shape.fid.pnt. As mentioned above, \(M\) should be atleast 3 for the coregistration to work.

If you did not use default 3D positions, after loading the sensorpositions you can perform coregistration of your sensors with SPM’stemplate head model. This initial alignment is helpful to verify thatthe sensor information you supplied were interpreted correctly andshould also be done if you would like to generate a 2D sensor templatebased on your 3D sensor positions (see below). The 2D-coordinates willbe used for displaying the data in a topologically meaningful way. Thisis implemented using the “Coregister” option. For details of how thisoption works see the 3D source reconstruction chapter[Chap:eeg:imaging].

‘Define EEG referencing’ menu makes it possible to specify the originalrecording reference for EEG data. This is necessary for sourcereconstruction and DCM to work correctly. Most commonly the referenceone of the sensors and it can be chosen from the list. It can also be acombination of two sensors (e.g. averaged ears) or average reference,specified by selecting the relevant or all sensors respectively. Itcould be possible to support even more complicated referencing schemes(rarely used in research setting) like double banana. That would requireloading a special montage file where the referencing arrangement isspecified.

The “2D Projection” menu deals with the generation of representative2D-coordinates for the sensors. Note that generating 2D-coordinates isnot obligatory. If the 2D-coordinates are not specified, the sensorswill be, when displaying, presented in a default square grid. Missingout on topographically meaningful 2D-coordinates might be useful whenworking on few channels. The 2D-coordinates are also used for producingscalp-level SPMs in voxel space when converting M/EEG data to images forlater statistical analysis (see below). If you are planning to do 3Dsource reconstruction or DCM, 2D-coordinates are not necessarilyrequired. Also, you can load 2D-coordinates from a file (several examplefiles are available in the EEGtemplates SPM directory). 2D-coordinatescan also be generated by projecting the 3D sensor positions to a plane.This is done automatically when default 3D coordinates can be assigned,and also for MEG. In case of custom EEG sensor positions coregistrationshould be performed first (see above). The resulting 2D-coordinates aredisplayed in SPM’s graphics window. You can modify these projected2D-coordinates manually by adding, deleting and moving sensors. Toselect a sensor, click on its label. The label will change its color togreen. If you then click at a different location, the sensor will bemoved to this position. Note that, at this stage, SPM does not checkwhether there is any correspondence between the labels of thecoordinates and the labels of the channels stored in the SPM file. Whenyou are satisfied with the 2D-coordinates, select “Apply” from the menuand the coordinates will be assigned to EEG or MEG channels according totheir labels. Note that 2D-coordinates cannot be assigned to channels ofother types than M/EEG.

Remember to save the file using “File/Save” after you finished modifyingit using the Prepare interface. Your changes will not be savedautomatically. In case of invoking Prepare from the reviewing tool youshould press the ‘OK’ button that will appear at the bottom left of theinteractive window, and then save the file with the “Save” button of thereviewing tool.

In the rare case that you neither have measured sensor locations, orfiducials, and the supplied standard templates do not work for you, youcan also supply a so-called channel template file, which contains allinformation necessary. However, remember, that if you do not supply any2D-coordinates, you can still use all SPM functions, however, SPM willuse 2D-coordinates laid out in a topographically unmeaningfulrectangular pattern.

A channel template file contains four variables:

Nchannels-The number of channels
Cnames-A cell vector of channel names. Each cell can contain either a string or a cell vector of strings. The latter allows for multiple versions of a given channel name. Case can be ignored, i.e., it doesn’t matter whether channel names are in small or capital letters.
Cpos-A \(2 \times Nchannels\)-matrix of channel coordinates on a 2D plane. In \(x\)- and \(y\)-direction the minimum coordinate must be \(\leq 0.05\) and the maximum coordinate must be \(\geq 0.95\).
Rxy-A factor that determines the ratio of the width of the display plots to their height when displaying the data. Standard is \(1.5\).

Note that the channel template files and 3D coordinate files with labels(such as *.sfp) can contain many more channel labels than your datafile. SPM searches, for each channel in the data, through the labels inthe channel template file. If the labels match, the coordinate is used.

Prepare (batch)

Many of the operations of the ‘Prepare’ tool can be batched. Therelevant batch tool is accessed by selecting ‘Prepare (batch)’ from‘Convert’ menu. One or more tasks can be selected (note that the ordercan matter). The configuration of each task should be clear based on thedescriptions above and will not be describe in detail here.

Integration of SPM and Fieldtrip

The SPM distribution includes the latest version of the FieldTriptoolbox3. FieldTrip is a MATLAB toolbox for MEG and EEG analysis thatis being developed at the Donders Institute for Brain, Cognition andBehaviour at the Radboud University Nijmegen together with collaboratinginstitutes. FieldTrip functions can be used for many kinds of analysiswhich are not supported in SPM proper. However, FieldTrip does not haveextensive graphical user interface and its functionality should beaccessed by writing scripts. Full reference documentation for FieldTripincluding example scripts is available at the FieldTrip website. The SPMdistribution also contains some documentation, contained as helpcomments in FieldTrip functions. These can be found in the directoryexternal\(\backslash\)fieldtrip.

Fieldtrip data structures can be converted to SPM EEG files using thespm_eeg_ft2spm function. SPM M/EEG data, once loaded with the functionspm_eeg_load can be converted to FieldTrip format using the methodsftraw (with syntax D.ftraw or ftraw(D)) and fttimelock (withsyntax D.fttimelock or fttimelock(D)). For SPM time-frequencydatasets fttimelock method converts the data to Fieldtriptime-frequency structure.

Loading data into workspace

If you use the GUI only, there is no need to read this section becausethe functions called by the GUI will read the data automatically.However, if you plan to write scripts and access the data and headerinformation more directly, this section should contain all the necessaryinformation to do so.

An SPM M/EEG file can be read using the spm_eeg_load function. Withoutany arguments a file requester asks for the name of the file. With astring argument \(P\), spm_eeg_load(P) will attempt to read a file withthe name P. The SPM-format stores the binary data in a *.dat file.All header information are stored in a *.mat file. This *.mat filecontains a single struct named D which contains several fields. Whenusing spm_eeg_load, the struct is transformed into an object, and thedata are linked into this object. The linking is done via memory mappingusing file_array objects. Note that the data should always be readusing the routine spm_eeg_load. The memory mapped data can beaddressed like a matrix (see below) which is convenient for accessingthe data in a random access way. However, a word of caution: If youwrite new values to this matrix, the matrix is not only changed in theobject (in memory), but also physically on the hard disk.

The meeg object

This section describes the meeg object and its methods. Thisinformation is intended for power users who would like to write theirown scripts and high level functions integrated with SPM. meeg methodsare functions that operate on an meeg object, loaded withspm_eeg_load. The code for all methods can be found in the @meeg SPMdirectory. Most methods provide some minimalist help text. In thefollowing, we will assume that the object variable is called D and wasloaded by using D = spm_eeg_load;. Methods can be called in two ways,either as standard function call with D as the first input (e.g.chanlabels(D, 1) returns the label of the first channel) or withstruct-like syntax D.chanlabels(1).

Constructor meeg

The meeg method is a constructor. Called without any arguments it willproduce a consistent, but empty object. It is also possible to providedata dimensions as inputs and create a dataset with default labels etc.that can be susbsequently updated using other methods. Most functions inSPM create new datasets in a different, more convenient way usingclone method (see below). In SPM, the constructor is called when astruct has been loaded into memory by spm_eeg_load, and is transformedinto an meeg object. Importantly, the constructor also checks theconsistency of the object.

Array-like interface

The actual M/EEG data are memory mapped and can be accessed directlyusing something like d = D(:,:,1). This command would put the firsttrial over all channels and time points into the variable d. The firstdimension of D is channels, the second peri-stimulus time, and thethird is trials. If the data are time-frequency transformed, there wouldbe four dimensions, where the frequency dimension is squeezed in at thesecond position (i.e., channels/frequencies/time/trials). If you wantedto change the values of the data, you would write something likeD(1,2,3) = 1;, which would change the value of the first channel,second time-point, and third trial to 1.

display

This method will return, in the MATLAB window, some information aboutthe object, e.g., display(D). The same will happen when just writingD in the command line and pressing Enter.

Number methods

These are methods which return the number of something; they count thenumber of channels, etc. For example, to find out how many channels anMEEG object contains, you would use D.nchannels, where \(D\) is theobject. Number functions arenchannels, nfrequencies, nsamples, ntrials. You can also use size(D)to get all the dimensions of the data array at once.

Reading and manipulation of information

There are a large number of methods that can be used to either read orwrite some information. The method name is the same but it depends onthe arguments whether something is read or stored. For example, when youuse the method badchannels, you can either type D.badchannels, whichreturns the indices of all bad channels. You could also changeinformation about specific bad channels, e.g.,D.badchannels([43:55], 1) will flag channels 43 to 55 as bad. Youcould also use D.badchannels([43:55], ones(1,13), i.e. you can eitheruse a scalar to change all channels listed, or supply a 0/1-flag foreach channel. There are other functions which use the same logic. In thefollowing we will list these functions and describe briefly what they dobut won’t go into much detail. We believe that you can work it out usingthe badchannels-example.

selectdata

With this method the data can be indexed using channel labels, times andcondition labels instead of indices which you would usually need to findout in your code. For instanceD.selectdata(’Cz’, [0.1 0.12], ’Oddball’) will return the waveforms ofchannel Cz between 100 and 120 ms in peristimulus time for the condition“Oddball”.

badchannels

Flags/unflags channels as bad.

badtrials

Flags/unflags trials as bad.

chanlabels

This method reads or writes the label of the channels (string). Notethat the channel labels must be unique.

chantype

This method reads or writes the type of a channel (string). Currently,the types recognized by SPM are: “EEG”, “MEG”, “EMG”, “EOG”, or “Other”,but in principle type can be any string.

clone

This is a useful method for creating new datasets by copying the headerinformation from an existing dataset and creating a new blank data file.Optionally the data dimensions can be changed when cloning. This methodis used by SPM preprocessing functions to create new datasets where theprocessed data is written out.

conditions

This method reads or writes the name of the condition of an epoch(string).

events

This method returns the events stored with each trial. Events arerecords of things that happened during the experiment - stimuli,responses, etc. Before a file is epoched all the events are stored withthe only trial and they can be used by the epoching function. For anepoched file SPM stores with each trial the events that occurred withinthat trial or possibly in some time window around it (this is aparameter of the epoching function that can be specified). You can usethis information for your analysis (for instance to sort trials byreaction time). Events are represented by a structure array with thefollowing fields:

  • .type - string (e.g. “front panel trigger”)

  • .value - number or string, can be empty (e.g. “Trig 1”).

  • .time - in seconds in terms of the original file

  • .duration - in seconds (optional)

Note that in order to find out the time of an event in peristimulus timeyou will need additional information provided by “trialonset” method.

fname

This method reads or sets the name of the mat-file, in which theheader information are stored.

fnamedat

This method returns the name of the dat-file, in which the data arestored. Most commonly the dat-file will have the same name as themat-file and will be stored in the same folder. However for some lesscommon uses there is a possibility to link an meeg header to a binarydatafile located elsewhere. (See also link method).

frequencies

If the data has been transformed to time-frequency, this method reads orwrites the frequencies (Hz) of the data.

fsample

This method reads or writes the sampling rate of the data. In SPM, alldata must have the same sampling frequency.

fullfile

Returns the full path to the dataset mat file. This is a shortcut forcommonly used fullfile(D.path, D.fname).

history

This method can read or add to the history of a file. Usually, each timea SPM function (e.g. like converting) does something to a data set, thefunction name and arguments (possibly after collecting them with theGUI) are stored in the history. Effectively, the history is adocumentation of how exactly the data were processed. Of course, thehistory function can also be used to replicate the processing, orgenerate (modifiable) scripts for processing other data in the same way.

montage

This method makes it possible to define online montages to apply lineartransforms to the data without writing it out as a new dataset. See themethod code for more documentation.

path

This method reads or writes the path, under which the mat- anddat-files are stored.

repl

This method returns the number of replications measured for a condition.This method is usually only used on single trial data.

timeonset

This method reads and writes the time of the first sample in a trial inperistimulus time (in seconds). In SPM all trials should have the sametime axis. Therefore there is only one timeonset in a file. Forinstance, if you have a pre-stimulus baseline of 100 ms and the stimuluscomes at time zero, timeonset will be -0.1. In general it is possibleto define the time axis any way you like and there is no requirementthat the stimulus comes at 0 or that there is baseline with negativetimes (which was the case in SPM5).

trialonset

This method should not be confused with the more commonly usedtimeonset (see above). It returns the times of the first sample ofeach trial in the original raw data file time. This information is notalways available to begin with. It may also be invalidated duringprocessing (for instance if you merge two epoched files). When thishappens the information is discarded. For SPM analysis trialonset isnot usually necessary. However it may be useful if you want to relatesomething in your analysis to the timing of your experiment, forinstance create a regressor for GLM analysis of single trials to accountfor fatigue. trialonset is also necessary for interpretation of eventsin epoched files.

transformtype

This method reads and writes the type of the data transform (string).For example, when the data are transformed to a time-frequencyrepresentation, transformtype is set to “TF”. For time data, this is“time”.

type

This method reads and writes the type of the data (string). Currently,this string can be “continuous”, “single”, “evoked”, or “grandmean”.

units

This method reads and writes the units of the measurements (string). Theunits are channel-specific, i.e., each channel can have its own units.

Reading of information

Some methods can only read information but not change them. These are:

condlist

This method returns a list of unique condition labels in the file. Theorder of this list is important as SPM functions rely on it many cases.For instance, when averaging an epoched dataset the conditions in theaveraged file will be in the order of condlist. The order of condlistdoes not have to be the same as physical order of trial on disk and canbe changed (See ‘Sort conditions’ below).

coor2D

This method returns the 2D-coordinates used for displaying or writingsensor data to voxel-based images. These coordinates can also be usefule.g. to find all the frontal channels (y-coordinate above 0.5) or allthe left channels (x-coordinate below 0.5) etc.

ind-methods

This is a group of methods that return indices into the data array basedon labels of the relevant data dimension. These include:

  • indchannel - returns indices given channel labels. Several labels can be provided together as a cell array.

  • indchantype - returns indices given channel types. Several types can be provided together as a cell array. An additional flag ‘GOOD’ or ‘BAD’ can be provided to return only good or bad channels.

  • indfrequency - returns indices given frequencies (for TF datasets).

  • indsample - returns indices given times (in sec).

  • indtrial - returns trial indices given condition labels. Several labels can be provided together as a cell array. An additional flag ‘GOOD’ or ‘BAD’ can be provided to return only good or bad trials.

modality

This method returns the modality of the dataset (MEG, EEG, etc.). Therecan be datasets with multiple modalities and in this case the methodreturns ‘Multimodal’ with a list of modalities as the second output.

time

This method returns the time axis of the dataset (in sec). When givensample indices as input it will return the corresponding times.

sensors

This method returns the sensor locations structure. There is anadditional argument for modality (‘EEG’ or ‘MEG’) as SPM supportsdatasets with more than one sensor type. The exact way sensors arerepresented depends on the modality and you can find more information inFieldtrip documentation as the sensors structure is produced and used bycode originally developed at by the Fieldtrip team. Note that in SPM,sensors are not directly linked with channels, unlike for instance inEEGLAB. So there is no requirement for the number of sensors andchannels to match or even for any relation between them. Of courseloading sensors completely unrelated to your data will not be veryuseful and will eventually lead to an error. This kind of representationis more powerful than a simple correspondence.

fiducials

This method returns the fiducials. They are represented as shapestruct (see the discussion of loading fiducials by the Preparefunction) with an additional field for units that is assignedautomatically.

ftraw

This method converts an object to a FieldTrip structure. Additionalarguments can be provided to only convert a subset of the data.

fttimelock

Similar to ftraw but converts the data to a different kind ofFieldtrip structure.

Manipulations of the data on disk

delete

This function deletes the mat- and dat-files from the disk. This isuseful, for instance, in a script to delete the intermediate datasetsafter the next processing step has been completed.

link

Links a header in the workspace to a binary data file on disk. This isusually done automatically when loading the dataset. The dimensions ofthe datafile should match the header.

unlink

Unlinks the header from the data. This can be useful e.g. for workingwith the header when the datafile is not available.

blank

Creates a new empty datafile matching header dimensions.

move

Renames or moves a dataset

copy

Makes a copy of the dataset.

save

This method saves the object to the mat- and dat-files.

Struct-like interface

In addition to pre-defined internal fields that should only bemanipulated using methods, the meeg object also allows storingadditional information in it as long as the names of additional fieldsdo not clash with the names of existing methods. This functionality isused by some SPM functions. For instance, the results of 3D sourcereconstructions are stored in D.inv field for which no methods arenecessary to access and modify it. You can use this functionality inyour scripts (try commands likeD.myfield = ’hellow world’; disp(D.myfield);). The methods rmfieldand isfield work for these extra-fields as they would if the meegobject was a struct. Several of the methods support the struct-likeinterface functionality: fieldnames, getfield, rmfield, isfield. Thestruct-like interface only allows to access those extra-fields that wereadded using it and not the core fields of the object.

SPM functions

In this section we will describe the high-level SPM functions which areused for preprocessing M/EEG data. These functions are fairly standardand should allow a simple preprocessing of the data (e.g., epoching,filtering, averaging, etc.). Here, we will just describe what eachfunction roughly does and what the batch input arguments mean. Moredetailed information about the syntax for scripts can be found in thehelp text of the code. For example, to get detailed help on epoching,type help spm_eeg_epochs. The general syntax is the same for allfunctions. Input arguments are provided in a struct (by conventioncalled S), whose fields contain the arguments. A typical call, e.g.,from a script would be: D = spm_eeg_epochs(S), where \(S\) is the inputstruct, and D contains the return argument, the epoched meeg object.Note that, with all SPM functions, the object is also always written tohard disk. The filenames of the mat- and dat-files are generated byprepending (by default) a single letter to the old file name. In theexample of epoching this would be an ‘e’. The idea is that by callinga sequence of functions on a file, the list of first letters of the filename shows (roughly) which preprocessing steps were called to producethis file. Note that another way of calling SPM functions and specifyingall input parameters is to use the batch interface.

Epoching the data: spm_eeg_epochs

Epoching cuts out little chunks of continuous data and saves them as“single trials”. In M/EEG research, this is a standard data selectionprocedure to remove long gaps between trials and extract time segmentswith the same time relation to the event of interest. The first input toepoching is a continuous M/EEG dataset. It can be either data in thetime domain or time-frequency data.

The epoching function can deal with three different ways of specifyingtrials (chosen under ‘How to define trials’) . The first way (‘Definetrial’) is to specify trials based on events stored in the dataset. Oneshould define the time window in peristimulus time (which will be thesame for all trials). In addition it is necessary to specify the events(triggers) around which the epochs will be “cut’ . The user can addmultiple entries for all the event types of interest. SPM identifiesevents by their “event type” and “event value”. These are strings ornumbers which the software run by the EEG or MEG vendor uses whengenerating the measurement file. If you don’t know what they are foryour system the interactive GUI in ‘Prepare’ will present the foundtriggers with their type and value entries. These tend to be the sameover scanning sessions, so that you can batch multi-subject epochingusing the types and values found in one subject. You also have to comeup with a “condition label” for each trial type, which can be anythingyou choose. This is the label that SPM will use to indicate the trialtype at later processing stages. It is possible to use several types oftriggers for defining trials with the same label. Using the ‘Shift’parameter it is possible to shift ‘time zero’ of the trial relative tothe original event. This can be useful e.g. to account for knownprojector delay.

The second choice is to load a trial definition file. This file can beproduced by an interactive GUI tool in ‘Prepare’ (under ‘Batchinputs’/’Trial definition’) or by the user’s custom code. Trialdefinition file is a mat-file containing either variables named‘trialdef’ and ‘timewin’ or the variables ‘trl’ and ‘conditionlabels’.‘trialdef’ and ‘timewin’ are analogous to the specification describedabove. trl is a \(N \times 2\) matrix, where each row contains the startand end of a trial (in samples). Optionally, there can be a third columncontaining the offset of the trigger with respect to the trial. Anoffset of 0 (default) means that the first sample of the trialcorresponds to the trigger. A positive offset indicates that the firstsample is later than the trigger, a negative offset indicates that thetrial begins before the trigger. In SPM the offset should be the samefor all trials. The need to specify a whole column is forinteroperability with FieldTrip where trials can have different timeaxes. In addition you have to specify conditionlabels (a single stringor a cell array of strings), either one for each trial or one for alltrials. Using trl and conditionlabels the user can have full controlover the way the data are epoched. So if your conditions are defined ina more complicated was than just based on a single trigger you shouldwrite your own code that will output a file with trl andconditionlabels variables and that file can then be used as input toepoching. When a trial definition is created in ‘Prepare’ GUI both‘trialdef’ and ‘trl’ versions are saved. ‘trl’ takes precedence if themat file is later used to epoch the same dataset on which it was defined(recognised based on the file name). Otherwise ‘trialdef’ will be usedand ‘trl’ - ignored. This makes it possible to define trials using GUIon a single file and then use the same trial definition mat-file onother datasets with the same triggers.

The third trial definition option is only relevant for studies ofsteady-state data (i.e. spectra). It is possible to break the data intoarbitrary segments with length defined by the user.

If the peri-stimulus time starts before zero, the epoched data will bebaseline-corrected by default, i.e. the mean of the pre-stimulus time issubtracted from the whole trial. The baseline correction can be removedif undesirable by setting ‘Baseline correction’ to ‘no’.

The ‘Event padding’ option makes it possible to store with each trialsome events that occur around it within the specified interval. This isuseful e.g. when a response comes long time after a stimulus but needsto be included with the trial e.g. to compute the reaction time at alater stage.

‘Filename Prefix’ option is for specifying the prefix to be added to thedataset name after epoching. The default prepended output letter is‘e’.

Filtering the data: spm_eeg_filter

Continuous or epoched data can be filtered, over time, with a low-,high-, stop- or bandpass-filter. SPM uses a Butterworth filter to dothis. Phase delays are minimised by using MATLAB ‘s filtfilt functionwhich filters the data twice, forwards and backwards. The batchinterface makes it possible to define filter type, band, cutofffrequencies, direction and order. The default prepended output letter is‘f’.

Baseline correction: spm_eeg_bc

This function subtracts the baseline from channel data. You will beasked to specify the baseline period in ms (e.g. [-100 0]). A newdataset will be written out with the name prepended by ‘b’.

Artefact detection and rejection: spm_eeg_artefact

Some trials not only contain neuronal signals of interest, but also alarge amount of signal from other sources like eye movements or muscularactivity. These signal components are referred to as artefacts. Thereare many kinds of artefacts and many methods for detecting them. Theartefact detection function in SPM is, therefore, extendable and canautomatically detect and use plugin functions that implement particulardetection algorithms. Simple algorithms presently implemented includethresholding of the data, thresholding of the difference betweenadjacent samples (to detect jumps), thresholding peak-to-peak amplitudeand detection of flat segments. Channels containing artefacts in largeproportion of the trials are automatically marked as bad.

Note that the function only indicates which trials are artefactual orclean and subsequent processing steps (e.g. averaging) will take thisinformation into account. However, no data is actually removed from the*.dat file. The *.dat file is actually copied over without anychange. The default prepended output letter is ‘a’.

Click on “File name” and select the dataset. Double click “How to lookfor artefacts” and a new branch will appear. It is possible to defineseveral sets of channels to scan and one of the several differentmethods for artefact detection. For each detection method there arespecific configuration parameter (e.g. for thresholding - the thresholdvalue).

Downsampling: spm_eeg_downsample

The data can be downsampled to any sampling rate. This is useful if thedata were acquired at a higher sampling rate than one needs for makinginferences about low-frequency components. For example, resampling from1000 Hz to 200 Hz would cut down the resulting file size to 20% of theoriginal file size. The prepended output letter is ‘d’.

Rereferencing: spm_eeg_montage

Sometimes it is necessary to re-reference the data to a new reference.For sensor level analysis it can be useful to use a reference thatemphasizes the effects of interest. In SPM this is done by specifying aweight matrix, which pre-multiplies the data. This is a general approachwhich allows one to re-reference to the average over channels, to singlechannels, or any linear combination of channels, e.g. the average over apair of channels. The prepended output letter is ‘M’.

The montage function has several ‘modes’ of action which have to do withthe fact that it is possible to use online montages which do notactually change the data on disk but apply the montage on line whenreading the data. M/EEG objects with online montage appear as if themontage has been applied (e.g they have channel labels corresponding tothe post-montage state). The most common mode ‘Write’ does not useonline montage but rather applies montage to the data and generates anew dataset. ‘Switch’ can switch between previously defined montages,‘Add’ can add a montage to the set of montages in the dataset withoutswitching to it and ‘Clear’ removes online montages and returns back tothe original channel set.

A montage is specified by a textttmat-file, which contains a struct with3 fields: labelnew (labels of new channels), labelorg (labels oforiginal channels), and the montage-matrix tra (“tra” as intransform). Montages files can be generated and edited using ‘Prepare’GUI.

Finally, you need to specify whether you want to “keep the otherchannels”. There may be channels that are not involved in the montage.For instance, if you the apply montage defined for your EEG channels butthere are also EOG or trigger channels in the file. If you answer “yes”,they will just be copied to the new file unaffected. If you answer “no”they will not be included in the new file.

Grand mean: spm_eeg_grandmean

The grand mean is usually understood as the average of evoked responsesover subjects. The grand mean function in SPM is typically used to doexactly this, but can also be used to average over multiple EEG files,e.g. multiple sessions of a single subject. There is an option to eitherdo averaging weighted by the number of trials in each file (suitable foraveraging across sessions within a subject) or do unweighted averaging(suitable for averaging across subjects).

You will need to specify the name of the output file.

Merge: spm_eeg_merge

Merging several MEEG files can be useful for concatenating multiplesessions of a single subject. Another use is to merge files and then usethe display tool on the concatenated file to be able to display in thesame graph data coming from different files. This is the preferred wayin SPM to display data together that is split up into several files. Themerged file will be written into the current working directory. Theprepended output letter is ‘c’.

You should specify what to do with condition labels. The simplest optionis to keep them the same. This might be useful for instance when youhave several sessions for one subject with the same conditions in allfiles. In other cases, however, it might be helpful to rename theconditions like “condition A” to something like “condition A, session1”, etc. The simplest way to do it is to append the name of the originalfile to the condition labels. There is also a possibility to specifymore sophisticated ‘recoding rules’ (see the documentation in thefunction header). This is mostly useful for writing scripts.

The function will first check whether there are at least two files, andwhether all data are consistent with each other, i.e., have the samenumber of channels, time points, and sampling rate.

Multimodal fusion: spm_eeg_fuse

SPM supports datasets containing simultaneously recorded MEG and EEG.For imaging source reconstruction it is possible to use both modalitiesto inform the source solution. Usually combined MEG/EEG data iscontained within the same raw dataset and can be pre-processed togetherfrom the beginning. If this is not the case spm_eeg_fuse makes itpossible to combine two datasets with different channels into a singledataset given that the sets of channels do not overlap and the datasetsare identical in the other dimensions (i.e. have the same sampling rateand time axis, the same number of trials and the same condition labelsin the same order). This function can be used to create a multimodaldataset also from separately recorded MEG and EEG which is a valid thingto do in the case an experiment with highly reproducible ERP/ERF.

Cropping: spm_eeg_crop

The ‘Crop’ function can be used to remove part of the data, particularlythe edges of trials. This is useful if the trials were originally madelonger than necessary to absorb edge artefacts like filter ringing andat a later stage of processing the padding can be removed. It is alsopossible to remove frequencies and channels.

Combine planar: spm_eeg_combineplanar

This functionality is specific to MEG systems with planar gradiometers(of which most common is the Neuromag system). It can also be applied toMEG datasets converted to synthetic planar gradient. Planar gradiometerscome in pairs corresponding to two directions of the magnetic field in aplain parallel to the head surface. To interpret the data from thissensors it is convenient to combine them. This can be done for data inthe time domain, in which case RMS is computed or time-frequency data inwhich case the data for the two directions are summed. Note that it isimportant to put the ‘Combine planar’ step in the right place in thepipeline. For instance it would not make sense to filter the combinedplanar data, so filtering must be done first. For time-frequency casethe ‘Combine planar’ step would usually precede the rescaling step. Notealso that combining planar channels is a nonlinear step so thesechannels cannot be used for source reconstruction or DCM.

You should choose whether to replace the original planar channels withcombined, add them in addition to the original ones, replace all MEGchannels with combined planar or only keep combined planar and discardall others.

Data reduction: spm_eeg_reduce

This function can be used to reduce data dimensionality by projectingthe data on a small number of spatial components (e.g. PCA). This is anextendable function where new reduction methods can be added.

Time-frequency decomposition: spm_eeg_tf

The time-frequency decomposition is extendable and can automaticallydetect and use plugin functions that implement particular spectralestimation algorithms. Algorithms presently implemented includecontinuous Morlet wavelet transform, Hilbert transform and multitaperspectral estimation. The result is written to one or two result files,one containing the instantaneous power and the other, optionallywritten, the phase estimates (phase estimation is not possible for allalgorithms). One can select the channels and frequencies for which powerand phase should be estimated. For power, the prepended output lettersare tf_, for phase tph_.

Rescaling and baseline correction of time-frequency: spm_eeg_tf_rescale

Usually raw event-related power is not the most informative thing tolook at (although contrasts of raw power between conditions can beinformative). To see the event-related effects better the power shouldbe either transformed or baseline-corrected separately for eachfrequency. There are several different ways to do this and they areimplemented in spm_eeg_tf_rescale function. ‘LogR’ method firstcomputes the log of power and then baseline-corrects and scales theresult to produce values in dB. ‘Diff’ just does simple baselinesubtraction. ‘Rel’ expresses the power in % of the baseline units.Finally ‘Log’ and ‘Sqrt’ options just compute the respective functionswithout baseline-correction. If necessary, you will need to specify thebaseline period. Optionally the baseline can come from a differentdataset. This can be useful e.g. to baseline correct response-lockeddata using a pre-stimulus baseline.

Averaging over time or frequency: spm_eeg_avgtime, spm_eeg_avgfreq

These functions can be used to average time-frequency data over time orfrequency and save the results as M/EEG datasets. This is useful whensubsequently additional processing steps need to be carried out (e.g.rescaling).

Averaging: spm_eeg_average

Averaging of single trial data is the crucial step to obtain the evokedor induced response. When averaging single trial data, single trials areaveraged within condition. The prepended output letter is ‘m’.

Optionally you can use robust averaging for your data. This approachestimates weights, lying between 0 and 1, that indicate how artefactuala particular sample in a trial is. Later on, when averaging to produceevoked responses, each sample is weighted by this number. For example,if the weight of a sample is close to zero, it doesn’t have muchinfluence in the average, and is effectively treated like an artefact.Ifyou choose robust averaging, you will be given an option to save theweights as a separate dataset which is useful for finding out what partsod the data were downweighted and adjusting the parameters if necessary.Then you should choose whether to compute the weights by condition (asopposed to for all the trials pooled together). When there areapproximately equal numbers of trials in each condition, it is probablysafer to compute weights across all conditions, so as not to introduceartifactual differences between conditions. However, if one conditionhas fewer trials than the others, it is likely to be safer to estimatethe weights separately for each condition, otherwise evoked responses inthe rarer condition will be downweighted so as to become more similar tothe more common condition(s). Finally, you will have to choose an offsetfor the weighting function. This value, default value 3, defines theweighting function used for averaging the data. The value 3 will roughlypreserve 95% of data points drawn randomly from a Gaussian distribution.Robust averaging can be applied to either time or time-frequency data.In the case of time data if you applied a low-pass filter beforeaveraging it is advised to apply it again after averaging becausedifferential weighting of adjacent points may re-introducehigh-frequencies into the data.

For phase data it is possible to compute phase-locking value (a.k.a.inter-trial coherence) instead of averaging the phase.

Contrast over epochs: spm_eeg_contrast

As an extension to the averaging functionality, SPM can also be used tocompute linear combinations of single trials or evoked responses. Forexample, if you want to compute the difference between two evokedresponses, you supply a contrast vector of \([-1; 1]\). Similarly, if youwant to remove some trials from the file, you can do this by using acontrast vector like \([1; 0]\) which would write a new file with only thefirst evoked response. The prepended output letter is ‘w’.

For each contrast, you have to enter a label and a vector of weights ofthe same length as the number of trial types in the file. Note that SPMwill zero-pad this vector if you specify fewer contrast weights than youhave trials. You also need to decide whether to “Weight byreplications”. This is important when you use this function on singletrials, where, typically, you have a different number of trials for eachtrial type. If you then choose to average over multiple trials, thisoption allows you to choose whether you want to form an average that isweighted by the number of measurements within each trial type. The ‘yes’choice is useful when combining multiple conditions into one. The ‘no’choice is useful when computing differences between responses.

Copy: spm_eeg_copy

This function makes it possible to make a copy of a dataset. It won’twork just to copy and rename the files because the name of the data fileis stored in the header file and this should be updated. You will beasked to specify the new dataset name.

Remove bad trials: spm_eeg_remove_bad_trials

This function physically removes trials marked as bad from a dataset.This can be useful, for instance, before time-frequency computation asprocessing bad trials generates a lot of overhead. Also under any othercirc*mstances when it is necessary to remove trials from a dataset (forinstance to get rid of some unused condition) these trials can be firstmarked as bad and then removed using this function.

Displaying data with SPM M/EEG Review

This tool can be called from the main SPM GUI under “Display”\(\rightarrow\) M/EEG.

SPM M/EEG Review is meant to provide theuser with basic visualization (data and source reconstruction) andreviewing (e.g. trial and sensor good/bad status) tools.

When called, SPM M/EEG Review displays inthe SPM graphics window information about the SPM data file which isdisplayed (only for MATLAB versions \(\geq\) 7.4).

SPM M/EEG Review uses tabs to easilyaccess different fields in the SPM data file structure (see relevant SPMmanual section for SPM EEG data format). The main tabs system, at thetop of the graphics windows, offers the following alternatives:

  • EEG displays EEG type data (if any). These are the data associated with “EEG” sensors. The content of this tab is described below, as well as the “MEG” and “OTHER” tabs.

  • MEG displays MEG type data (if any).

  • MPLANAR displays MEG data from planar gradiometers (if any).

  • MCOMB displays RMS MEG data from combined planar gradiometers (if any).

  • OTHER displays any other type of data (e.g. HEOG, VEOG, etc).

  • info (active tab by default): displays basic information about the data file. This tab contains three further sub-tabs4: “channels”, “trials” and “inv” (the latter shows source reconstructions parameters, if any). Some of this info can be changed by the user (e.g. sensor/trial5 type, label and status, etc) by editing the table. The changes become effective when clicking on “update”. They are actually saved in the data file when clicking on “SAVE”.

  • source displays source reconstructions (if any). See below (2- source reconstructions visualization).

In addition, the user can call the SPMPrepare routine 6 or save anymodification in the data file using the top-right buttons “Prepare SPMfile” and “SAVE”.

Data visualization

The graphics window of SPM Review offerstwo modes of data visualization: “scalp” and “standard” (default). Forcontinuous (non-epoched) data, only “standard” mode is enabled. Fortime-frequency data, only “scalp” mode is enabled. For any other type ofdata, the user can switch to any of these modes using the standard/scalpradio button. These two modes are described below:

  • standard channels are displayed vertically, within the same axes. A channel uicontextmenu can be accessed by right clicking on any time series (e.g. for changing the channel good/bad status). An additional axis (bottom right) provides the user with the temporal and horizontal scale of the displayed data). The size of the plotted time window can be changed using the top left buttons 1 and 2. User can scroll through the data using the temporal slider, at the bottom of the graphics window. A global display scaling factor can be changed using the top buttons 3 and 4. Zooming within the data is done by clicking on button 5. Clicking on button 6 displays a 2D scalp projection of the data.

When displaying epoched data, the user can select the trial within the list of accessible trials (top right of the window). It is also possible to switch the status of trials (good/bad) by clicking on button 10.

When displaying continuous data, SPM M/EEG Review allows the user to manage events and selections. After having clicked on button 7, the user is asked to add a new event in the data file, by specifying its temporal bounds (two mouse clicks within the display axes). Basic properties of any events can be accessed either in the “info” table, or by right-clicking on the event marker (vertical line or patch superimposed on the displayed data). This gives access to the event uicontextmenu (e.g. for changing the event label). Buttons 8 and 9 allow the user to scroll through the data from marker to marker (backward and forward in time).

  • scalp channels are displayed vertically, within the same axes. A channel uicontextmenu can be accessed by right clicking on any time series (e.g. for changing the channel good/bad status). An additional axis (bottom right) provides the user with the temporal and horizontal scale of the displayed data). The size of the plotted time window can be changed using the top left buttons 1 and 2. User can scroll through the data using the temporal slider, at the bottom of the graphics window. A global display scaling factor can be changed using the top buttons 3 and 4. Zooming within the data is done by clicking on button 5. Clicking on button 6 displays a 2D scalp projection of the data.

When displaying epoched data, the user can select the trial within the list of accessible trials (top right of the window). It is also possible to switch the status of trials (good/bad) by clicking on button 10.

Source reconstructions visualization

SPM M/EEG Review makes use of sub tabsfor any source reconstruction that has been stored in the data file7.Since these reconstructions are associated with epoched data, the usercan choose the trial he/she wants to display using the list ofaccessible events (top of the main tab). Each sub tab has a label givenby the corresponding source reconstruction comment which is specified bythe user when source reconstructing the data (see relevant section inthe SPM manual). The bottom-left part of each sub tab displays basicinfos about the source reconstruction (date, number of included dipoles,number of temporal modes, etc). The top part of the window displays arendering of the reconstruction on the cortical surface that has beenused. User can scroll through peri-stimulus time by using the temporalslider below the rendered surface. Other sliders allow the user to (i)change the transparency of the surface (left slider) and (ii) thresholdthe colormap (right sliders). In the center, a butterfly plot of thereconstructed intensity of cortical source activity over peri-stimulustime is displayed. If the data file contains more than one sourcereconstruction, the bottom-right part of the window displays a bar graphof the model evidences of each source reconstruction. This provides theuser with a visual Bayesian model comparison tool8. SPM M/EEGReview allows quick and easy switchingbetween different models and trials, for a visual comparison of corticalsource activities.

M/EEG preprocessing - SPM Documentation (1)

Script generation

Another way of batching jobs is by using scripts, written in MATLAB .You can generate these scripts automatically. To do this, you first haveto analyze one data set using the GUI or batch system. Whenever apreprocessing function is called, all the input arguments, once theyhave been assembled by the GUI, are stored in a “history”. This historycan then be used to not only see in detail which functions have beenused on a data set, but also to generate a script that repeats the sameanalysis steps. The big difference is that, this time, no more GUIinteractions are necessary because the script already has all the inputarguments which you gave during the first run. The history of an meegobject can be accessed by D.history.

To generate a script from the history of an SPM MEEG file, open the filein the M/EEG Review facility and selectthe info tab: a history tab is then available that will display allthe history of the file. Clicking the Save asscript button will ask for the filename of the MATLAB script tosave and the list of processing steps to save (default is all but it ispossible to select only a subset of them). This will generate a script,which, when run, repeats the analysis. The script can also be obtainedby directly calling the function spm_eeg_history.

Of course, this script can not only be used to repeat an analysis, butthe script can also be seen as a template that can be re-used for otheranalyses. One needs minimal MATLAB knowledge for these changes. Forexample, you can replace the filenames to preprocess a differentsubject. Or you can change parameters and then re-run the analysis. Wehave prepared an example, using the same example data set, as in theprevious subsection to demonstrate this (see the fileman\(\backslash\)example_scripts\(\backslash\)history_subject1.m).With a script, you could also use object methods directly, e.g. add aline like D=badchannels(D, 23, 1), which flags channel 23 as bad (seealso our example script after the filtering step). To run the examplescript on your computer, you need the data set that you can downloadfrom the SPM webpage (9).

  1. fileio: http://fieldtrip.fcdonders.nl/development/fileio

  2. fileio: http://fieldtrip.fcdonders.nl/dataformat

  3. FieldTrip: http://fieldtrip.fcdonders.nl/

  4. Users can also check sensor coregistration when clicking on“sensor positions”.

  5. Sensor/trial status (good/bad) can also be changed under theEEG/MEG/OTHER tabs, when visualizing trials (sensor: right-clickuicontextmenu ; trials: button 10).

  6. This is part of the SPM EEG preprocessing tools. It mainlyconcerns the coregistration of the sensors onto the normalized SPMspace. See relevant section in the SPM manual.

  7. This concerns any distributed source reconstruction, i.e. alsoincludes imaging DCM analyses, but not ECD reconstructions (so far).

  8. Remember that model evidences \(p(y|m)\) can only be compared forthe same data. Therefore, if the source reconstructions havedifferent time windows, filters, number of temporal modes, etc., thecomparison does not hold. This is why basic information (bottom-leftpart of the window) has to be recalled when comparing models.

  9. http://www.fil.ion.ucl.ac.uk/spm/data/eeg_mmn/

M/EEG preprocessing - SPM Documentation (2024)
Top Articles
Latest Posts
Article information

Author: Twana Towne Ret

Last Updated:

Views: 6008

Rating: 4.3 / 5 (44 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Twana Towne Ret

Birthday: 1994-03-19

Address: Apt. 990 97439 Corwin Motorway, Port Eliseoburgh, NM 99144-2618

Phone: +5958753152963

Job: National Specialist

Hobby: Kayaking, Photography, Skydiving, Embroidery, Leather crafting, Orienteering, Cooking

Introduction: My name is Twana Towne Ret, I am a famous, talented, joyous, perfect, powerful, inquisitive, lovely person who loves writing and wants to share my knowledge and understanding with you.