心理のためのMatlabチュートリアル (SPMユーザに役立つMatlab入門)

SPMを使う方々は必ずMatlabを使いますが、世の中のMatlab入門をうたった書籍は、たいていが工学向けで、SPMを使う人がこれを知っておいたらいいというようなMatlab入門はあまりありません。何かいい手引きがないかと探していたら、Antonia Hamilton女史の書いたMatlab for Psychologists: A Tutorialという手引きを見つけました。ざっと見たところ非常によい手引きと感じたので、Hamilton女史に連絡をとり、日本語訳の許可をいただきました。日本語訳ができましたので、公開します。「心理のため」となっていますが、SPMを使う方々には、とても有用だと思います。
 なお、翻訳にあたり、山口大学の松尾幸治先生に多くのアドバイスをいただきました。この場をお借りして深謝いたします。

心理のためのMatlabチュートリアルをダウンロード

チュートリアルで用いるデータは下からダウンロードしてください。
練習用データ

SPM switcher: Run different versions of SPM in one Matlab

I used to write an article, “Run SPM2, SPM5, and SPM8 concurrently.” Though this is a smart way to run different version of SPM, we need to prepare scripts separately. So I came up with another script, called “SPM switcher”. This script brings up a dialog and you can select the version of SPM you want to run.

  • Make a directory where you want to save scripts. (e.g. C:\Users\foo\Documents\MATLAB\)
  • Add the directory to the path in Matlab. (File -> Set Path -> Add path)
  • put spm_rmpath.m in SPM2 and SPM99 directory.
  • You find this file in SPM5 or SPM8 directory. You can just copy it from SPM5/8 to SPM2/99 directory.

  • save switchspm.m in the directory you prepared.
  • edit switchspm.m and change “spm_path=’C:\spm\'” according to your circumstance.

Typing switchspm in Matlab command window will bring up a dialog below and you can run different version of SPM easily.

switchspm_screenshot

Download switchspm.m (Right click –> Save as)

%switchspm: Run different version of SPM
%This tiny script prompts the dialog which SPM version you want to run.
%Prerequisites
%1. Each version of SPM is supporsed to be located under spm_path.
%2. Please copy spm_rmpath.m from SPM5 or later and put it into SPM99 and
%   SPM2 direcotry. Otherwise, Path removal won't work correctly.
%3. Please change the SPM path according to your environment

%%%Please change the path below according to your environment%%%
spm_path='C:\spm\';
%%%

%The path for each version of SPM
spm99_path=fullfile(spm_path,'spm99');
spm2_path=fullfile(spm_path,'spm2');
spm5_path=fullfile(spm_path,'spm5');
spm8_path=fullfile(spm_path,'spm8');
spm12_path=fullfile(spm_path,'spm12');

str = ['spm99 '; 'spm2  '; 'spm5  '; 'spm8  '; 'spm12'];
spmver = listdlg('PromptString','SPM ver you want to run...',...
                'SelectionMode','single',...
                'ListString',str);

switch spmver
    case 1, %spm99
    % remove spm path
    while true
      try
        spm_rmpath
        catch break;
      end;
    end;
    % add spm99 path
    addpath(spm99_path);
    % run spm99
    spm;
        
    case 2, %spm2
    % remove spm path
    while true
      try
        spm_rmpath
        catch break;
      end;
    end;
    % add spm2 path
    addpath(spm2_path);
    % run spm2
    spm;

    case 3, %spm5
    % remove spm path
    while true
      try
        spm_rmpath
        catch break;
      end;
    end;
    % add spm5 path
    addpath(spm5_path);
    % run spm5
    spm;
        
    case 4 %spm8
    % remove spm path
    while true
      try
        spm_rmpath;
        catch break;
      end;
    end;
    % add spm8 path
    addpath(spm8_path);
    % run spm8
    spm;

    case 5 %spm12
    % remove spm path
    while true
      try
        spm_rmpath;
        catch break;
      end;
    end;
    % add spm12 path
    addpath(spm12_path);
    % run spm12
    spm;
end

SPM5およびSPM8でAC-PCを自動で設定できるスクリプト

この記事は、http://www.nemotos.net/?p=17で紹介したものを日本語に訳しただけのものです。

2008年10月18日に、Carlton Chu氏がSPMのメーリングリストに便利なスクリプトを投稿しました。
メーリングリストでは特に反応はなかったのですが、非常に有用だと思いますので、本ブログで紹介させていただきます。

このスクリプトの目的はいたってシンプルです:AC-PCを自動的にあわせてくれます!

若干時間がかかります(1例に数分かかります)が、何百例もAC-PCをあわせなくてはいけないような状況では、大きな時間の節約になります。
もし関心があったら、次のスクリプトを試してみて下さい。SPM5、SPM8でうまく動きます。

オリジナルの投稿では、若干動作しないバグがありました。そこを修正してあります。

使用方法:添付のファイルをダウンロードし、SPM5かSPM8に置いてください。その後、MATLABのコマンドウィンドウから、”auto_reorient”とタイプしてください。ファイル選択のウィンドウが立ち上がりますので、AC-PCを設定したいファイルを選択して下さい(複数選択できます)。

function auto_reorient(p)
spmDir=which('spm');
spmDir=spmDir(1:end-5);
tmpl=[spmDir 'canonical/avg152T1.nii'];
vg=spm_vol(tmpl);
flags.regtype='rigid';
p=spm_select(inf,'image');
for i=1:size(p,1)
f=strtrim(p(i,:));
spm_smooth(f,'temp.nii',[12 12 12]);
vf=spm_vol('temp.nii');
[M,scal] = spm_affreg(vg,vf,flags);
M3=M(1:3,1:3);
[u s v]=svd(M3);
M3=u*v';
M(1:3,1:3)=M3;
N=nifti(f);
N.mat=M*N.mat;
create(N);
end

auto_reorient.m

SPMをオンラインでアップデートする方法

SPMは定期的にアップデートされています。spm_updateというコマンドをうつと、自分のSPMのバージョンが最新かどうかチェックできます。

>> spm_update
A new version of SPM is available on:
ftp://ftp.fil.ion.ucl.ac.uk/spm/spm8_updates/
(Your version: 4290 - New version: 4667)

これまで、FTPでアップデートをとってきていましたが、ある方に、spm_update(1)とやると、自動で最新ファイルを入手してくれるよと教わりました。

自分が使っているSPMがちょうどアップデートが必要だったのでやってみました。

>> spm_update(1)
A new version of SPM is available on:
ftp://ftp.fil.ion.ucl.ac.uk/spm/spm8_updates/
(Your version: 4290 - New version: 4667)
2781 files have been updated.

確かにアップデートされます。便利ですね。

VBMの結果を用いて容積を測定する方法

VBMで得られる画像を用いて、灰白質や白質画像の容積を求めることができます。

事前の準備として、以下のことが必要です。

  • get_totals.m
  • Ged Ridgwayが公開している容積算出のためのスクリプトです。http://www0.cs.ucl.ac.uk/staff/g.ridgway/vbm/get_totals.mここから入手できます(右クリックしてリンク先を保存としてください)。これをSPMのディレクトリに保存します。

  • WFU PickAtlas
  • これは、局所容積を求めたい時に便利です。マスク画像を簡単に作成することができます。http://fmri.wfubmc.edu/software/PickAtlasここから入手できます。今回はこのセットアップ方法は説明しませんのであしからず。

続きを読む

How to do Topological FDR

Many ask “how to do Topological FDR” in SPM ML. Below are the posts I found useful.

Originally Guillaume Flandin showed how to do that.
https://www.jiscmail.ac.uk/cgi-bin/webadmin?A2=SPM;44838216.0904

The height threshold you define during the Results procedure is the feature-inducing threshold (used to define local maxima and clusters).
For topological FDR, I would typically choose “none” and a small T-value, for example 3.
The MIP will display all voxels whose T-value is above 3 and the Results table will display all local maxima whose T-value is above 3 (actually, at most 3 local maxima per cluster, more than 8mm apart) and the corresponding FWE p-values and FDR q-values for peaks and clusters.

If you want to threshold the MIP to a particular significance level, go through the Results procedure again and enter the corresponding height and extent thresholds (the 0.05 critical thresholds are indicated at the bottom left of the Results table):
(height) FWEp and FDRp for peak-FWE and -FDR.
(extent) FWEc amd FDRc for cluster-FWE and -FDR.

Jonathan Peele also gave a detail instruction of how to do that. This time he focused more on cluster-thresholded FDR.
https://www.jiscmail.ac.uk/cgi-bin/webadmin?A2=SPM;6f4e0139.1110

> How can I see images with a threshold at the cluster-level instead of the peak level with the graphical user interface?

I’m not aware of a way to set a cluster-level threshold when running results the first time (i.e., “show everything that is cluster-level corrected p < .05").  What I would do is this: 1) Run results using some voxelwise threshold.  This threshold defines your clusters, and it's fine to use an uncorrected threshold (e.g., p< .001, uncorrected). 2) In the results table, for each cluster you will see the cluster extent (i.e. how many voxels) and the cluster-corrected p value.  In SPM8 you will see 2 cluster-corrected p values, one for topological FDR (Chumbley & Friston, 2009), one for random field theory (labeled FWE).  You can then look at the size of those clusters, and figure out the cluster extent  that divides p < .05 from the others.  For example, if a cluster of 300 voxels is p = .10, and a cluster of 400 voxels is p = .04, then you know that any cluster 400 voxels or larger would be p < .05. 3) Re-run the results, selecting the same voxelwise threshold. But now, in the minimum cluster extent, specify the cluster size you just figured out—in the above example, you could specify 400.

4) Now all of the displayed results should be cluster-level corrected.

5) If you want to save this thresholded image for displaying with another program, just click the “save” button, and you can write out a thresholded t map as a nifti file.

In practice this is actually fairly quick to do once you’ve done it a couple of times.

Note the difference between these two. Two-step approach is the same, but Guillaume’s way deals with peak and cluster threshold and Jonathan’s way deals with cluster threshold.

Voxel-wise FDR and Topological FDR

In SPM8, voxel-wise FDR was hidden and Topological FDR was introduced. What is Topological FDR? I find some useful notes from SPM8 Release Notes and a post by Tom Nichols to SPM-ML. I quote these two.

SPM8 Release Notes

Topological False Discovery Rate (FDR)

FDR control is an alternative to the more conservative “family-wise error” control for multiple comparisons. Historically, SPM has aimed to control FDR on voxels (the
expected fraction of false-positive/total-positive decisions made about individual voxels in an image). This is now superseded by FDR control of topological properties of the signal (i.e. control of properties that pertain to the spatial organization of activations – e.g. height and extent – and are not reducible to individual voxels). SPM is now able to identify significantly voluminous blobs according to a decision procedure that controls spatial-extent FDR. Thus, on average, the fraction of blobs falsely deemed to have significant spatial extent is controlled beneath say 5/100 = .05 or 1/100 = .01. More recent work is examining FDR control over local maxima.

A post to SPM-ML by Tom Nichols

In SPM8 FDR topological inference was introduced, and voxel-wise FDR inference hidden. Topological inference means inference on peaks and clusters; voxel-wise inference is based on every individual voxel in the image (instead of spatial features of the image). Thus “Topological FDR” means inference on clusters based on cluster size (or local peaks based on peak height), controlling the fraction of false positive clusters among all clusters (or false positive peaks among all peaks) on average, over many experiments.

While topological FDR results may be easier to interpret, in my experience it is is generally not very sensitivity and yields similar results to FWE-corrected inferences.

If you would like to use voxel-wise FDR in SPM8, edit spm_defaults, changing “topoFDR” line to read
defaults.stats.topoFDR = 0;
(quit and re-start SPM to take effect).

References
Chumbley, J., Worsley, K., Flandin, G., & Friston, K. (2010). Topological FDR for neuroimaging. NeuroImage, 49(4), 3057-64. doi: 10.1016/j.neuroimage.2009.10.090.

Chumbley, J. R., & Friston, K. J. (2009). False discovery rate revisited: FDR and topological inference using Gaussian random fields. Neuroimage, 44(1), 62–70. doi: 10.1016/j.neuroimage.2008.05.021.

Files generated in VBM statistics

When you do VBM analysis, you see many files are generated in your stats directory. Suppose you are doing a two sample t-test. You see files like below.

  • beta_0001
  • beta_0002
  • con_0001
  • mask
  • ResMS
  • RPV
  • spmT_001

Ged Ridgway made a clear explanation of these files in NITRC discussion forum. http://www.nitrc.org/forum/message.php?msg_id=6483
It is important to know what these files are, so I quote his post with some modification.

  • beta
  • The estimated linear model parameters at each voxel. In a two-sample design, these are just the two group mean images. beta_0001 is a mean image of group A, and beta_0002 is a mean image of group B.

  • con
  • The contrasts of the parameters. If one makes a contrast of [-1 1], the con_0001 will simply be beta_0002 – beta_0001

  • mask
  • A binary image indicating which voxels were considered in the analysis. If this mask is too small, you may miss the region you are interested in. If too big, it is less likely to survive multiple comparison. So it is worth checking the mask image before you draw some conclusion from your analysis.

  • ResMS
  • The estimated variance (residual mean squares), from which the above-mentioned standard error is derived.
    In more detail, the standard error is proportional to the square root of ResMS and a term that relates to the design matrix X and contrast c as sqrt(c’*pinv(X’*X)*c), which (in two sample t-test) roughly reflects the fact that the standard error is inversely proportional to the number of subjects one has.

  • RPV
  • The resels-per-voxel image related to the smoothness (roughness)
    estimate needed for random field theory.

  • spmT
  • The t-statistic maps formed by dividing the contrast image by its estimated standard error.

Voxel-counting script

Sometimes we just want to count the number of voxels whose values are more than zero.
My friend showed me a script which can do that easily. SPM functions are used, so you need to install SPM first.

%%%%%countvx.m
%a script which counts voxels whose values are more than zero.
file = spm_select;
vol = spm_vol(file);
img = spm_read_vols(vol);
sum(img(:)>0)

If you change the value of the last line from 0 to 0.1, you will count the number of voxels whose values are more than 0.1.

共変量⊂Covariateではあるが、共変量=Covariateではない

SPMを使っていると、Covariateという単語がよく出てきます。
Covariateを日本語に訳すと、「共変量」となりますが、SPMでのCovariateはもうちょっと広い気がしていました。
Matthew BrettのIntroduction to SPM statisticsを翻訳したものに対し、他の先生方からご指摘をいただき、改めて検討してみました。

Wikipedia英語版では、covariateについて以下のように説明されています。

In statistics, a covariate is a variable that is possibly predictive of the outcome under study. A covariate may be of direct interest or it may be a confounding or interacting variable.

ここで、covariateは結果を予測する変数であり、直接関心のある変数のこともあれば、そうでないこともあると書かれています。日本語の「共変量」の意味するところは、後者のことだけを指しますので、英語のcovariateの方が広義ということになります。

Wikipediaに戻ります。

The alternative terms explanatory variable , independent variable , or predictor, are used in a regression analysis . In econometrics , the term “control variable” is usually used instead of “covariate”.

上記で述べたように、covariateは説明変数、独立変数、予測因子とも表現されると書かれています。

さらに、以下のようにも述べられています。

In a more specific usage, a covariate is a secondary variable that can affect the relationship between the dependent variable and other independent variables of primary interest.

ここで、「より狭義の意味では、covariateは従属変数と最も関心のある独立変数との関係に影響を与える二次的な変数である」となっています。これがまさに日本語に訳されるところの「共変量」ということになります。

つまり、covariateには、広義のcovariateと狭義のcovariateがあり、狭義のcovariateは日本語で言うところの共変量を指し、広義のcovariateは、回帰分析における説明変数のような変数も入ってくるわけです。

ということで、タイトルになるわけですが、SPMにおいては、共変量⊂Covariateではあるが、共変量=Covariateではないということに注意が必要です。
説明をするときには気をつける必要がありますね。

A study of SPM script: Data type converter

I’m learning how to make a script for SPM.
Below is a simple script which converts the data type of the image file.
It should work for both SPM8 and SPM5.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Data type converter
%Convert the data type (uint8, int16, int32, float32, float64)
%Usage
%Change the value at line 26(options.dtype) to the datatype you want.
%Kiyotaka Nemoto 2 Jan 2010
P = spm_select(Inf,’image’,'Select Files to be converted’);
for i=1:size(P,1)
ref = deblank(P(i,:));
[pth,nam,ext] = spm_fileparts(ref);
odir = pth;
cvt = ['d' nam '.nii'];
matlabbatch{1}.spm.util.imcalc.input = {ref};
matlabbatch{1}.spm.util.imcalc.output = cvt;
matlabbatch{1}.spm.util.imcalc.outdir = {odir};
matlabbatch{1}.spm.util.imcalc.expression = ‘i1′;
matlabbatch{1}.spm.util.imcalc.options.dmtx = 0;
matlabbatch{1}.spm.util.imcalc.options.mask = 0;
matlabbatch{1}.spm.util.imcalc.options.interp = 1;
matlabbatch{1}.spm.util.imcalc.options.dtype = 4;
% uint8=2; int16=4; int32=8; float32=16; float64=64
spm_jobman(‘run’,matlabbatch);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Download datatypeconv.m

VBM8マニュアル 日本語版

VBMをされている方ならばChristian Gaserが開発しているVBM-toolsについて聞き及んだことがあると思います。
彼の許可を得て、このたびVBM8のマニュアルを訳しました。
訳がこなれていないところはありますが、英語を読むのがつらい方には多少はお役に立つかと。
それにしても、この世界にいる方々はみんな親切で協力的です。とてもありがたいことですね。

VBM8日本語マニュアルをダウンロード

*21/Aug/2013 リンク先をChristian Gaserのページに変更しました。
縦断解析の行列のところに修正がかかっています。
修正版をダウンロードしてご使用いただけたらと思います。
ご指摘いただいたM先生ありがとうございました。

VBMチュートリアル日本語版

これまで日本語でのVBMのドキュメントは非常に限られたものでした。
いいものが出てこないかなと思っていましたが、なかなか出てこないので、思い切って自分で日本語のドキュメントを作成してみました。といっても他の方々の協力をたくさん得てですが。

オリジナルは2010年5月にEdinburghで開催されたSPM couseのVBMクラスで使われた資料です。John Ashburner氏がSPMのメーリングリストで公開されていましたので、Johnから翻訳の承認をもらったうえで、翻訳しました。翻訳を助けてくださった高橋先生、草稿に目を通してくださってアドバイスをくださった松尾先生に感謝いたします。

興味のある方は以下のリンクからPDFをダウンロードしてみてください。

VBMチュートリアル日本語版

SPMのセットアップ方法

包括型脳科学研究推進支援ネットワークで、2011年1月16日に、ワークショップ「精神疾患の画像研究スタートアップ」が行われました。

私がそこで参加者の皆様にお配りしたSPMのセットアップに関しての手引きに関していくつかリクエストをいただいたので公開します。

SPMのセットアップに困っている方々のお役に立つかもしれません。

SPMのセットアップ方法をダウンロード

Introduction to SPM statistics 日本語版 (SPM統計入門)

私がSPMについて学び始めたころ、SPMの統計のところについての入門書的なリソースがないか探していた時に、Matthew Brett氏のIntroduction to SPM statisticsに出会いました。1999年に書かれたものなので、SPM96とSPM99を対象に書かれていますが、原則は同じですので、今でも十分に役立ちます。SPMの統計の基本を学びたい方にとっては必読と思います。

このたび、Matthew Brett氏から許可を得て日本語に翻訳しました。SPMの日本語リソースがまだまだ少ない中、お役に立てれば幸いです。

SPM統計入門(PDF)をダウンロード

Run SPM2, SPM5, and SPM8 concurrently

Many SPMers use different versions of SPM. We can run different versions of SPM in one computer, but we need to set MATLAB path carefully.

I had some discussion with Volkmar Glauche and Guillaume Flandin, who kindly gave me advice how to write the script for running diferrent spms.

Below is the scripts which enables us to run SPM2, SPM5, and SPM8 concurrently.

  1. make a directory where you want to save scripts. (e.g. ~/spm_paths/)
  2. add the directory to the path in Matlab. (File -> Set Path -> Add path)
  3. put spm_rmpath.m in SPM2 folder.
  4. You find this file in SPM5 or SPM8 directory. You can just copy it from SPM5/8 to SPM2 directory.

  5. write scripts to run spm2, spm5, and spm8
  6. suppose your spm2, spm5, and spm8 directories are “/usr/local/spm2″, “/usr/local/spm5″, and “/usr/local/spm8″. (change the pathname to your circumstance)

    %%%%%%%%%%%%%%% spm2.m
    % remove spm path
    while true
    try, spm_rmpath; catch break; end
    end
    % add spm2 path
    addpath /usr/local/spm2;
    % run spm2
    spm;

    %%%%%%%%%%%%%%% spm5.m
    % remove spm path
    while true
    try, spm_rmpath; catch break; end
    end
    % add spm5 path
    addpath /usr/local/spm5;
    % run spm5
    spm;

    %%%%%%%%%%%%%%% spm8.m
    % remove spm path
    while true
    try, spm_rmpath; catch break; end
    end
    % add spm8 path
    addpath /usr/local/spm8;
    % run spm8
    spm;

    (Of course you can add any paths you like between “addpath /usr/local/spm/spm2/5/8″
    and “spm”)

  7. save these scripts in the directory ~/spm_paths/
  8. In a matlab window, type “spm2″
  9. In another matlab window, type “spm5″
  10. In another matlab window, type “spm8″

Now you can run different versions of SPM concurrently.

Matlab script for automatic AC-PC setting in SPM5, 8, or 12

ON 17 Oct 2008, Carlton Chu posted a nice script to SPM mailing list.
Though it doesn’t have any response from the list, I find it very useful, so I introduce the script on my blog.

The purpose of the script is simple: Set AC-PC automatically for you!

Though it takes time (around 5 minutes per subject in my circumstance), It’s so much time-saving for me who have more than 1000 subjects which I need to realign.

If you are interested, try the following script. It works for SPM5 and later (SPM8 or 12).

In the original post, function which calls select files window was commented out. I uncommented it and it runs without any problems.


function auto_reorient(p)
spmDir=which('spm');
spmDir=spmDir(1:end-5);
tmpl=[spmDir 'canonical/avg152T1.nii'];
vg=spm_vol(tmpl);
flags.regtype='rigid';
p=spm_select(inf,'image');
for i=1:size(p,1)
f=strtrim(p(i,:));
spm_smooth(f,'temp.nii',[12 12 12]);
vf=spm_vol('temp.nii');
[M,scal] = spm_affreg(vg,vf,flags);
M3=M(1:3,1:3);
[u s v]=svd(M3);
M3=u*v';
M(1:3,1:3)=M3;
N=nifti(f);
N.mat=M*N.mat;
create(N);
end

Usage: Download the file below, put the file into the SPM5, 8, or 12 directory, and run “auto_reorient” from Matlab window.

auto_reorient.m