Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... ·...

67
Scripting BrainVoyager QX from Matlab June 28, 2007

Transcript of Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... ·...

Page 1: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

Scripting BrainVoyager QX from Matlab

June 28, 2007

Page 2: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

2

Page 3: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

Contents

1 Introduction 51.1 Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

1.1.1 Starting BrainVoyager QX from Matlab . . . . . . . . . . . . . 71.1.2 Syntax differences . . . . . . . . . . . . . . . . . . . . . . . . 101.1.3 List of functions . . . . . . . . . . . . . . . . . . . . . . . . . . 11

2 Creating projects 132.1 Creating a functional project (*.fmr) . . . . . . . . . . . . . . . . . . . 132.2 Creating an anatomical project (*.vmr) . . . . . . . . . . . . . . . . . 15

2.2.1 List of functions . . . . . . . . . . . . . . . . . . . . . . . . . . 162.2.2 Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

2.3 Script to filter a VMR in Matlab . . . . . . . . . . . . . . . . . . . . . 202.4 Creating AMR projects . . . . . . . . . . . . . . . . . . . . . . . . . . 22

2.4.1 List of functions . . . . . . . . . . . . . . . . . . . . . . . . . . 222.5 Creating a diffusion weighted project (*.dmr) . . . . . . . . . . . . . . 23

3 Preprocessing functional data 253.1 Slice scan time correction . . . . . . . . . . . . . . . . . . . . . . . . 253.2 Motion correction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

3.2.1 Motion correction . . . . . . . . . . . . . . . . . . . . . . . . . 263.2.2 Motion correction and intrasession alignment . . . . . . . . . 263.2.3 Interpolation differences . . . . . . . . . . . . . . . . . . . . . 27

3.3 Temporal filtering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273.3.1 Linear trend removal . . . . . . . . . . . . . . . . . . . . . . . 273.3.2 High pass filtering . . . . . . . . . . . . . . . . . . . . . . . . 273.3.3 Temporal Gaussian smoothing . . . . . . . . . . . . . . . . . 283.3.4 Spatial smoothing . . . . . . . . . . . . . . . . . . . . . . . . 283.3.5 List of functions . . . . . . . . . . . . . . . . . . . . . . . . . . 28

4 Transformations 294.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294.2 Isovoxelation of anatomical data (*.vmr) . . . . . . . . . . . . . . . . 294.3 Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304.4 Transform anatomical data (*.vmr) to sagittal orientation . . . . . . . 304.5 Transform functional data to a standard space (*.vtc) . . . . . . . . . 31

4.5.1 Script to create multiple VTC files . . . . . . . . . . . . . . . 334.5.2 List of functions . . . . . . . . . . . . . . . . . . . . . . . . . . 374.5.3 More on BrainVoyager transformation (*.trf) files . . . . . . . 384.5.4 Function to write a transformation file . . . . . . . . . . . . . 40

3

Page 4: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

4 CONTENTS

5 Experimental design 435.1 Creating stimulation protocols (*.prt) . . . . . . . . . . . . . . . . . . 435.2 Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445.3 Creating design matrices (*.rtc, *.mdm) . . . . . . . . . . . . . . . . 46

5.3.1 List of functions . . . . . . . . . . . . . . . . . . . . . . . . . . 475.3.2 Script to create a design matrix . . . . . . . . . . . . . . . . . 48

6 Statistical analysis 496.1 Computing General Linear Models (*.glm) . . . . . . . . . . . . . . . 49

6.1.1 Computing a single study GLM . . . . . . . . . . . . . . . . . 496.1.2 Computing a multi study GLM . . . . . . . . . . . . . . . . . . 516.1.3 List of functions . . . . . . . . . . . . . . . . . . . . . . . . . . 52

6.2 Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536.3 Manipulating contrasts (*.ctr) . . . . . . . . . . . . . . . . . . . . . . 54

6.3.1 List of functions . . . . . . . . . . . . . . . . . . . . . . . . . . 556.4 Data-driven analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

6.4.1 Plotting IC parameter values in Matlab . . . . . . . . . . . . . 566.4.2 Validating the IC components . . . . . . . . . . . . . . . . . . 59

7 Surface meshes 617.0.3 List of functions . . . . . . . . . . . . . . . . . . . . . . . . . . 62

7.1 Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

8 Using BVQXtools 65

Page 5: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

Chapter 1

Introduction

The component object model (COM) technology on Windows is since BrainVoy-ager QX 1.9 implemented in its Qt Script for Applications (QSA) module. Thismakes it possible to communicate between other COM-enabled programs andBrainVoyager QX [2] via the scripting commands (1.1).

Figure 1.1: Remote scripting in BrainVoyager QX from matlab

These programs are other COM-enabled programs, like Matlab (The Math-Works, Inc.) or Microsoft Excel. Via the OLE Viewer it is possible to check whichprograms are COM-enabled. First, activate OLE View (see figure 1.2).

Figure 1.2: Activating OLE View

Then, look in the category ’Automation objects’ (see figure 1.3). (Thanks to Dirk

5

Page 6: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

6 CHAPTER 1. INTRODUCTION

Figure 1.3: BrainVoyager QX in the OLE Viewer

Heslenfeld for this contribution).When BrainVoyager QX 1.9 is not installed via the installer, use the command

-regserver to activate the COM interface in BrainVoyager (figure 1.4):

Figure 1.4: Activating the COM interface in BrainVoyager QX

In this case, ensure that there are no spaces in the filename and pathname, orthat the name is provided between double quotes (thanks to Jens Schwarzbach).

Page 7: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

1.1. GETTING STARTED 7

1.1 Getting started

1.1.1 Starting BrainVoyager QX from Matlab

The BrainVoyager QX can be started from Matlab via the simple command

bvqx = actxserver(’BrainVoyagerQX.BrainVoyagerQXInterface.1’)

. BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlabwill request its methods via the COM-interface (see figure 1.5).

Figure 1.5: Matlab requesting the COM-interface to the BrainVoyager scriptingmethods

The items that are accessible via COM are shown as yellow cubes (objects) inthe Matlab Workspace (see figure 1.6).

Figure 1.6: COM and other objects in the Matlab Workspace

Page 8: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

8 CHAPTER 1. INTRODUCTION

We can literally send messages from Matlab to BrainVoyager QX via the PrintToLogfunction of BrainVoyager. The figure 1.7 below shows how easy this is. First, theBrainVoyager QX COM server object is invoked viabvqx = actxserver(’BrainVoyagerQX.BrainVoyagerQXInterface’);.Then, the log tab is sent to the front via bvqx.ShowLogTab;. Now the messagecan be sent via the argument for the function PrintToLog():bvqx.PrintToLog(’Message from Matlab...’).

Figure 1.7: Sending a message from Matlab to the BrainVoyager QX log tab

The methods and properties of an object can be found via the Property Inspec-tor in Matlab (see figures 1.8 and 1.9).

Figure 1.8: Methods of the BrainVoyager QX object in Matlab in the Property In-spector

They can also be obtained in a Workspace object list via the method bvqxfuncs = get(bvqx).If necessary, the BrainVoyager QX window can be resized so that Matlab

and BrainVoyager fit on one screen viabvqx.ResizeWindow(600,700);.

Page 9: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

1.1. GETTING STARTED 9

Figure 1.9: Methods of the VMR project in Matlab in the Property Inspector

Page 10: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

10 CHAPTER 1. INTRODUCTION

1.1.2 Syntax differences

The same principles in QSA should be used when scripting BrainVoyager QX fromMatlab. When using a scripting function, first the name of the object is mentioned,then a ’.’ and then the function of that object: nameObject.functionObject();.So when the BrainVoyager server just is started, only the methods of the BrainVoy-ager QX application object (here ’bvqx’) can be used, for examplebvqx.OpenDocument(’C:/Data/CG_QX_DCM.vmr’);.Once a BrainVoyager FMR, VMR or AMR project is opened, the functions of projectscan be used as well, for example vmrproject.AddCondition(’LVF’);. How-ever, there is one difference between scripting via the BrainVoyager QX ScriptingEditor and BrainVoyager scripting via Matlab, which is that the () are not usedwhen there are no arguments for a function, for examplevmrproject.ClearStimulationProtocol;.

In BrainVoyager QX, several scripting functions return a boolean value trueor false to indicate whether the operation succeeded, for example when creatingprojects or preprocessing FMR files. In Matlab, these values are simply repre-sented by 0 for false and 1 for true.

A script does not need to be executed at once in Matlab, also fragments can beused. In this way one can ’walk through’ a script to see the effect of each of thesteps. Code fragments can be executed by selecting the code, right-clicking withthe mouse and choosing ’Evaluate selection’ (see figure 1.10).

Figure 1.10: Executing a selection of code in Matlab choosing ’Evaluate selection’after right-clicking

Page 11: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

1.1. GETTING STARTED 11

1.1.3 List of functions

Table 1.1: Relevant BrainVoyager QX functionsDescription of function Function in QSA Since

QXUpdate surface window UpdateSurfaceWindow;Make snapshot of surfacewindow

SaveSnapshotOfSurfaceWindow;

Show BrainVoyager QXlog tab

ShowLogTab; 1.4

Send text to log tab PrintToLog( ’message’ ) 1.4Move BrainVoyager QXwindow

MoveWindow; 1.0

Select active project ActiveDocument; 1.0Open project (FMR, VMR,AMR)

OpenDocument( ’name’ ) 1.0

Close project (FMR, VMR,AMR)

Close; 1.0

Set current directory SetCurrentDirectory; 1.0Resize the BrainVoyagerwindow

ResizeWindow( new width, new height ); 1.0

Rename DICOM files indirectory

RenameDicomFilesInDirectory( ’dirname’ ) 1.9

Page 12: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

12 CHAPTER 1. INTRODUCTION

Page 13: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

Chapter 2

Creating projects

In this chapter is shown via examples how to create BrainVoyager QX functional(FMR), anatomical 3D (VMR), anatomical 2D (AMR) and diffusion weighted (DMR)projects.

But first it might be necessary to rename the files, in case they are DICOM.This can be performed with the commandRenameDicomFilesInDirectory( ’dirname’ ). Example use is first to startBrainVoyager QX via: bvqx = actxserver(’BrainVoyagerQX.BrainVoyagerQXInterface’);then to rename the files in a certain directory:bvqx.RenameDicomFilesInDirectory(’C:\Data\Experiment\’); % rename

2.1 Creating a functional project (*.fmr)

For a mosaic functional data project (*.fmr), the following parameters need to beprovided:

1. Filetype Define the file type. fileType = ’DICOM’; or use one of’SIEMENS’, ’GE_I’, ’GE_MR’, ’PHILIPS_REC’, ’ANALYZE’.

2. Name of first file Create a variable with the first file name including the filepath. firstFile = ’C:/Data/0001.dcm’;

3. Number of volumes Specify the number of volumes nrOfVols = 252;

4. Number of volumes to skip Specify the number of volumes that should beskipped var skipVols = 2;

5. Create pseudo AMR Indicate whether a pseudo AMR project should be cre-ated from the first functional volume via true or false.createAMR = true;

6. Number of slices Specify the number of slices. nrSlices = 25;

7. STC prefix Provide an prefix name that will be used for the *.stc slice(s).stcprefix = ’run1-’;

8. Swap In case the raw data are Big Endian, set the ’swapBytes’ parameter totrue. byteswap = false;

13

Page 14: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

14 CHAPTER 2. CREATING PROJECTS

9. Width of mosaic image Indicate the x-resolution of the mosaic image, this isthe size of the concatenated slices (for example 25 slices will be in a squaregrid of 5 x 5. When the x-resolution of a single file is 64, the x-resolution forthe mosaic image is 5 x 64 = 320. The size is also visible in the ’Rows’ and’Columns’ of the Info tab when creating a project via the user interface.

10. Height of mosaic image Indicate the y-resolution of the mosaic image.

11. Number of bytes per pixel Insert the number of bytes per pixel of the data.For functional data, the number of bytes is usually 2 (short integer, 16 bits).bytesperpixel = 2;

12. Directory to save the data Provide the name of the path where the files shouldbe saved. savingDir = "C:/Data/";

13. Number of volumes in mosaic image Enter the number of volumes in a mo-saic image.

14. Image width The x-resolution parameter should describe the width of theimage. sizeX = 64;

15. Image height The y-resolution parameter should describe the height of theimage. sizeY = 64;

Please note that the order of the parameters is different when the data arenon-mosaic (see the examples below).

Non-mosaicfmr = BrainVoyagerQX.CreateProjectFMR(fileType, fmrname, nrOfVols,...

skipVols, createAMR, nrSlices,...stcprefix,byteswap, sizeX, sizeY, bytesperpixel);

Mosaicfmr = BrainVoyagerQX.CreateProjectMosaicFMR(fileType, fmrname, nrOfVols,...

skipVols, createAMR, nrSlices,...stcprefix, byteswap, mosaicSizeX, mosaicSizeY, bytesperpixel,...targetfolder, nrVolsInImg, sizeX, sizeY);,...

For the BrainVoyager QX sample data used for the Getting Started Guide 2.5,the command would be:

fmr = bvqx.CreateProjectMosaicFMR( ’DICOM’,...’C:/Data/Experiment/BetSog_20040312_Goebel_C2 -0003-0036-00876.dcm’,...252, 2, true, 25, ’ObjectsExperiment-’, false, 320, 320, 2,...

’C:/Data/Experiment’, 1, 64, 64 );

Save the project via fmr.SaveAs(’ObjectsExperiment.fmr’);.

Page 15: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

2.2. CREATING AN ANATOMICAL PROJECT (*.VMR) 15

Table 2.1: FMR filesDescription of function Function in QSA Since

QXCreate project from rawdata

CreateProjectFMR( arguments ) 1.0

CreateProjectMosaicFMR( arguments ) 1.0CreateProjectFMRSlicesTimeLooping( argu-ments )

1.6

Link AMR LinkAMR( argument ) 1.6Link PRT LinkStimulationProtocol( argument ) 1.3Get data TR (property)

InterSliceTime (property)NrOfVolumes (property)PixelSizeOfSliceDimX (property)PixelSizeOfSliceDimY (property)SliceThickness (property)GapThickness (property)VoxelResolutionVerified (property)TimeResolutionVerified (property)FileNameOfPreprocessdFMR (property) 1.0

2.2 Creating an anatomical project (*.vmr)

Scripting a VMR project is relatively straightforward, if the parameters are known.The function CreateProjectVMR() only requires 7 parameters:

1. The filetype, which is one of ’DICOM’, ’SIEMENS’, ’GE_I’, ’GE_MR’,’PHILIPS_REC’ or ’ANALYZE’.2. The first file name, including path.3. A boolean value true or false indicating whether the data need to be swapped.4. The number of slices.5. The size of the image on the x-axis.6. The size of the image on the y-axis.7. The number of bytes per pixel. For anatomical data, this likely to be 1 or 2 bytes.

The function returns a VMR project object (see figure 2.1).

Figure 2.1: The VMR project object

Page 16: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

16 CHAPTER 2. CREATING PROJECTS

2.2.1 List of functions

Table 2.2: VMR filesDescription of function Function in QSA Since

QXCreate project from rawdata

CreateProjectVMR() 1.0

Isovoxelate AutoTransformToIsovoxel() 1.6Transform to sagittal ori-entation

AutoTransformToSag() 1.6

Get header information TR (property) 1.0InterSliceTime (property)NrOfVolumes (property)PixelSizeOfSliceDimX (property)PixelSizeOfSliceDimY (property)InterSliceTime (property)SliceThickness (property)GapThickness (property)VoxelResolutionVerified (property)TimeResolutionVerified (property)

Get data GetVoxelIntensity()SetVoxelIntensity() 1.0

Page 17: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

2.2. CREATING AN ANATOMICAL PROJECT (*.VMR) 17

2.2.2 Scripts

Script to create a VMR project via Matlab dialogs%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% create_vmrproject_via_interface.m% Script to create a BrainVoyager VMR project in Matlab% Works with BrainVoyager QX 1.9%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

bvqx = actxserver(’BrainVoyagerQX.BrainVoyagerQXInterface.1’)h = msgbox(’Please select the first file of the raw data set’, ’Create VMR project’);% Seefigure 2.2uiwait(h);cancel = 0;

Figure 2.2: Announcement at beginning of script

% get first file % See figure 2.3[filename, pathname] = uigetfile( ...

{’*.dcm; *.IMA; *.I; *.MR; *.REC;*.hdr’,’Raw data files (*.dcm,*.IMA,*.I, *.MR, *.REC,*.hdr)’;’*.dcm’, ’DICOM files (*.dcm)’; ...

’*.IMA’,’Siemens DICOM files (*.IMA)’; ...’*.I’,’GE I files (*.I)’; ...’*.MR’,’GE MR (*.MR)’; ...’*.REC’,’Philips files (*.REC)’; ...’*.hdr’,’Analyze (*.hdr)’}, ...

’Please select the first file’);

Figure 2.3: Select the first file

firstfilename = strcat(pathname, filename);[pathstr,name,ext,versn] = fileparts(firstfilename);switch ext

case ’.dcm’, filetype = ’DICOM’case ’.IMA’, filetype = ’SIEMENS’case ’.I’, filetype = ’GE_I’case ’.MR’, filetype = ’GE_MR’case ’.REC’, filetype = ’PHILIPS_REC’case ’.hdr’, filetype = ’ANALYZE’otherwise cancel = 1

end

if ˜cancel% get parameters

if (strcmp(ext, ’.dcm’) == 1) && (exist(’dicominfo.m’) > 0)dcminfo = dicominfo(firstfilename);bytesperpixel = (dcminfo.BitsAllocated/8);xres = dcminfo.Columns;yres = dcminfo.Rows;

Page 18: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

18 CHAPTER 2. CREATING PROJECTS

elseprompt = {’Size of x-axis:’,’Size of y-axis:’, ’Number of bytes per pixel:’}; %

See figure 2.4dlgtitle = ’Parameters for VMR project’;nrlines = 1;def = {’256’,’256’, ’2’};answer = inputdlg(prompt,dlgtitle,nrlines,def);xres = answer{1};yres = answer{2};bytesperpixel = answer{3};

end

Figure 2.4: Enter parameters

button = questdlg(’Are there only raw data files for a VMR project in this directory?’,...%See figure 2.5

Figure 2.5: Enter the number of slices

’Create VMR script’,’Yes’,’No’,’Yes’);if strcmp(button,’Yes’)

rawfileselection = [pathname [’*’ ext]];files = dir(rawfileselection);sizeAr = size(files);nrslices = sizeAr(1);

elseanswer = inputdlg(’Please enter the number of slices’); % See figure 2.6nrslices = answer{1};

end

Figure 2.6: Enter the number of slices

button = questdlg(’Swap data?’, ’Create VMR script’,’Yes’,’No’,’No’); % See figure2.7

if strcmp(button,’Yes’), swap = 1; else swap = 0; end;

vmrproject = bvqx.CreateProjectVMR(filetype, firstfilename, nrslices, swap, xres, yres, bytesperpixel);success = vmrproject.SaveAs(fullfile(pathname, [name ’.vmr’]));

end

Page 19: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

2.2. CREATING AN ANATOMICAL PROJECT (*.VMR) 19

Figure 2.7: Question whether swapping is necessary

Script to display a VMR file in MatlabBelow a (slightly slow) script to use the GetVoxelIntensity(x,y,z) func-

tion. For a faster alternative, use the BVQXTools to read binary BrainVoyager filesin Matlab (please see chapter 8).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% display_vmr_in_matlab.m% Script to display a BrainVoyager VMR project in Matlab% Warning: executing this script can last more than half an hour!% Works with BrainVoyager QX 1.9%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

bvqx = actxserver(’BrainVoyagerQX.BrainVoyagerQXInterface’);[FileName,PathName] = uigetfile(’*.vmr’,’Please select a VMR file’);vmrfilename = [PathName FileName];vmr = bvqx.OpenDocument(vmrfilename);bvqx.PrintToLog(’Transforming image in Matlab...’);for k = 1:vmr.DimZ

for j = 1:vmr.DimYfor i = 1:vmr.DimX

vmrdata(i,j,k) = vmr.GetVoxelIntensity(i,j,k);end

endend

figure;

h1 = subplot(1,3,1); imagesc(resvmr(:,:,100)); title(’sagittal view’); axis image xy off

h2 = subplot(1,3,2); imagesc(squeeze(resvmr(:,100,:))); title(’axial view’); axis image xy off

h3 = subplot(1,3,3); imagesc(squeeze(resvmr(100,:,:))); title(’coronal view’); axis image xy off

colormap gray

Page 20: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

20 CHAPTER 2. CREATING PROJECTS

2.3 Script to filter a VMR in Matlab

This script applies a Laplacian of a Gaussian, a Sobel (approximating a gradient)or a Canny filter on a VMR project and displays it in BrainVoyager QX.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% filter_vmr_in_matlab.m% Script to filter a BrainVoyager VMR project in Matlab%% Works with BrainVoyager QX 1.9 and VMR versions higher than 1.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

[FileName,PathName] = uigetfile(’*.vmr’,’Please select a VMR file’);vmrfilename = [PathName FileName];fid = fopen(vmrfilename, ’rb’);version = fread(fid, [1 1], ’uint16’);dimx = fread(fid, [1 1], ’uint16’);dimy = fread(fid, [1 1], ’uint16’);dimz = fread(fid, [1 1], ’uint16’);data = fread(fid, [1 dimx*dimy*dimz], ’uchar’);rest = fread(fid);fclose(fid);vmrdata = reshape(data, dimx, dimy, dimz);

% H = FSPECIAL(’log’,HSIZE,SIGMA) returns a rotationally symmetric% Laplacian of Gaussian filter of size HSIZE with standard deviation% SIGMA (positive). HSIZE can be a vector specifying the number of rows% and columns in H or a scalar, in which case H is a square matrix.% The default HSIZE is [5 5], the default SIGMA is 0.5.

% show filters %(see figure 2.8)figure;img = vmrdata(:,:,floor(dimx/2));img = rot90(img, 3);subplot(2,2,1);imagesc(img);title(’Original Image’);H = fspecial(’log’,[5 5],.5);Laplacian = imfilter(img,H);subplot(2,2,2);imagesc(Laplacian);title(’Laplacian of Gaussian filter’);cannyimg = edge(img,’canny’,.15);subplot(2,2,3);imagesc(cannyimg);title(’Canny filter (0.15)’);H = fspecial(’sobel’);sobelimg = imfilter(img,H);subplot(2,2,4);imagesc(sobelimg);title(’Sobel filter’);colormap gray;

filterlist = {’Laplacian’, ’Canny’, ’Sobel’}; %(see figure 2.9)[filter,ok] = listdlg(’PromptString’,’Select a filter:’,...’SelectionMode’,’single’,...’Name’, ’Filter VMR’,...’ListString’,filterlist);

H_log = fspecial(’log’,[5 5],.5);H_sobel = fspecial(’sobel’);

if filter == 2 %(see figure 2.10)prompt = {’Enter canny filter value:’};

dlg_title = ’Filter VMR’;num_lines= 1;def = {’0.15’};answer = inputdlg(prompt,dlg_title,num_lines,def);filterval = answer{1};

end

% apply filter and write image[pathstr,name,ext,versn] = fileparts(vmrfilename);filteredimgname = fullfile(pathstr, [name ’_filtered’ ext]);if ok == 1

% write VMR headerfid = fopen(filteredimgname,’w’);fwrite(fid,version,’ushort’);fwrite(fid,dimx,’ushort’);fwrite(fid,dimy,’ushort’);fwrite(fid,dimz,’ushort’);% write VMR image volumefor slicenr=1:len(3)

img = vmrdata(:,:,slicenr);if filter==1

filteredimg = imfilter(img,H_log);elseif filter ==3

Page 21: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

2.3. SCRIPT TO FILTER A VMR IN MATLAB 21

filteredimg = imfilter(img, H_sobel);elseif filter == 2

filteredimg = edge(img,’canny’,filterval);else

break;endfwrite(fid,filteredimg,’uchar’);

end% write rest of VMR headerfwrite(fid,rest);fclose(fid);

end

% show in BrainVoyager QX

bvqx = actxserver(’BrainVoyagerQX.BrainVoyagerQXInterface’);

filteredvmr = bvqx.OpenDocument(filteredimgname);

bvqx.ShowLogTab;

bvqx.PrintToLog([’Filter: ’ filterlist{filter}]);

Figure 2.8: Show filters

Figure 2.9: Select filter dialog

Page 22: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

22 CHAPTER 2. CREATING PROJECTS

Figure 2.10: Enter canny filter value

2.4 Creating AMR projects

2.4.1 List of functions

Table 2.3: AMR filesDescription of function Function in QSA Since

QXCreate project from rawdata

CreateProjectAMR() 1.0

Page 23: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

2.5. CREATING A DIFFUSION WEIGHTED PROJECT (*.DMR) 23

2.5 Creating a diffusion weighted project (*.dmr)

Diffusion weighted data can be treated in the same fashion as anatomical andfunctional data, via the creation of a BrainVoyager QX project.

Table 2.4: DMR filesDescription of function Function in QSA Since

QXCreate project from rawdata

CreateProjectDMR() 1.9

CreateProjectMosaicDMR() 1.9Link AMR LinkAMR() 1.6Get data TR (property)

InterSliceTime (property)NrOfVolumes (property)PixelSizeOfSliceDimX (property)PixelSizeOfSliceDimY (property)SliceThickness (property)GapThickness (property)VoxelResolutionVerified (property)TimeResolutionVerified (property)

Page 24: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

24 CHAPTER 2. CREATING PROJECTS

Page 25: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

Chapter 3

Preprocessing functional data

In this section will be described how to preprocess functional data in BrainVoyagerfrom Matlab.

3.1 Slice scan time correction

The slice scan time correction method accepts two parameters, which are the sliceorder and the type of interpolation.

The slice order parameter can have the following values:

Table 3.1: Slice order optionsSlice order ValueAscending 0Ascending interleaved 1Ascending interleaved 2 2Descending 10Descending interleaved 11Descending interleaved 2 12

The interpolation can have the following values:

Table 3.2: Interpolation optionsInterpolation type ValueTrilinear 0Sinc 1

Perform the slice scan time correction from Matlab viasuccess = fmr.CorrectSliceTiming(1, 0);

Obtain the name of the slice scan time corrected project vianewfmrname = fmr.FileNameOfPreprocessdFMR;.

25

Page 26: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

26 CHAPTER 3. PREPROCESSING FUNCTIONAL DATA

Close the non-preprocessed FMR viafmr.Close;.

Open the slice scan time corrected project vianewfmr = fmr.OpenDocument(newfmrname);

3.2 Motion correction

3.2.1 Motion correction

In BrainVoyager QX, there are two methods to perform motion correction withinone run. These areCorrectMotion() and CorrectMotionEx(). In the latter method, the numberof parameters that can be used for the motion correction is extended.

If multiple runs are performed in one session, the run closest to the 3D scanwould be corrected by using the single-run version: CorrectMotion(int TargetVolume),i.e. with a value of 1 for the parameter TargetVolume. All subsequent runs wouldthen be corrected by specifying the name of the first run as target as well as thesame volume as specified for the first run. This ensures that all volumes of all runsare aligned to the same target volume.

If CorrectMotion( <target volume nr> ) is used, the applied methodis trilinear detection and sinc interpolation. This can be inspected in the *_3DMC.logfile. This can also be seen from the resulting filename, containing ’3DMCTS’,where the ’T’ stands for trilinear detection and the ’S’ for sinc interpolation.The full data set will be used, and the default number of iterations is set (100). Noextended log file is created.

In the version with extended parameters, the parameters are the following:CorrectMotionEx(Target volume (number), Interpolation method (0 or 1),...Full data set (true or false), Max nr of iterations (number),...

movies (true or false), log (true or false));(Replace the names by real parameters and remove spaces in the names).

3.2.2 Motion correction and intrasession alignment

To combine motion correction with intra-session alignment, the methodsCorrectMotionTargetVolumeInOtherRun() andCorrectMotionTargetVolumeInOtherRunEx() are available.

The CorrectMotionTargetVolumeInOtherRun(filename, volume) ac-cepts the following 2 parameters:

1. target fmr file name

2. target volume number

When this function is applied, a reduced data set will be used, and the defaultnumber of iterations is set (100). No extended log file is created.

Its use can be illustrated in the following way:success = fmr2.CorrectMotionTargetVolumeInOtherRun(’C:\Data\Experiment\ObjectsExperiment.fmr’, 1); TheCorrectMotionTargetVolumeInOtherRunEx() accepts the following 7 pa-rameters:

1. target fmr file name

2. target volume number usually the first volume, so 1.

3. interpolation method use 1: trilinear

Page 27: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

3.3. TEMPORAL FILTERING 27

4. use full data set if 1: yes, if 0: no

5. maximum number of iterations this determines how often the estimates shouldbe changed in order to find the values for the rotation and translation param-eters; in the BrainVoyager QX user interface, this value is default set to 100.

6. create movies these *.avi files cannot be generated yet, so the parametercan be set to 0.

7. create extended log file this is very useful. if 1: yes, if 0: no.

These parameters are the same as for CorrectMotionEx() method except forthe extraTargetFMRFileName parameter used here.

3.2.3 Interpolation differences

When invoking CorrectMotion(), the trilinear detection and windowed sinc func-tion for correction is used. When using CorrectMotionEx(), the trilinear detec-tion and correction is applied. This is also the case for the motion correction func-tions including intra session alignment, c.q. CorrectMotionTargetVolumeInOtherRun()and CorrectMotionTargetVolumeInOtherRunEx().

The applied interpolation methods are reflected in the resulting FMR filename.The ’T’ means just trilinear for both detection and correction. The characters ’TS’are used in the FMR filename for trilinear detection with sinc (windowed) correction.

3.3 Temporal filtering

3.3.1 Linear trend removal

Linear trend removal is automatically included when applying high pass filtering tothe data. In case it should be applied independently,success = newfmr.LinearTrendRemoval;can be used.

3.3.2 High pass filtering

The high pass filter is applied in the frequency domain. The temporal high-passfilter can be specified in cycles or in Hz.When it is specified in cycles, is this relative to the number of time points specifiedin the functional data, i.e. length of the time series.

When the units are specified in Hz, it is in signal intensity changes per Hz, forexample:

success = newfmr.TemporalHighPassFilter(0.115385, ’Hz’);

The units in Hertz can be computed from the cycles per time course via: num-ber of cycles / number of data points.

Page 28: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

28 CHAPTER 3. PREPROCESSING FUNCTIONAL DATA

3.3.3 Temporal Gaussian smoothing

Temporal Gaussian smoothing in FMR projects can be applied by specifying thewidth of the smoothing kernel in seconds (’s’) or in TR (’TR’), for example:

newfmr.TemporalGaussianSmoothing(20, ’s’);

3.3.4 Spatial smoothing

Specification of the smoothing kernel for the FMR project is possible up to twodecimals. When more values are specified, they will be rounded (1.06667 pixelsround to 1.07). The units can be specified in pixels, ’px’ or millimeters, ’mm’:

newfmr.SpatialGaussianSmoothing(4, ’mm’);andnewfmr.SpatialGaussianSmoothing(1.06667, ’px’);

The resulting files will be placed in the same folder as the source files. Thefilenames will contain the _SD3DSS appendix.

3.3.5 List of functions

Table 3.3: Preprocessing of FMR filesDescription of function Function in QSA SinceGet new file name FileNameOfPreprocessdFMR (property) 1.0Slice time correction CorrectSliceTiming() 1.5Motion correction and in-tra session alignment

CorrectMotion()

CorrectMotionEx() 1.0CorrectMotionTargetVolumeInOtherRun()CorrectMotionTargetVolumeInOtherRunEx() 1.2

Low pass filter/smooth TemporalGaussianSmoothing() 1.0SpatialGaussianSmoothingHigh pass filter TemporalHighPassFilter()

LinearTrendRemoval() 1.0

Page 29: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

Chapter 4

Transformations

4.1 Introduction

Several transformations in BrainVoyager QX can be scripted. For anatomical data,these are the transformation to isotropic voxels and the reorientation to sagittal.For functional data, these are the transformation to *.vtc file scripting functions;this is discussed in section 4.5.

It is also possible to write a transformation file in Matlab and apply the transfor-mation in BrainVoyager QX. This will be shown in section 4.5.3.

4.2 Isovoxelation of anatomical data (*.vmr)

VMR files can be automatically transformed to isovoxel size of 1x1x1 mm via thefunctionAutoTransformToIsoVoxel(<interpolation method>, <new vmr name>).The resulting VMR is written to disk. The function returns a boolean value (true orfalse) to indicate whether the transformation succeeded. The transformation matrixis also displayed in the BrainVoyager QX Log tab.

29

Page 30: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

30 CHAPTER 4. TRANSFORMATIONS

4.3 Scripts

The function below presents a file dialog to select a VMR file, opens this VMR filein the BrainVoyager QX main window, transforms the VMR file and saves it on diskin the same directory as the original VMR file with the name “isovoxel.vmr”.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% isovoxel_vmr.m% Script to make a VMR isovoxel%% Works with BrainVoyager QX 1.9%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

bvqx = actxserver(’BrainVoyagerQX.BrainVoyagerQXInterface.1’);

bvqx.ShowLogTab;

[FileName,PathName] = uigetfile(’*.vmr’,’Please select the anatomical data file...’);

vmrfilename = strcat(PathName, FileName);

vmrproject = bvqx.OpenDocument(vmrfilename);

bvqx.PrintToLog(’Start isovoxelating VMR...’);

[pathstr,name,ext,versn] = fileparts(vmrfilename);

isovmrfilename = fullfile(pathstr, [name ’_ISO’ ext]);

success = vmrproject.AutoTransformToIsoVoxel(1, isovmrfilename);

bvqx.PrintToLog([’Saving ’ isovmrfilename ’...’]);

isoproject = bvqx.OpenDocument(isovmrfilename); %see figure 4.1

h = msgbox([’The isovoxel file can be found at ’ isovmrfilename]);

uiwait(h);

Figure 4.1: Isovoxel VMR

4.4 Transform anatomical data (*.vmr) to sagittal ori-entation

Page 31: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

4.5. TRANSFORM FUNCTIONAL DATA TO A STANDARD SPACE (*.VTC) 31

4.5 Transform functional data to a standard space (*.vtc)

The functions CreateVTCInVMRSpace(), CreateVTCInACPCSpace() andCreateVTCInTALSpace() will transform the time series in slices (*.stc) to timeseries in volumes so that the functional data are aligned to the anatomical data inone of the native (VMR), AC-PC aligned (ACPC) or Talairach space (TAL) coordi-nate spaces.To invoke these functions, BrainVoyager QX needs to be provided with the same in-formation as it would have when creating VTCs via the user interface. The creationof VTC files can be performed from Matlab in the following steps:

1. Start the BrainVoyager QX server

2. Open an anatomical file (*.vmr)

3. Collect the parameters to provide to the CreateVTC...() function Theseare the parameters:

• Name of FMR project This is the name of the functional data (*.fmr) thatshould be transformed to a VTC file.

• Name of initial alignment file This is the name of the initial alignment file(*IA.trf); the matrix in this file represents the largest part of the mappingfrom the anatomical to the functional data.

• Name of fine alignment file This is the name of the fine alignment file(*FA.trf); the matrix in this file represents additional small changes forthe mapping of the anatomical to the functional data.

• Name of AC-PC alignment file This is the name of the file that trans-forms the data from native space to a space where data are aligned tothe plane of the anterior commissure (AC) and the posterior commissure(PC). This argument only needs to be provided in case the functionsCreateVTCInACPCSpace() and CreateVTCInTALSpace() are in-voked.

• Name of Talairach landmarks file This file contains the coordinates ofthe 12 landmarks that are used to transform the data from AC-PC spaceto Talairach space. This argument only needs to be provided in case thefunction CreateVTCInTALSpace() is invoked.

• Resolution The value of this parameter defines whether the VTC file willhave a resolution of 3mm3, 2mm3 or 1mm3.

• Interpolation This numeric value indicates the interpolation method. Cur-rently the value should be set to 1, which means ’trilinear interpolation’.In future, more interpolation methods will be available for this function.

• Bounding box threshold This value is only relevant in case the VTC isnot created in Talairach space; however, the value should always be pro-vided. The default is 100. The value represents the intensity thresholdon basis of which the size of the VTC box is determined.

4. Set the extended Talairach parameter This is a property of the VMR project,and should also be set in case the VTC will not be in Talairach space.

5. Invoke the CreateVTC...() function

In the following script is shown how to create multiple VTC files. To use thescript, first open the script create_multiple_vtcs.m in Matlab (see figure 4.2).

Page 32: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

32 CHAPTER 4. TRANSFORMATIONS

Figure 4.2: Open the script in Matlab

Figure 4.3: Starting the Matlab script by clicking ’run’

Page 33: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

4.5. TRANSFORM FUNCTIONAL DATA TO A STANDARD SPACE (*.VTC) 33

When the script is opened in Matlab, press ’run’ to start the script (see figure4.3).

If the script is not located in the current directory, a question will appear whetherto change the current directory. Select the option “Add the directory to the top ofthe Matlab path” (see figure 4.4).

Figure 4.4: Changing the current directory by adding the path of the script

4.5.1 Script to create multiple VTC files%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% create_multiple_vtcs.m% Script to create multiple volume time course files (*.vtc)% For use: load in Matlab and press ’run’.%(see figure 4.3)%% Works with BrainVoyager QX 1.9%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

h = msgbox([’Via this script will be multiple VTCs created. Please first define all parameters...’])%(seefigure 4.5) uiwait(h);

bvqx = actxserver(’BrainVoyagerQX.BrainVoyagerQXInterface.1’);bvqx.ShowLogTab;loadparams = questdlg(’Would you like to load VTC parameters (from earlier use of this script)?’,...’Create multiple VTCs’);if strcmp(loadparams, ’Yes’) == 1

[FileName,PathName] = uigetfile(’*.mat’, ’Please select the VTC parameters file ’);load([PathName FileName]);

elseanswer = inputdlg(’Please enter the number of projects...’,’Create multiple VTCs’,...

1);%(see figure 4.6)if isnumeric(str2num(answer{1})) && str2num(answer{1}) > 0

nrofprojects = str2num(answer{1});end

% create cell arrays to store the vtc parametersfmr_names = cell(nrofprojects, 1);ia_names = cell(nrofprojects, 1);fa_names = cell(nrofprojects, 1);acpc_names = cell(nrofprojects, 1);tal_names = cell(nrofprojects, 1);vtc_names = cell(nrofprojects, 1);

vtcspaces = {’native’, ’acpc’, ’talairach’};%(see figure 4.7)[space,v] = listdlg(’PromptString’,’select the target space:’,...

’SelectionMode’,’single’,...’Name’, ’Create multiple VTCs’,...’ListSize’, [200 160],...’ListString’, vtcspaces)

for i=1:nrofprojects

[FileName,PathName] = uigetfile(’*.fmr’,...[’Please select FMR file ’ num2str(i) ’ of ’ num2str(nrofprojects) ’...’]);%(see figure 4.8)

fmr_names{i,1} = strcat(PathName, FileName);[FileName,PathName] = uigetfile(’*_IA.trf’,...

Page 34: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

34 CHAPTER 4. TRANSFORMATIONS

[’Please select initial alignment file ’ num2str(i) ’ of ’ num2str(nrofprojects) ’...’]);ia_names{i,1} = strcat(PathName, FileName);[FileName,PathName] = uigetfile(’*_FA.trf’, ...

[’Please select fine alignment file ’ num2str(i) ’ of ’ num2str(nrofprojects) ’...’]);fa_names{i,1} = strcat(PathName, FileName);

if space > 1[FileName,PathName] = uigetfile(’*_ACPC.trf’,...

[’Please select AC-PC alignment file ’ num2str(i) ’ of ’ num2str(nrofprojects) ’...’]);acpc_names{i,1} = strcat(PathName, FileName);if space > 2

[FileName,PathName] = uigetfile(’*.tal’,...[’Please select Talairach landmarks file ’ num2str(i) ’ of ’ num2str(nrofprojects) ’...’]);

tal_names{i,1} = strcat(PathName, FileName);end

end[pathstr,name,ext,versn] = fileparts(fmr_names{i,1});vtc_names{i,1} = fullfile(pathstr, [name ’_’ vtcspaces{space} ’.vtc’]);

end

resolution = 3;answer = inputdlg(’Please enter the voxel resolution...’,...

’Create multiple VTCs’,1,{num2str(resolution)});if isnumeric(str2num(answer{1})) && str2num(answer{1}) > 0

resolution = str2num(answer{1});endinterpolation = 1; % trilinearbbithresh = 100;%(see figure 4.10) cerebellum = 0;if space < 3

answer = inputdlg(’Please enter an intensity threshold...’,...’Create multiple VTCs’,1,{num2str(bbithresh)});

if isnumeric(str2num(answer{1})) && str2num(answer{1}) > 0bbithreshold = str2num(answer{1});

endelse

button = questdlg(’Would you like an extended Talairach space (incl. cerebellum)?’,...’Create multiple VTCs’);%(see figure 4.11) if strcmp(button, ’Yes’) == 1, cerebellum = 1; end

end[FileName,PathName] = uigetfile(’*.vmr’,’Please select the anatomical data file...’);vmrfilename = strcat(PathName, FileName);

end

vmrproject = bvqx.OpenDocument(vmrfilename);vmrproject.ExtendedTALSpaceForVTCCreation = cerebellum;for i=1:nrofprojects

if space == 1success = vmrproject.CreateVTCInACPCSpace(fmr_names{i,1}, ia_names{i,1}, fa_names{i,1},...

vtc_names{i,1}, resolution, interpolation, bbithresh);elseif space == 2

success = vmrproject.CreateVTCInACPCSpace(fmr_names{i,1}, ia_names{i,1}, fa_names{i,1},...acpc_names{i,1}, vtc_names{i,1},...resolution, interpolation, bbithresh);

elseif space == 3success = vmrproject.CreateVTCInTALSpace(fmr_names{i,1}, ia_names{i,1}, fa_names{i,1},...

acpc_names{i,1}, tal_names{i,1}, vtc_names{i,1},...resolution, interpolation, bbithresh);

elsemsgbox(’An error occurred. Our apologies’);

endif (success == 1)

bvqx.PrintToLog([’Created ’ vtc_names{i,1}]);else

disp([’An error occurred while creating the VTC file’ vtc_names{i,1}]);end

end

button = questdlg(’Would you like to save the VTC parameters (for later use of this script)?’,...’Create multiple VTCs’);if strcmp(button, ’Yes’) == 1

vtcparamsfilename = fullfile(pathstr, ’vtcparams.mat’)save(vtcparamsfilename);

end

Page 35: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

4.5. TRANSFORM FUNCTIONAL DATA TO A STANDARD SPACE (*.VTC) 35

Figure 4.5: Messagebox announcing the purpose of the function

Figure 4.6: Dialog for entering the number of projects

Figure 4.7: Dialog for selecting the VTC space

Page 36: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

36 CHAPTER 4. TRANSFORMATIONS

Figure 4.8: Selecting the FMR file

Figure 4.9: Selecting the initial alignment transformation file

Figure 4.10: Entering the bounding box intensity threshold

Figure 4.11: Question about the extended box for Talairach space

Page 37: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

4.5. TRANSFORM FUNCTIONAL DATA TO A STANDARD SPACE (*.VTC) 37

4.5.2 List of functions

Table 4.1: VTC filesDescription of function Function in QSA SinceCreate VTC in VMR space CreateVTCInVMRSpace(arguments):boolean 1.3Create VTC in AC-PCspace

CreateVTCInACPCSpace(arguments):boolean 1.3

Create VTC in Talairachspace

CreateVTCInTALSPace(arguments):boolean 1.3

Link VTC file to VMR LinkVTC( ’name’ )Set TAL bounding boxsize

ExtendedTALSpaceForVTCCreation (prop-erty)

Page 38: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

38 CHAPTER 4. TRANSFORMATIONS

4.5.3 More on BrainVoyager transformation (*.trf) files

A coordinate transformation assigns new coordinates to an object in a certainspace [1]. This is necessary when the object is moved (translated), when theobject changes size (scaling) or when the object is rotated. This can be performedwith a function that transforms the x, y and z coordinates of each voxel. The co-efficients to compute the new x, y and z coordinates from the current coordinatescan be expressed in a 4x4 matrix. These coefficients express how much the objectis translated, rotated or scaled. When the coefficient quantity is equal to 1 or −1,the complete shape of the object is preserved, only its orientation can be differ-ent. Since this preserves all properties of the object, it is called an automorphism.A scaling function however changes the object, for example a matrix to performisovoxelation:

1 0 0 00 1 0 00 0 2 00 0 0 1

The first value on the diagonal of the matrix, position (0,0)1, indicates that theposition of the object on the x-axis is completely preserved in the transformation.This is also the case for the position of the voxels on the y-axis on position (1,1)of the matrix. For the z-axis however, the 2 indicates that the stepsize changes; itis computed by new voxel resolution/current voxel resolution}, inthis case 1.0/0.5 (see figure 4.12).

Figure 4.12: Components of a composed transformation matrix

1where matrix indices denoted by (row, column)

Page 39: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

4.5. TRANSFORM FUNCTIONAL DATA TO A STANDARD SPACE (*.VTC) 39

In BrainVoyager QX, 4x4 transformation matrices are saved in transformationfiles (*.trf). Via the following Matlab function can a transformation file be generated,that can be used in the creation of VTCs or to transform a anatomical (*.vmr) orstatistical volume (*.vmp) via the 3D Volume Tools dialog (see figure 4.13).

Figure 4.13: Load a transformation file via the 3D Volume Tools in BrainVoyagerQX

For example, if we would like to create a transformation file for the matrix thatflips a volume, we could do the following.

First, create the 4x4 matrix via the line

matrix = [1 0 0 0; 0 1 0 0; 0 0 2 0; 0 0 0 1];

. Then, enter the name of the file that should be transformed, for example

sourcefile = ’C:\Data\Experiment\project.vmr’;

Split the name of the sourcefile into parts to create a new filename via

[pathstr,name,ext,versn] = fileparts(sourcefile);

The new name can be created via the Matlab fullfile() command

transformedvmrname = fullfile(pathstr, [name ’_TRF’ ext]);

Finally, invoke the writeTrf() function that is provided below. Be sure thatthe Matlab current directory is the same as the directory where the Matlab file (*.m)containing the writeTrf() function.

writeTrf(2, matrix, 0, sourcefile, transformedvmrname)

Page 40: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

40 CHAPTER 4. TRANSFORMATIONS

4.5.4 Function to write a transformation filefunction writeTrf(trftype, matrix, coordsys, sourcefile, targetfile, varargin)%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% writeTrf.m% Inputparameters:% 1. trftype: 1= rigidbody; 2=affine (f.e. tosag and isovoxel); 4=tal; 5=untal% 2. 4 x 4 matrix (Matlab format: column oriented),...% 1 x 16 vector [col1 col2 col3 col4] or mat filename (SPM)% 3. coordsys: 0 is BV internal; 1 is BV sys; 2 is Talairach.% 4. sourcefile; in case of transformation type 2, optional.% 5. targetfile (trftype=1)% 6. slices; number of slices of functional data(trftype=1)% 7. functhick: slice thickness of functional images (trftype=1)% 8. gap; slice gap of functional data(trftype=1)% 9. fmr3d; 2 or 3 (trftype=1)% 10. alignstep; 1: initial alignment; 2: fine alignment (trftype=1)% 11. matxtra: 4 x 4 matrix specifying a transformation of the anatomical data (trftype=1)%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if trftype==1if nargin < 10, disp(’Need at least parameters for rigid body transformation file.’); return; endif nargin < 11

xtratrf = 0;else

matxtra = varargin(5)xtratrf = 1;

endslices = varargin(1)gap = varargin(2)fmr3d = varargin(3)alignstep = varargin(4)

elseif trftype==2if nargin < 2, disp(’Need at least 2 parameters for affine transformation file.’); return; endif nargin < 5, targetfile = fullfile(pwd,’somefile_TRF.vmr’); endif nargin < 4, sourcefile = fullfile(pwd,’somefile.vmr’); endif nargin < 3, coordsys = 2; end % assume TAL or MNI spacextratrf = 0;

endfileversion = 5;[srcPath,sourcePrt,srcExt,srcVersn] = fileparts(sourcefile);

if isnumeric(matrix)[rows, cols] = size(matrix);if rows==4 && cols==4

mat1 = reshape(matrix, 1,[]);elseif rows*cols˜=16

disp(’Wrong number of parameters in matrix’);return;

elsemat1 = matrix;

endelseif exist(matrix)==2

s = load(matrix,’M’);mat1 = reshape(s.M, 1,[]); %s.M;

else %if exist(matfile)˜=2disp(’Unrecognized input for matrix parameter’);return;

end

if trftype ==1[trgPath,targetPrt,trgExt,trgVersn] = fileparts(targetfile);trfName = fullfile(srcPath, [targetPrt ’TO’ sourcePrt ’.trf’]);

else %if trftype ==2trfName = fullfile(srcPath, [sourcePrt ’.trf’]);

end

trfFid = fopen(trfName,’wt’);fprintf(trfFid, ’\n%s\t%s\n’, ’FileVersion:’, num2str(5));fprintf(trfFid, ’\n%s\t%s\n\n’, ’DataFormat:’, ’Matrix’);fprintf(trfFid, ’%3.16f\t%3.16f\t%3.16f\t%3.16f\n’,...mat1(1,1), mat1(1,5), mat1(1,9), mat1(1,13));fprintf(trfFid, ’%3.16f\t%3.16f\t%3.16f\t%3.16f\n’,...mat1(1,2), mat1(1,6), mat1(1,10), mat1(1,14));fprintf(trfFid, ’%3.16f\t%3.16f\t%3.16f\t%3.16f\n’,...mat1(1,3), mat1(1,7), mat1(1,11), mat1(1,15));fprintf(trfFid, ’%3.16f\t%3.16f\t%3.16f\t%3.16f\n\n’,...mat1(1,4), mat1(1,8), mat1(1,12), mat1(1,16));fprintf(trfFid, ’%s\t%s\n’, ’TransformationType:’, num2str(trftype));

Page 41: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

4.5. TRANSFORM FUNCTIONAL DATA TO A STANDARD SPACE (*.VTC) 41

fprintf(trfFid, ’%s\t%s\n\n’, ’CoordinateSystem:’, num2str(coordsys));if trftype==1

fprintf(trfFid, ’%s\t%s\n’, ’NSlicesFMRVMR:’, num2str(slices));fprintf(trfFid, ’%s\t%s\n’, ’SlThickFMRVMR:’, num2str(functhick));fprintf(trfFid, ’%s\t%s\n’, ’SlGapFMRVMR:’, num2str(gap));fprintf(trfFid, ’%s\t%s\n’, ’CreateFMR3DMethod:’, num2str(fmr3d));fprintf(trfFid, ’%s\t%s\n\n’, ’AlignmentStep:’, num2str(alignstep));fprintf(trfFid, ’%s\t%s\n\n’, ’ExtraVMRTransf:’, num2str(xtratrf));if xtratrf

fprintf(trfFid, ’%3.16f\t%3.16f\t%3.16f\t%3.16f\n’,...matxtra(1,1), matxtra(1,5), matxtra(1,9), matxtra(1,13));

fprintf(trfFid, ’%3.16f\t%3.16f\t%3.16f\t%3.16f\n’,...matxtra(1,2), matxtra(1,6), matxtra(1,10), matxtra(1,14));

fprintf(trfFid, ’%3.16f\t%3.16f\t%3.16f\t%3.16f\n’,...matxtra(1,3), matxtra(1,7), matxtra(1,11), matxtra(1,15));

fprintf(trfFid, ’%3.16f\t%3.16f\t%3.16f\t%3.16f\n\n’,...matxtra(1,4), matxtra(1,8), matxtra(1,12), matxtra(1,16));

endendfprintf(trfFid, ’%s\t%s%s%s\n’, ’SourceFile:’, ’"’, sourcefile, ’"’);fprintf(trfFid, ’%s\t%s%s%s\n’, ’TargetFile:’, ’"’, targetfile, ’"’);fclose(trfFid);

return;

Page 42: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

42 CHAPTER 4. TRANSFORMATIONS

Page 43: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

Chapter 5

Experimental design

In this chapter is described how to create stimulation protocols (*.prt) and designmatrices (*.rtc, *.mdm).

5.1 Creating stimulation protocols (*.prt)

The colors for each condition can be set via the functionfmrproject.SetConditionColor(’conditionname’, red, green, blue);.To discriminate the different conditions, different colors can be used. The colors inBrainVoyager are specified as a combination of red, green and blue components,in this order. To lowest value for each component is 0 and the highest value is 255.When one of the components is set to 255 and the other two to 0, a primary color isobtained. When each of the components red, green and blue is set to 0, the resultwill be black in absence of all colors. A list with red, green and blue componentvalues for the most common colors can be found in figure 5.1.

Figure 5.1: RGB colors

43

Page 44: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

44 CHAPTER 5. EXPERIMENTAL DESIGN

Table 5.1: PRT filesDescription of function Function in QSA SinceCreate new protocol ClearStimulationProtocol() 1.3Add condition AddCondition() 1.3Get header information StimulationProtocolFile (property) 1.3

StimulationProtocolExperimentName (prop-erty)StimulationProtocolResolution (property)StimulationProtocolBackgroundColorR/G/B(properties)StimulationProtocolTimeCourseColorR/G/B(properties)StimulationProtocolTextColorR/G/B (prop-erties)StimulationProtocolTimeCourseThickness(property)

Get condition-specific in-formationSet color of condition SetConditionColor()Add interval AddInterval() 1.3Save stimulation protocol SaveStimulationProtocol() 1.3

5.2 Scripts

In this section is shown how to create a stimulation protocol from a hypotheticalPresentation Log file.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% presentation_to_bvqxprotocol.m; script to read Presentation Log file and% create stimulation protocol in Matlab% Works with BrainVoyager QX 1.9%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

bvqx = actxserver(’BrainVoyagerQX.BrainVoyagerQXInterface.1’)

[presName, presDir] = uigetfile(’*.log’,’Please select the Presentation log file...’);

presfilename = [presDir presName];

presFile2 = textread(presfilename,’%s’,’delimiter’,’\t’,’whitespace’,’’);

% reading with tabs

stimProt = struct(’Trialnr’,{},’Eventname’,{}, ’EventOffsetInMSec’,{}, ...

’EventOffsetInSec’,{}, ’EventOffsetInMin’,{}, ...

’DurationOfEventInMsec’,{}, ’DurationOfEventInSec’,{});

eventnr = 1;

for i=1:length(presFile2);

value = presFile2{i};

if ˜isempty(strfind(value, ’Picture’))

stimProt(eventnr).Trialnr = presFile2{i-1};

stimProt(eventnr).Eventname = presFile2{i+1};

offtsms = str2num(presFile2{i+2});

stimProt(eventnr).EventOffsetInMSec = (offtsms / 10);

stimProt(eventnr).EventOffsetInSec = (offtsms / 1000 / 10);

stimProt(eventnr).EventOffsetInMin = (stimProt(eventnr).EventOffsetInSec / 60);

stimProt(eventnr).DurationOfEventInMsec = (str2num(presFile2{i+5}) / 10);

stimProt(eventnr).DurationOfEventInSec = (str2num(presFile2{i+5}) / 1000 / 10);

eventnr = eventnr + 1;

end

Page 45: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

5.2. SCRIPTS 45

end;

[vmrName, vmrDir] = uigetfile(’*.vmr’,’Please select the VMR file...’);

vmrfilename = [vmrDir vmrName];

vmrproject = bvqx.OpenDocument(vmrfilename);

bvqx.ResizeWindow(600,400);

[vtcName, vtcDir] = uigetfile(’*.vtc’,’Please select the VTC file...’);

vtcfilename = [vtcDir vtcName];

vmrproject.LinkVTC(vtcName); % only filename, not pathname

vmrproject.ClearStimulationProtocol;

vmrproject.StimulationProtocolExperimentName = ’Objects_in_VF’;

vmrproject.AddCondition(’LVF’);

vmrproject.SetConditionColor(’Objects in LVF’, 255,0,0); % red

vmrproject.AddCondition(’RVF’);

vmrproject.SetConditionColor(’Objects in RVF’, 0,255,0); % green

vmrproject.AddCondition(’BVF’);

vmrproject.SetConditionColor(’Objects in BVF’, 0,0,255); % blue

vmrproject.AddCondition(’Fixation’);

vmrproject.SetConditionColor(’Fixation’, 192,192,192); % gray

% go through all the ’Picture’ objects in the ’stimProt’ structure

% to assign them as intervals to the different conditions

Picture_LVF = ’LVF’;

Picture_RVF = ’RVF’;

Picture_BVF = ’BVF’;

for i=1:length(stimProt)

if (strfind(stimProt(i).Eventname, Picture_LVF) > 0)

vmrproject.AddInterval(’LVF’, stimProt(i).EventOffsetInMSec,...

(stimProt(i).EventOffsetInMSec+stimProt(i).DurationOfEventInMsec));

elseif (strfind(stimProt(i).Eventname, Picture_RVF) > 0)

vmrproject.AddInterval(’RVF’, stimProt(i).EventOffsetInMSec,...

(stimProt(i).EventOffsetInMSec+stimProt(i).DurationOfEventInMsec));

elseif (strfind(stimProt(i).Eventname, Picture_BVF) > 0)

vmrproject.AddInterval(’BVF’, stimProt(i).EventOffsetInMSec,...

(stimProt(i).EventOffsetInMSec+stimProt(i).DurationOfEventInMsec));

end;

end

vmrproject.SaveStimulationProtocol(’cgobjects_frommatlab.prt’);

%vmrproject.LoadStimulationProtocol(’cgobjects_frommatlab.prt’);

%vmrproject.Close;

Page 46: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

46 CHAPTER 5. EXPERIMENTAL DESIGN

5.3 Creating design matrices (*.rtc, *.mdm)

Creating a single-subject design matrix (*.rtc) consists of the following steps. First,a project needs to be opened via the OpenDocument(name)method. This returnsa BrainVoyager AMR, FMR, VMR or DMR project object. All following functionsbelong to this project. Then, a VTC file and a stimulation protocol are linked viathe functions LinkVTC(name) and LinkStimulationProtocol(name). Makespace for the new matrix via the function ClearDesignMatrix;. Then, the pre-dictors can be added via AddPredictor(’name’). Set the predictor values viaSetPredictorValuesFromCondition(’name’, ’name in protocol’, value with decimals);. Thedefault value is 1.0. Then, apply the delay of the HRF in the model viaApplyHemodynamicResponseFunctionToPredictor(’name’);. Finally, the design matrix (*.rtc)can be saved with the functionSaveSingleStudyGLMDesignMatrix(’name.rtc’);. For an example script,please see below.

Page 47: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

5.3. CREATING DESIGN MATRICES (*.RTC, *.MDM) 47

5.3.1 List of functions

Table 5.2: RTC and MDM filesDescription of function Function in QSA SinceCreate new design matrix ClearDesignMatrix() 1.3Add predictor AddPredictor()

AutoAddConstantPredictor() 1.3Set predictor values SetPredictorValues()

SetPredictorValuesFromCondition()ScalePredictorValues() 1.3

Apply HRF to condition ApplyHemodynamicResponseFunctionToPredictor()1.3Get predictor valuesLoad design matrix LoadSingleStudyGLMDesignMatrix() 1.3Save design matrix SaveSingleStudyGLMDesignMatrix() 1.3Create new design matrix ClearMultiStudyGLMDefinition() 1.3Add FMR/VTC and RTC AddStudyAndDesignMatrix() 1.3Load MDM LoadMultiStudyGLMDefinitionFile() 1.3Save MDM SaveMultiStudyGLMDefinitionFile() 1.3

Page 48: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

48 CHAPTER 5. EXPERIMENTAL DESIGN

5.3.2 Script to create a design matrix%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% bvqxprotocol_to_bvqxdesignmatrix.m% Script to create a design matrix from a stimulation protocol in Matlab% Works with BrainVoyager QX 1.9%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

bvqx = actxserver(’BrainVoyagerQX.BrainVoyagerQXInterface.1’)

[vmrName, vmrDir] = uigetfile(’*.vmr’,’Please select the VMR file...’);

vmrfilename = [vmrDir vmrName];

vmrproject = bvqx.OpenDocument(vmrfilename);

bvqx.ResizeWindow(600,400);

[vtcName, vtcDir] = uigetfile(’*.vtc’,’Please select the VTC file...’);

vtcfilename = [vtcDir vtcName];

vmrproject.LinkVTC(vtcName); % only filename, not pathname

vmrproject.LinkStimulationProtocol(’cgobjects_frommatlab.prt’);

vmrproject.ClearDesignMatrix;

vmrproject.AddPredictor(’LVF’);

vmrproject.AddPredictor(’RVF’);

vmrproject.AddPredictor(’BVF’);

vmrproject.SetPredictorValuesFromCondition(’LVF’, ’Objects in LVF’, 1.0);

vmrproject.SetPredictorValuesFromCondition(’RVF’, ’Objects in RVF’, 1.0);

vmrproject.SetPredictorValuesFromCondition(’BVF’, ’Objects in BVF’, 1.0);

vmrproject.ApplyHemodynamicResponseFunctionToPredictor(’LVF’);

vmrproject.ApplyHemodynamicResponseFunctionToPredictor(’RVF’);

vmrproject.ApplyHemodynamicResponseFunctionToPredictor(’BVF’);

vmrproject.SaveSingleStudyGLMDesignMatrix(’cgobjects.rtc’);

vmrproject.CorrectForSerialCorrelations = true;

vmrproject.ComputeSingleStudyGLM;

vmrproject.ShowGLM;—

Page 49: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

Chapter 6

Statistical analysis

6.1 Computing General Linear Models (*.glm)

Via the ComputeSingleStudyGLM(), ComputeMultiStudyGLM() en ComputeRFXGLM()scripting functions, the beta weights for the model defined in the design matrix arecomputed (see figure 6.1). This expresses to what extent the actual values can beexplained from the model formulated in the design matrix.

6.1.1 Computing a single study GLM

Since the model is saved in a reference time course (*.rtc) file, this should beloaded first. The logical sequence of steps to compute a single study generallinear model (GLM) is then the following.

1. Start BrainVoyager QX Start BrainVoyager QX from Matlab viabvqx = actxserver(’BrainVoyagerQX.BrainVoyagerQXInterface.1’)

2. Open a project An FMR project or VMR project needs to be opened viavmrproject = bvqx.OpenDocument( <name> ).

3. Link VTC In case of a VMR file, link the corresponding VTC file to the VMRwith the methodvmrproject.LinkVTC( <name> ). Provide the function with the name ofthe VTC file that should be linked to the VMR file.

4. Link stimulation protocol Link the stimulation protocol defined in the *.prt fileviavmrproject.LinkStimulationProtocol( <name without path> );. This file should be in the same folder as the project.

5. Load design matrix Load the model in the reference time course file (*.rtc) viavmrproject.LoadSingleStudyGLMDesignMatrix( <name without path> );. The file should also reside in the same folder as the project.

6. Set appropriate flags

• Autocorrelation removal Set the flag for removal of the autocorrelationof the noise. This can be performed setting the BrainVoyager projectproperty vmrproject.CorrectForSerialCorrelations to true.

49

Page 50: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

50 CHAPTER 6. STATISTICAL ANALYSIS

• Normalize time courses Also can be chosen to normalize the time courses.This can be done by setting one of the project properties PSCTransformStudies,to transform to percent signal change, or ZTransformStudies orZTransformStudiesBaselineOnly, to z-transform, to true.

7. Compute the GLM The necessary preparations are entered now and theGeneral Linear Model can be computed via ComputeSingleStudyGLM().This method does not require additional arguments.

8. Save GLM results The results of the computation of the GLM can be savedvia the SaveGLM( <name> ) method. The argument that should be pro-vided is the name for the *.glm file.

Figure 6.1: Analysis of variance

Page 51: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

6.1. COMPUTING GENERAL LINEAR MODELS (*.GLM) 51

6.1.2 Computing a multi study GLM

1. Start BrainVoyager QX Start BrainVoyager QX from Matlab viabvqx = actxserver(’BrainVoyagerQX.BrainVoyagerQXInterface.1’)

2. Open a VMR project A VMR project needs to be opened viavmrproject = bvqx.OpenDocument( <name> ).

3. Load design matrix Load the models (*.rtc) and functional data (*.fmr/*.vtc)listed in the multi-study GLM definition file (*.mdm) viavmrproject.LoadMultiStudyGLMDefinitionFile( <name without path> );. The file should also reside in the same folder as the project.

4. Set appropriate flags

• Autocorrelation removal Set the flag for removal of the autocorrelationof the noise. This can be performed setting the BrainVoyager projectproperty vmrproject.CorrectForSerialCorrelations to true.

• Normalize time courses Also can be chosen to normalize the time courses.This can be done by setting one of the project properties PSCTransformStudies,to transform to percent signal change, or ZTransformStudies orZTransformStudiesBaselineOnly, to z-transform, to true.

5. Compute the GLM The necessary preparations are entered now and theGeneral Linear Model can be computed via ComputeMultiStudyGLM. Thismethod does not require additional arguments.

6. Save GLM results The results of the computation of the GLM can be savedvia the SaveGLM( <name> ) method. The argument that should be pro-vided is the name for the *.glm file.

Page 52: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

52 CHAPTER 6. STATISTICAL ANALYSIS

6.1.3 List of functions

Table 6.1: GLM filesDescription of func-tion

Function in QSA Since

Load GLM LoadGLM() 1.3Show GLM ShowGLM() 1.3Set GLM parame-ters

CorrectForSerialCorrelations (property) 1.3

ZtransformStudies (property)ZtransformStudiesBaselineOnly (property)PSCTransformStudies (property)SeparationOfStudyPredictors (property)SeparationOfSubjectPredictors (property)

Compute GLM ComputeSingleStudyGLM()ComputeMultiStudyGLM() 1.3ComputeRFXGLM()

Save GLM SaveGLM( ’name’ ) 1.3

Page 53: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

6.2. SCRIPTS 53

6.2 Scripts

The following script computes a GLM in BrainVoyager, opens the GLM in Matlab viathe BVQXtools and displays the betavalues of the middle slice in the first volume.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% compute_glm_display_betaweights.m

% Script to compute a GLM, reads it in Matlab via the BVQXtools (see wiki)

% and display the betaweights in Matlab

%

% Works with BrainVoyager QX 1.9

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

[FileName,PathName] = uigetfile(’*.fmr’,’Please select the functional data file...’);

fmrfilename = strcat(PathName, FileName);

[FileName,PathName] = uigetfile(’*.prt’,’Please select the protocol file...’);

prtfilename = strcat(PathName, FileName);

[FileName,PathName] = uigetfile(’*.rtc’,’Please select the design matrix file...’);

rtcfilename = strcat(PathName, FileName);

bvqx = actxserver(’BrainVoyagerQX.BrainVoyagerQXInterface.1’);

bvqx.ShowLogTab;

bvqx.PrintToLog(’Start computing GLM from Matlab...’);

fmrproject = bvqx.OpenDocument(fmrfilename);

fmrproject.LinkStimulationProtocol(prtfilename);

fmrproject.CorrectForSerialCorrelations = 1;

fmrproject.PSCTransformStudies = 1;

bvqx.PrintToLog([’Loading ’ rtcfilename ’...’]);

fmrproject.LoadSingleStudyGLMDesignMatrix(rtcfilename); % design matrix (*.rtc)

fmrproject.ComputeSingleStudyGLM();

fmrproject.ShowGLM();

[pathstr,name,ext,versn] = fileparts(fmrfilename);

glmfilename = fullfile(pathstr, [name ’.glm’]);

bvqx.PrintToLog([’Saving ’ glmfilename ’...’]);

fmrproject.SaveGLM(glmfilename);

answer = questdlg(’Close project?’, ’Compute GLM’);

if answer == ’Yes’

fmrproject.Close;

end

% Now read the GLM file in via BVQXtools

h = msgbox(’Please select the BVQXtools directory’);

uiwait(h);

addpath(uigetdir);

glm = BVQXFile(’GLM’);

glm = BVQXfile(glmfilename);

glm.GLMData % shows fields in structure

betaweights4d = glm.GLMData.BetaMaps;

volsize = size(betaweights4d)

slicenr = num2str(floor(volsize(3)/2));

betaweights2d = betaweights4d(:,:,floor(volsize(3)/2),1);

figure;%(see figure 6.2)

subplot(1,2,1); surf(double(betaweights2d));

title([’surface plot of beta values slice ’ slicenr ’ map 1’]); axis image xy off

subplot(1,2,2); contour(betaweights2d);

title([’contourplot of beta values slice ’ slicenr ’ map 1’]); axis image xy off

Page 54: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

54 CHAPTER 6. STATISTICAL ANALYSIS

Figure 6.2: Plot of beta values

6.3 Manipulating contrasts (*.ctr)

By setting contrasts, different hypotheses can be tested after the GLM has beencomputed. BrainVoyager QX provides several methods to add contrasts and setthe values of the contrasts (see the list of functions). To display the statistical map,use ShowGLM().The quickest way to set all contrasts simultaneously is via the methodSetContrastString( " values " ). For example, setting the contrast shownin figure 6.3, requires the following steps:

• Add the contrast The contrast can be added via AddContrast( <name> ):doc.AddContrast(’Objects_in_RVF > Objects_in_LVF’);

• Set the contrast to current The current contrastcan be set via SetCurrentContrast( <name> ):doc.SetCurrentContrast(’Objects_in_RVF > Objects_in_LVF’);

• Set the values of the contrasts for each predictor Setting the contrast valuescan be performed via indexing or strings. doc.SetContrastString(’1 -1 0’);Please note here that the third value in the string (text), represents the con-found. The contrast value can be set to 0.

Page 55: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

6.3. MANIPULATING CONTRASTS (*.CTR) 55

Figure 6.3: Contrasts

6.3.1 List of functions

Table 6.2: CTR filesDescription of function Function in QSA SinceClear constrasts ClearContrasts() 1.3Add contrast AddContrast( ’name’ ) 1.3Select contrast to change SetCurrentContrast()

SetCurrentContrastIndex() 1.3Set contrast(s) SetContrastString( ’text’ )

SetContrastValue( number )SetContrastValueAtIndex( index, value ) 1.3

Page 56: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

56 CHAPTER 6. STATISTICAL ANALYSIS

6.4 Data-driven analysis

In BrainVoyager QX, one can estimate the explanatory variables underlying theactual values using independent component analysis (ICA).To separate the mixed signal, which approaches a Gaussian distribution due to theCentral Limit Theorem, the signals are evaluated on their non-gaussianity.Distributions can be characterized by its moments, which is the tendency to clusteraround some particular value. The moments are the sums of integer powers of thevalues [6].The first moment is the mean, which estimates the value around which centralclustering occurs. The width or variability around that central value is called thesecond moment, i.e. variance or its square root, the standard deviation. Thethird moment, a less robust estimator, is the degree of asymmetry of a distributionaround its mean. This is also called skewness. The relative peakedness or flatnessof a distribution compared to a normal distribution is the fourth moment, also calledkurtosis. A positive kurtosis is called leptokurtic, a negative, c.q. relatively flat,distribution is platykurtic. Since the fourth moment in Gaussian distributions iszero, while is assumed that the separate components do have this characteristic,the kurtosis is estimated for the components via the mixing matrix.

Figure 6.4: The four moments of a distribution

The non-gaussianity can be measured in several ways. By minimizing mutualinformation (MI), which tells how much information is overlapping in the signals.The inverse can also be performed, which is maximizing the negentropy; this givesa direct estimate of how unique signal components are.This approach has two equivalents, which are Kullback-Leibler (KL) divergence be-tween the joint density and the product of its marginal densities. The equivalenceto minimizing mutual information is maximum likelihood estimation (ML). However,when using ML, only supergaussian components can be estimated, while the Fas-tICA algorithm can estimate both sub- and supergaussian independent compo-nents [4](see figure 6.4)).

6.4.1 Plotting IC parameter values in Matlab

Once in BrainVoyager QX independent components are computed [5], its finger-print can be displayed via the ’Fingerprint’ button on the Overlay ICA dialog.

A fingerprint of an independent component(see figure ??) can be assigned toone of the classes BOLD signal, residual motion artifacts, EPI susceptibility, ves-

Page 57: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

6.4. DATA-DRIVEN ANALYSIS 57

Figure 6.5: Fingerprint of BOLD component

sel, high-frequency spatially distributed noise and high frequency temporal noisebased on a characteristc score on the following dimensions:

1. degree of clustering

2. skewness

3. kurtosis

4. spatial entropy

5. first-lag autocorrelation (AR(1))

6. temporal entropy

7. power in the frequency band 0-0.0008 Hz

8. power in the frequency band 0.0008-0.02 Hz

9. power in the frequency band 0.02-0.05 Hz

10. power in the frequency band 0.05-0.1 Hz

11. power in the frequency band 0.1-0.25 Hz

Page 58: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

58 CHAPTER 6. STATISTICAL ANALYSIS

Script to plot scores of fingerprint dimensionsIn the script below the ParamsMatrix.txt is required, which contains the scores

on the 11 dimensions. The result is a plot with the components (see figure 6.6).

[FileName,PathName] = uigetfile(’*.txt’,’Please select the ParamsMatrix.txt file...’);paramsFile1 = strcat(PathName, FileName);[clustering skewness kurtosis spatialEntropy AR1 ...temporalEntropy power0to0_0008 power0_0008to0_02 power0_02to0_05 power0_05to0_1 power0_1to0_25] = ...textread(paramsFile1, ’%f %f %f %f %f %f %f %f %f %f %f’);task1 = [clustering skewness kurtosis spatialEntropy AR1 temporalEntropy...power0to0_0008 power0_0008to0_02 power0_02to0_05 power0_05to0_1 power0_1to0_25];

meansTask1 = mean(task1); % means per type of measurestdTask1 = std(task1);figure;plot(task1’, ’LineWidth’, 1, ’Color’, ’black’);hold onplot(meansTask1, ’*’)lbl1 = ’1:clust 2:skew 3:kurt 4:entropy(xyz) 5:AR(1) 6:entropy(t) 7:pow’lbl2 = ’0-0.0008 8:pow 0.0008-0.02 9:pow 0.02-0.05 10:pow 0.05-0.1 11:pow 0.1-0.25’xlabel([lbl1 lbl2]);

% components classified as BOLD, for example IC’s 6, 8, 9, 10, 16, 21BOLD(1, :) = task1(6,:);BOLD(2, :) = task1(8,:);BOLD(3, :) = task1(9,:);BOLD(4, :) = task1(10,:);BOLD(5, :) = task1(16,:);BOLD(6, :) = task1(21,:);hold onBOLDline = plot(BOLD’, ’LineWidth’, 2, ’Color’, ’green’);lblp1 = ’Scores of independent components on 11 fingerprint dimensions ’lblp2 = ’ (green: presumed BOLD components, *: mean of all components)’title([lblp1 lblp2]);hold off

Figure 6.6: Plot of the fingerprint scores

Thanks to Tobias Otto

Page 59: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

6.4. DATA-DRIVEN ANALYSIS 59

6.4.2 Validating the IC components

Script to perform first validation steps of ICsBelow is a script to get started with the ICASSO toolbox [3], using the default

BrainVoyager QX ICA settings with deflation approach, tanh non-gaussianity mea-sure and 30 eigenvalues. After the VTC is created using the COM functionality de-scribed in chapter 4, the BVQXtoolbox is used to read the VTC value in the Matlabworkspace. Then, the clusters are estimated and plotted, showing the consistencyof the component (see figure 6.7).

h = msgbox(’Please select the ICASSO directory...’)uiwait(h);dirname = uigetdiraddpath(dirname)h = msgbox(’Please select the FastICA-25 directory...’)uiwait(h);dirname = uigetdiraddpath(dirname)h = msgbox(’Please select the BVQXTools directory...’)uiwait(h);bvqxtoolsdir = uigetdiraddpath(bvqxtoolsdir)[FileName,PathName] = uigetfile(’*.vtc’,’Please select the VTC file...’);vtcfilename = [PathName FileName];vtc = BVQXfile(vtcfilename);size(vtc.VTCData)vtcdata = permute(vtc.VTCData,[2 3 4 1]);vtcdims = size(vtcdata);vtc2d = double(reshape(vtcdata,[],vtcdims(4)));sR=icassoEst(’both’, vtc2d’, 25, ’lastEig’, 30,...’g’, ’tanh’, ’approach’, ’defl’);sR=icassoExp(sR);disp(’Launch Icasso visualization supposing 30 estimate-clusters.’);disp(’Show demixing matrix rows...’);icassoShow(sR,’L’,30,’estimate’,’demixing’);disp(’Launch Icasso visualization supposing 30 estimate-clusters...’);disp(’Show IC source estimates (default), reduce number of lines...’);[iq,A,W,S]=icassoShow(sR,’L’,30,’colorlimit’,[.8 .9]);

Figure 6.7: Similarity graph of the estimates

Page 60: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

60 CHAPTER 6. STATISTICAL ANALYSIS

Page 61: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

Chapter 7

Surface meshes

Currently, the scripting methods available for meshes are for display purposes.This can be used for example for automation of the display of several meshes se-quentially, and taking screenshots.

ExampleStart BrainVoyager from Matlab:

bvqx = actxserver(’BrainVoyagerQX.BrainVoyagerQXInterface’);Get the name of the VMR file:[FileName,PathName] = uigetfile(’*.vmr’,...’Please select the VMR file...’);Create the VMR name:vmrname = [PathName FileName]Open a VMR project:vmr = bvqx.OpenDocument(vmrname). Get the name of the mesh:[FileName,PathName] = uigetfile(’*.srf’,...’Please select the surface file...’);Create the SRF name:srfname = [PathName FileName]Load the mesh:vmr.LoadMesh(srfname);Make a screenshot by providing an image name:vmr.SaveSnapshotOfSurfaceWindow(’C:\Data\srfsnapshot.png’);

61

Page 62: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

62 CHAPTER 7. SURFACE MESHES

7.0.3 List of functions

Table 7.1: Surface (*.srf) and viewpoint settings (*.vwp) filesDescription of function Function in QSA SinceSave SRF file SaveMesh() 1.2Load SRF file LoadMesh() 1.2Add SRF file AddMesh() 1.2Change viewpoint set-tings

ViewpointTranslationX (property) 1.2

ViewpointTranslationY (property)ViewpointTranslationZ (property)ViewpointRotationX (property)ViewpointRotationY (property)ViewpointRotationZ (property)

Page 63: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

7.1. SCRIPTS 63

7.1 Scripts

The following script reads a BrainVoyager QX surface file (*.srf) version 3 in Matlaband displays the mesh in different ways.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% meshes.m% Script to visualize a mesh with different axes in Matlab%% Works with BrainVoyager QX 1.9 with *.srf files at least up to version 4.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

[FileName,PathName] = uigetfile(’*.srf’,’Please select the *.srf file...’);srfFile = strcat(PathName, FileName);fid=fopen(srfFile,’rb’); % read only%%%%% read in header data %%%%%version_number = fread(fid, [1 1], ’float32’); % version number of surface file; default: 3reserved = fread(fid, [1 1], ’uint32’); % reserved, must be ’0’NrOfVertices = fread(fid, [1 1], ’uint32’); % number of verticesNrOfTriangles = fread(fid, [1 1], ’uint32’); % number of triangles

% COORDINATE VALUESMeshCenterX = fread(fid, [1 1], ’float32’); % center of mesh on X-axis; default coordinate: 128MeshCenterY = fread(fid, [1 1], ’float32’); % center of mesh on Y-axis; default coordinate: 128MeshCenterZ = fread(fid, [1 1], ’float32’); % center of mesh on Z-axis; default coordinate: 128VertexX = fread(fid, [1 NrOfVertices], ’float32’); % sequence of X coordinates of all verticesVertexY = fread(fid, [1 NrOfVertices], ’float32’); % sequence of Y coordinates of all verticesVertexZ = fread(fid, [1 NrOfVertices], ’float32’); % sequence of Z coordinates of all verticesNormalX = fread(fid, [1 NrOfVertices], ’float32’); % sequence of X components of all vertex normalsNormalY = fread(fid, [1 NrOfVertices], ’float32’); % sequence of Y components of all vertex normalsNormalZ = fread(fid, [1 NrOfVertices], ’float32’); % sequence of Z components of all vertex normals

% COLORS OF THE SURFACERedConvCurv = fread(fid, [1 1], ’float32’);% R component of convex curvature color (range: 0.0 - 1-0); default: 0.322GreenConvCurv = fread(fid, [1 1], ’float32’);% G component of convex curvature color (range: 0.0 - 1-0); default: 0.733BlueConvCurv = fread(fid, [1 1], ’float32’);% B component of convex curvature color (range: 0.0 - 1-0); default: 0.980AlphaConvCurv = fread(fid, [1 1], ’float32’);% Alpha component of convex curvature color (range: 0.0 - 1-0); default: 0.500RedConvCurv = fread(fid, [1 1], ’float32’);% R component of convex curvature color (range: 0.0 - 1-0); default: 0.100GreenConcCurv = fread(fid, [1 1], ’float32’);% G component of concave curvature color (range: 0.0 - 1-0); default: 0.240BlueConcCurv = fread(fid, [1 1], ’float32’);% B component of concave curvature color (range: 0.0 - 1-0); default: 0.320AlphaConcCurv = fread(fid, [1 1], ’float32’);% Alpha component of concave curvature color (range: 0.0 - 1-0); default: 0.500MeshColor = fread(fid, [1 NrOfVertices], ’int32’);% sequence of color indices of all vertices (*1)

% ALL VERTEX NEIGHBOURSvertexNeighbours = struct(’VertexNr’,{}, ’NrNeighbours’,{},’Neighbours’,{});for vertexCounter=1:NrOfVertices

vertexNeighbours(vertexCounter).VertexNr = vertexCounter;NrOfNeighbours = fread(fid, [1 1], ’int32’);vertexNeighbours(vertexCounter).NrNeighbours = NrOfNeighbours;vertexNeighbours(vertexCounter).Neighbours = fread(fid, [1 NrOfNeighbours], ’int’);

end% TriangleSequence = fread(fid, [1 NrOfTriangles*3], ’int’);% Sequence of three indices to constituting vertices of each triangle% NrOfTriangleStripElements = fread(fid, [1 1], ’int’); % Number of triangle strip elements% if (NrOfTriangleStripElements > 0)% StripElemSequence = fread(fid, [1 NrOfTriangleStripElements], ’int32’); % Sequence of strip elements% endfclose(fid);% (*1) Each vertex has one color index. An index value of 0 references the convex curvature color,% a value of 1 references the concave curvature color. Functional colors, RGB colors can be also represented.

% From example from Matlab Help documentation on multiple axes

tris = reshape(TriangleSequence,3,[])’+1;

figure; %(see figure 7.1)

h(1) = axes(’Position’,[0 0 1 1]);

trimesh(tris, VertexX’,VertexY’,VertexZ’);

h(2) = axes(’Position’,[0 0 .4 .6]); % closer, on the left lower corner

Page 64: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

64 CHAPTER 7. SURFACE MESHES

trimesh(tris, VertexX’,VertexY’,VertexZ’);

h(3) = axes(’Position’,[0 .5 .5 .5]); % closer, on the left upper corner, stretched

trimesh(tris, VertexX’,VertexY’,VertexZ’);

h(4) = axes(’Position’,[.5 0 .4 .4]); % closer, on the right lower corner, stretched

trimesh(tris, VertexX’,VertexY’,VertexZ’);

h(5) = axes(’Position’,[.5 .5 .5 .3]); % closer, on the right upper corner, very stretched

trimesh(tris, VertexX’,VertexY’,VertexZ’);

set(h,’Visible’,’off’)

Figure 7.1: Display meshes with different axes

Page 65: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

Chapter 8

Using BVQXtools

The BVQXtools is a toolbox created by Jochen Weber to read and manipulateBrainVoyager data in Matlab. The functionality in BrainVoyager QX and the BVQX-tools can be nicely combined now COM is available.For example, once a COM connection is established between Matlab and Brain-Voyager QX, one can first instruct BrainVoyager QX to create and preprocess func-tional data, and even create VTC files. Then, the files can be read quickly into theMatlab workspace by the BVQXtools.

To obtain the BVQXtools, download the toolbox from the BrainVoyager QX wikiathttp://wiki.brainvoyager.com/BVQXTools (see figure 8.1). To make theBVQXTools available in Matlab, add the path of the BVQXtools to Matlab. This canfor example be realized via the instruction addpath(uigetdir);.

Figure 8.1: BVQXtools on the BrainVoyager QX wiki

65

Page 66: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

66 CHAPTER 8. USING BVQXTOOLS

Page 67: Scripting BrainVoyager QX from Matlabsupport.brainvoyager.com/documents/Automation... · BrainVoyager QX will fullfil the role of COM-server, where the COM-client Matlab will request

Bibliography

[1] J.D. Foley, A. van Dam, S.K. Feiner, and J.F. Hughes. Computer Graphics;Principles and Practice. Boston: Addison-Wesley Publishing Company, Inc.,1997.

[2] R. Goebel, F. Esposito, and E. Formisano. Analysis of fiac data with brain-voyager qx: From single-subject to cortically aligned group glm analysis andself-organizing group ica. Human Brain Mapping, 27(5):392–401, 2006.

[3] J. Himberg, A. Hyvrinen, and F. Esposito. Validating the independent compo-nents of neuroimaging time-series via clustering and visualization. NeuroIm-age, 22(3):1214–1222, 2004.

[4] A. Hyvrinen and E. Oja. Independent component analysis: Algorithms andapplications. Neural Networks, 13(4-5):411–430, 2000.

[5] F. de Martino, F. Gentile, F. Esposito, M. Balsi, F. Di Salle, R. Goebel,and E. Formisano. Classification of fmri independent components using ic-fingerprints and support vector machine classifiers. NeuroImage, 34(1):177–194, 2007.

[6] W.A. Press, S.A. Teukolsky, W.T. Vettering, and B.P. Flannery. NumericalRecipes in C; The Art of Scientific Computing. Cambridge: Cambridge Uni-versity Press, 2002.

67