Tuesday, July 31, 2012

FSL Summary

After finishing that cycle of tutorials, I feel as though a summary would be useful. Some of these are points that were highlighted during the walkthroughs, whereas others are germane to any neuroimaging experiment and not necessarily specific to any software analysis package. The past couple of weeks have only scratched the surface as to the many different experimental approaches and analysis techniques that are available, and the number of ways to gather and interpret a set of data are nearly inexhaustible.

That being said, here are some of the main points of FSL:

1) These guys really, really like acronyms. If this pisses you off, if you find it more distracting than useful, I'm sorry.

2) Download a conversion package such as dcm2nii (part of Chris Rorden's mricron package here) in order to convert your data into nifti format. Experiment with the different suffix options in order to generate images that are interpretable and easy to read.

3) Use BET to skull strip your anatomicals as your first step. There is an option for using BET within the FEAT interface; however, this is for your functional images, not your anatomical scans. Skull stripping is necessary for more accurate coregistration and normalization, or warping your images to a standardized space.

4) As opposed to other analysis packages, FSL considers each individual run to be a first-level analysis; an individual subject comprising several runs to be a second-level analysis; collapsing across subjects to be a third-level analysis; and so forth. I recommend using the FEAT interface to produce a template for how you will analyze each run (and, later, each subject), before proceeding to batch your analyses. Especially for the beginner, using a graphical interface is instructive and helps you to comprehend how each step relates to the next step in the processing stream; however, once you feel as though you understand enough about the interface, wean yourself off it immediately and proceed to scripting your analyses.

5) Use the Custom 3-column option within the Stats tab of FEAT in order to set up your analysis. Most studies these days are event-related, meaning that events are of relatively short duration, and that the order of presentation is (usually) randomized. Even if your analysis follows the same pattern for each run, it is still a good habit to use and get comfortable with entering in 3-column timing files for your analysis.

6) If your initial attempts at registration and normalization fail, set the coregistration and normalization parameters to full search and maximum degrees of freedom (i.e., 12 DOF). This takes more time, but has fixed every registration problem I have had with FSL.

7) Look at the output from your stats, and make sure they are reasonable. If you have done a robust contrast which should produce reliable activations - such as left button presses minus right button presses - make sure that it is there. If not, this suggests a problem with your timing, or with your images, which is a good thing to catch early. Also look at your design matrix, and make sure that events are lined up when you think they should be lined up; any odd-looking convolutions should be investigated and taken care of.

8) This piece of advice was not covered in the tutorials, nor does it apply to neuroimaging analysis itself exactly, but it bears repeating: Run a behavioral experiment before you scan. Obtaining behavioral effects - such as reaction time differences - are good indicators that there may actually be something going on neurally that is causing the observed effects. The strength and direction of these behavioral differences will allow you to predict and refine your hypotheses about where you might observe activation, and why. Furthermore, behavioral experiments are much cheaper to do than neuroimaging experiments, and can lead to you to make considerable revisions to your experimental paradigm. Running yourself through the experiment will allow you to make a series of commonsense but important judgments, such as: Do I understand how to do this task? Is it too long or too boring, or not long enough? Do I have any subjective feeling about what I think this experiment should elicit? It may drive you insane to pilot your study on yourself each time you make a revision, but good practice, and can save you much time and hassle later.

That's about it. Again, this is targeted mainly toward beginners and students who have only recently entered the field. All I can advise is that you stick with it, take note of how the top scientists run their experiments, and learn how to script your analyses as soon as possible. It can be a pain in the ass to learn, especially if you are new to programming languages, but it will ultimately save you a lot of time. Good luck.

Sunday, July 29, 2012

FSL Tutorial 6: Automating FEAT

So now you know enough to run an analysis on your own; Congratulations! However, before you crack open a fresh jar of Nutella to celebrate, be aware that there are other methods that can greatly increase your efficiency, confidence, and libido.

We now turn to a slightly more sophisticated way to run your analyses, that is, through the command line as opposed to the pointing and clicking through the graphical user interface. When I mentioned in the last post that this factors out human error, what I meant was that it eliminates any error due to faulty clicks in the GUI, or fat-finger dialing of any additional parameters. The probability that you would enter everything in by hand the exact same way for every subject is essentially zero. Learning the basics of scripting is essential for any neuroimaging researcher these days, even if it is just to acquire enough familiarity to know what is going on when reading other people's scripts.

Whenever you set up and run an analysis, a file called design.fsf is output into each results directory; this contains everything you specified in the GUI, but in text format. This file can also be generated at any time by using the "Save" option within the FEAT GUI, and conversely, can be loaded using the "Load" option; this will fill in all of the fields as they were when you saved the design.fsf file.

The power of design.fsf comes from its commandline use. Simply type in "feat design.fsf" and it will execute every command inside the design.fsf file, the same as it would if you were to load it into the FEAT GUI and press the Go button.

Honestly, I am surprised that this feature is not showcased more in the FSL documentation; a couple of lines are devoted to its commandline usage in the FEAT basics section of the manual, but really they should emphasize this much more. (There is a good tutorial here about how to swap code within the design.fsf file and execute it with feat.) If you are new to Unix and need to get your feet wet, I suggest going through the following tutorials: One for basic Unix usage, the other for basics of shells scripting. This will be a new language to you, and as with any language, the beginning can be disorienting and overwhelming at times; however, stick with it, and I promise that the fog will begin to clear eventually, and you will discern what exactly it is you need to know when searching the help manuals, and what it is that you can disregard.

For those of you who have enough Unix background to feel comfortable reading scripts, here is something I created for a recent study I analyzed. This is a special case, since there were some runs where the participant was not exposed to a condition; in this case, for that regressor FSL requires you to specify the shape as "All Zeroes", something that we did not cover yet, but something that you should be aware of. The following script will check for whether the timing file is empty or not, and adjust the shape specification accordingly; however, it will also work for studies which have all regressors accounted for and do not have any missing data.

Here is the script, which can also be downloaded here; I apologize that the formatting is a little screwy with the margins:

#!/bin/bash

for run in 01 02 03 04
do
#Loops through all runs and replaces "ChangeMe" with run number

\cp design.fsf tmpDesign.fsf
sed -i -e 's/run01/runChangeMyRun/' tmpDesign.fsf
sed -i -e 's/FSL_01/FSL_ChangeMyRun/' tmpDesign.fsf #Replaces run placeholder with variable "ChangeMyRun"; this will be swapped later with the appropriate run number
iter=1 #Counter for running loops below
while [ $iter -le 11 ] do for timingFile in FSL_"$run"_EmotionRegAM.txt FSL_"$run"_EmotionRegAS.txt FSL_"$run"_EmotionRegNM.txt FSL_"$run"_EmotionRegNS.txt FSL_"$run"_EmotionResp1.txt FSL_"$run"_EmotionResp2.txt FSL_"$run"_EmotionResp3.txt FSL_"$run"_EmotionResp4.txt FSL_"$run"_EmotionResp5.txt FSL_"$run"_Instructions.txt FSL_"$run"_Relax.txt
do
if [ -s ../Timing/$timingFile ] then echo "File found; timing file is "$timingFile
sed -i -e 's/fmri(shape'$iter') 3/fmri(shape'$iter') 3/' tmpDesign.fsf
else
echo "File not found; timing file is " $timingFile sed -i -e 's/fmri(shape'$iter') 3/fmri(shape'$iter') 10/' tmpDesign.fsf fi iter=$(( $iter + 1)) done done \cp tmpDesign.fsf design_$run.fsf #Make a copy for each run
sed -i -e 's/ChangeMyRun/'$run'/' design_$run.fsf #Swap "ChangeMyRun" with run number
\rm *-e #Remove excess schmutz

Wednesday, July 11, 2012

Repost: Why Blogs Fail

 Pictured: One of the reasons why blogs fail

Blogger Neuroskeptic recently wrote a post about why blogs fail, observing what divides successful from unsuccessful blogs, and why the less successful ones ultimately stop generating new content or disappear altogether. Reading this made me reflect on why I started this in the first place; initially it was to write down, in blog-form, what I saw and heard at an AFNI workshop earlier this spring. Since then, I tried to give it a more coherent theme, by touching upon some fMRI methodology topics that don't get as much attention as they deserve, and creating a few walkthroughs to help new students in the field get off the ground, as there isn't much out there in the way of interactive videos showing you how to analyze stuff.

Analyzing stuff, in my experience, can be one of the most intimidating and paralyzing experiences of a graduate student's career; not because of laziness or incompetence, but because it is difficult to know where to start. Some of the obstacles that hinder the analysis of stuff (e.g., common mistakes involving experiment timing, artifacts that can propagate through an entire data set, not having a method for solving and debugging scripting errors) do not need to be repeated by each generation, and my main objective is to point out where these things can happen, and what to do about them. Of course, this blog contains other topics related to my hobbies, but overall, the theme of how to analyze stuff predominates.

In light of all of this, here is my pact with my readers: This blog will be updated at least once a week (barring any extreme circumstances, such as family emergencies, religious observations, or hospitalization from Nutella overdose); new materials, such as walkthroughs, programs, and instructional videos, will be generated on a regular basis; and I will respond to any (serious) questions posted in the comments section. After all, the reason I take any time out of my busy, Nutella-filled day to write any of this content is because I find it interesting and useful, and hope that somebody else will, too.

Tuesday, July 10, 2012

Chopin: Nocturne in E-flat Major

This is probably one of the best-known and best-loved out of all Chopin's nocturnes - rightly so. Although it has been overplayed to death, and although several performances suffer from excruciatingly slow tempi, no one can deny its elegance and charm.

The architecture is straightfoward enough: an A section which repeats, followed by a B section, then A again, then B, and a coda, in a form technically known as rounded binary. Chopin's genius lies in keeping the same harmonic foundation in each repeated section while progressively ornamenting the melody, finding ways to keep it fresh and exciting every time it returns. Finally, elements of both themes in the A and B sections are combined into a wonderful coda (listen for them!), becoming increasingly agitated until reaching an impassioned dominant, prepared by a c-flat anticipation held for an almost ridiculous amount of time.

Almost - Chopin, as well as Beethoven, is a master at reaching the fine line separating drama and melodrama, pathos and sentimentality, without going over the edge. The famous cadenza - a four-note motif marked senza tempo during which time stands still - repeats faster and faster, more and more insistent, until finally relenting, and finding its way back to a tender, emotional reconciliation with the tonic.

Enjoy!

Sunday, July 8, 2012

FSL Tutorial: Part 1 (of many)

I recently started testing out FSL to see if it has any advantages over other fMRI analysis packages, and decided to document everything on Youtube as I go along. The concepts are the same as any other package (AFNI, SPM, etc), but the terminology is slightly different, and driving it from the command line is not as intuitive as you would think. Plus, they use a ton of acronyms for everything, which, to be honest, kind of pisses me off; I don't like it when they try to be cute and funny like that. The quotes and sonnets generated by AFNI after exiting the program, however, are sophisticated and endearing. One of my favorites: "Each goodbye makes the next hello closer!"

In any case, here is the first, introductory tutorial I made about FSL. I realized from searching around on Youtube that hardly any fMRI analysis tutorial videos exist, and that this is a market that sorely needs to be filled. A series of walkthroughs and online lessons using actual data, in my opinion, would be far more useful at illustrating the fundamentals of fMRI data analysis than only having manuals (although those are extremely important as well, and I would recommend that anyone getting started in the field read them so that they can needlessly suffer as I did).

I will attempt to upload more on a regular basis, and start to get some coherent lesson plan going which allows the beginner to get off the ground and understand what the hell is going on. True story: It took me at least three years to fully comprehend what a beta weight was. Three years. I'm not going to blame it all on Smirnoff Ice, but it certainly didn't help.

Note: I suggest hitting fullscreen mode and viewing at a higher resolution (360p or 480p) in order to better see the text in the terminal window.

Also, the example data for these tutorials can be found here.

Tuesday, July 3, 2012

One of my hobbies is playing piano, and recently I bought the equipment to record sound from my electric piano. I own a Yamaha CLP-320 series, which has been an excellent piano and has held up remarkably well for the past three years.

The first recording uploaded from this piano is a nocturne by Chopin in B-flat minor,  opus 9, #1. I have had it in my repertoire for quite a while now, and it still remains my favorite nocturne out of all of them. I plan to upload more recordings with some regularity (e.g., every week or two), so be sure to check out the channel often to see what's new. Subscribing (or even just "liking") is a great way to help me out.

One feature of my videos is annotations which highlight certain interesting parts of the piece, such as important key modulations, any historical background that might be significant, and so on. I also think it looks cool when Chopin spits facts about his music. My goal is for it to be edifying rather than distracting; time will tell whether the public likes it or not.

Anyway, here's a link to the video. Enjoy!

[Edit 07.08.2012]: I removed the annotations, because I eventually found them distracting. Any notes will be placed in the "Description" box, as soon as I convince the recording companies that this indeed my own original work, and not a copy.

Sunday, July 1, 2012

Region of Interest Analysis

Before we get down to regions of interest, a few words about the recent heat wave: It's taken a toll. The past few days I've walked out the door and straight into a slow broil, that great yellowish orb pasted in the cloudless sky like a sticker, beating down waves of heat that saps all the energy out of your muscles. You try to get started with a couple miles down the country roads, crenelated spires of heat radiating from the blacktop, a thin rime of salt and dust coating every inch of your skin, and realize the only sound in this inferno is the soles of your shoes slapping the cracked asphalt. Out here, even the dogs have given up barking. Any grass unprotected by the shade of nearby trees has withered and died, entire lawns turned into fields of dry, yellow, lifeless straw. Flensed remains of dogs and cattle and unlucky travelers lie in the street, bones bleached by the sun, eyeless sockets gazing skyward like the expired votaries of some angry sun god.

In short, it's been pretty brutal.

Regions of Interest

Region of Interest (ROI) analysis in neuroimaging refers to selecting a cluster of voxels or brain region a priori (or, also very common, a posteriori) when investigating a region for effects. This can be done either by creating a small search space (typically a sphere with a radius of N voxels), or based on anatomical atlases available through programs like SPM or downloadable from web. ROI analysis has the advantage of mitigating the fiendish multiple comparisons problem, in which a search space of potentially hundreds of thousands of voxels is reduced to a smaller, more tractable area, thus reducing overly stringent multiple comparisons correction thresholds. At first glance this makes sense, given that you may not be interested in a whole brain analysis (i.e., searching for activation in every single voxel in the entire volume); however, it can also be abused to carry out confirmatory analyses after you have already determined where a cluster of activation is.

Simple example: You carry out a whole brain analysis, and find a cluster of fifty voxels extending over the superior frontal sulcus. This is not a large enough cluster extent to pass cluster correction at the whole brain level, but you go ahead anyway and perform an additional ROI analysis focused on the center of the cluster. There are not any real safeguards against this measure, as it is impossible to know what the researcher had in mind when they conducted the test. For instance, what if an investigator happened to simply make a mistake and see the results of a whole brain analysis before doing an ROI analysis? Pretend that he didn't see them? These are questions which may be addressed in a future post about a Bayesian approach to fMRI, but for now, be aware that there exists significant potential for misuse of this technique.

Non-Independence
Colloquially known as "double-dipping," non-independence has become an increasingly important issue over the years as ROI analyses have become more common (see Kriegeskorte et al, 2009, 2010).  In order to avoid biasing an ROI toward certain regressors, it is essential that the ROI and the contrast of interest share no common regressors. Consider a hypothetical experiment with three regressors: A, B, and C.  The contrast A-B is used to define an ROI, and the experimenter then decides to test the contrast of A-C within this ROI.  As this ROI is already biased toward voxels that are more active in response to regressor A, this is a biased contrast to conduct. This is not endemic only to fMRI data, but applies to any other statistical comparison where bias is a potential issue.

Correction for Multiple ROI Analyses
Ideally, each ROI analysis should be treated as an independent test, and should be corrected for multiple comparisons. It is better practice to have an a priori ROI that will be used for a single test, instead of exploring several ROIs and then correcting for multiple comparisons afterwards.

ROI Analysis in AFNI

Within AFNI, there exists a useful program called 3dUndump which requires x, y, and z coordinates (in millimeters), radius size of the sphere, and the master dataset where the sphere will be applied. A typical command looks like:

3dUndump -prefix (OutputDataset) -master (MasterDataset) -srad (Radius of Sphere, in mm) -xyz (X, Y, and Z coordinates of sphere)

One thing to keep in mind is the orientation of the master dataset. For example, the standard template that AFNI warps has a positive to negative gradient when going from posterior to anterior; in other words, values in the Y-direction will be negative when moving forward of the anterior commissure. Thus, it is important to note the space and orientation of the coordinates off of which you are basing your ROI, and make sure it matches up with the orientation of the dataset you are applying the ROI to. In short, look at your data after you have generated the ROI to make sure that it looks reasonable.

The following is a short Python wrapper I made for 3dUndump. Those already familiar with using 3dUndump may not find much use in it, but for me, having an interactive prompt is useful:

#!usr/bin/env python

import os
import math
import sys

#Read in Raw user input, assign to variables
print("MakeSpheres.py")
print("Created by Andrew Jahn, Indiana University 03.14.2012")
prefix = raw_input("Please enter the output filename of the sphere: ")
master = raw_input("Please enter name of master dataset (e.g., anat_final.+tlrc): ")
rad = raw_input("Please enter radius of sphere (in mm): ")
xCoord = raw_input("Please enter x coordinate of sphere (MNI): ")
yCoord = raw_input("Please enter y coordinate of sphere (MNI): ")
zCoord = raw_input("Please enter z coordinate of sphere (MNI): ")

#Make string of coordinates (e.g., 0 36 12)
xyzString = xCoord + " " + yCoord + " " + zCoord
printXYZString = 'echo ' + xyzString + ' > sphere_' + rad + 'mm_'+xCoord+'_'+yCoord+'_'+zCoord+'.txt'
os.system(printXYZString) #prints xyzstring to filename given above

#Will need sphere file in this format for makeSpheres function
xyzFile = 'sphere_' + rad + 'mm_'+xCoord+'_'+yCoord+'_'+zCoord+'.txt'

def makeSpheres(prefix, master, rad, xyz ):
cmdString = '3dUndump -prefix '+prefix+ ' -master '+master+' -srad '+rad+' -xyz '+xyz
os.system(cmdString)
return

Which will generate something like this (Based on a 5mm sphere centered on coordinates 0, 30, 20):

Beta values, time course information, etc., can then be extracted from within this restricted region.

ROI Analysis in SPM (Functional ROIs)

This next example will focus on how to do ROI analysis in SPM through MarsBar, a toolbox available here if you don't already have it installed. In addition to walking through ROI analysis in SPM, this will also serve as a guide to creating functional ROIs. Functional ROIs are based on results from other contrasts or interactions, which ideally should be independent of the test to be investigated within that ROI; else, you run the risk of double-dipping (see the "Non-Independence" section above).

After installation, you should see Marsbar as an option in the SPM toolbox dropdown menu:

1. Extract ROIs

After installing Marsbar, select it from the toolbox dropdown menu.  After Marsbar boots up, click on the menu “ROI Definition”.  Select “Get SPM clusters”.

This will prompt the user to supply an SPM.mat file containing the contrast of interest.  Select the SPM.mat file that you want, and click “Done”.

Select the contrast of interest just as you would when visualizing any other contrast in SPM.  Select the appropriate contrast and the threshold criteria that you want.

When your SPM appears on the template brain, navigate to the cluster you wish to extract, and click “current cluster” from the menu, underneath “p-value”.  Highlight the cluster you want in the SPM Results table.  The highlighted cluster should turn red after you select it.

Navigate back to the SPM results menu, and click on “Write ROIs”.  This option will only be available if you have highlighted a clutter.  Click on “Write one cluster”.  You can enter your description and label for the ROI; leaving these as default is fine.  Select an appropriate name for your ROI, and save it to an appropriate folder.

2. Export ROI

Next, you will need to convert your ROI from a .mat file to an image file (e.g., .nii or .img format).  Select “ROI Definition” from the Marsbar menu and then “Export”.

You will then be presented with an option for where to save the ROI.

Select the ROI you want to export, and click Done.  Select the directory where you wish to output the image.  You should now see the ROI you exported, with a .nii extension.

3. ROI Analysis

You can now use your saved image for an ROI analysis.  Boot up the Results menu as you would to normally look at a contrast, but when prompted for “ROI Analysis?”, select “Yes”. You can select your ROI from the “Saved File” option; alternatively, you can mask activity based on atlas parcellations by selecting the “Atlas” option.

The constriction of search space will mean fewer multiple comparisons need to be corrected for, and thus increases the statistical power of your contrast.