Showing posts with label FSL. Show all posts
Showing posts with label FSL. Show all posts

Wednesday, August 6, 2014

DTI Analysis: Soup to Nuts Playlist




Instead of going through each DTI analysis step individually, I've collated everything into a Youtube playlist down below. Just remember that we are using data from the FSL practical course here, and also remember that suing somebody for giving out bad advice, although it is admittedly an easy way to become fantastically wealthy, won't necessarily make you happier.

In any case, just to briefly go over the rest of the steps: After correcting for magnetic field distortions and eddy currents, tensors are fitted using the dtifit command (or simply going through the FDT menu in the FSL interface). Once this has been done for each subject, a series of TBSS tools are used, each one prefixed by "tbss"; for example, tbss_1_preproc, tbss_2_reg, and so on. (You can find all of these in the $FSLDIR/bin directory, and if you have a good handle on Unix programming, you can inspect the code yourself.) After you have run all of those for your dataset, you set up the appropriate experimental design and contrasts, and use the randomise tool to perform statistics in your tractography mask.

Keep in mind that this is just beginner's material; and that if you were to compare your DTI competence to dating, if would be like you were still in that awkward teenager phase, unable to talk to anybody or make eye contact.

However, much of this material has already been covered in other blogs and online resources, provided by several other highly talented scientists and researchers, and - as much as I constantly fantasize about establishing a monopoly over neuroimaging information - there is no practical way to destroy them all.

Therefore, instead of posting redundant information, I highly recommend checking out an ongoing step-by-step series on TORTOISE by Peter Molfese, which you can compare to your results with FSL, and another blog dedicated to diffusion imaging, diffusion-imaging.com. The latter site covers virtually every piece of diffusion imaging software and pipeline out there, and is a good place to start.


Monday, August 4, 2014

DTI Analysis, Steps 1 & 2: Distortion Correction and Eddy Correction

DTI data comes into this world just as we do - raw, unprocessed, unthresholded, and disgusting. Today's parents are much too easy on their children; back in my day, boys and girls were expected to correct their own erratic motion artifacts, to strip their own skulls when too much cranium started sprouting around their cortex, and reach significance through their own diligence and hard work. "No dinner for you until you've gotten rid of those filthy distortion currents on your hands, young man!" was a common saying around my household.

Unfortunately, these days we live in a society increasingly avoiding taking responsibility for their own actions, filled with people more and more unwilling to strip their own skulls. (Even though that would save neuroimaging researchers countless hours of preprocessing.) This trend is the result of several complex cultural and sociological factors, by which I mean: Lawyers. Things have gotten so bad that you could, to take a random example, potentially sue someone posting advice on an unlicensed website if following those instructions somehow messed up your data.

This actually happened to a friend of mine who publishes the nutrition blog tailored for Caucasian males, White Man's Secret. After one of his readers formed kidney stones as a result of following advice to drink a two-liter of Mello Yello every day, the author was sued for - and I quote from the court petition - "Twelve Bazillion Dollars."

In any case, DTI data takes some time to clean up before you can do any statistics on it. However, the preprocessing steps are relatively few, and are analogous to what is done in a typical FMRI preprocessing pipeline. The steps are to identify and correct any distortions during the acquisition, and then to correct for eddy currents.

The first step, distortion correction, can be done with FSL's topup command. Note that this will require two diffusion weighted images, one with the encoding direction in anterior-to-posterior direction (AP) and one encoded in the posterior-to-anterior direction (PA). You will also need a textfile containing information about the encoding directions and the total readout time (roughly the amount of time between the first echo and the last echo); for example, let's say we have a text file, acqparams.txt, containing the following rows:

0 -1 0 0.0665
0 1 0 0.0665

Here a -1 means AP, and 1 means PA. The last column is the readout time. If you have any questions about this, ask your scanner technician. "What if he's kind of creepy?" I don't care, girl; you gotta find out somehow.

While you're at it, also ask which image from the scan was the AP scan, and which was the PA scan. Once you have identified each, you should combine the two using fslmerge:

fslmerge -t AP_PA_scan AP_scan PA_scan 

Once you have that, you have all you need for topup:

topup --imain=AP_PA_scan --datain=acqparams.txt --out=topup_AP_PA_scan

This will produce an image, topup_AP_PA_scan, of where the distortions are located in your DTI scan. This will then be called by the eddy tool to undo any distortions at the same time that it does eddy correction.

The only other preparation you need for the eddy correction is an index list of where the acquisition parameters hold (which should usually just be a 1 for each row for each scan), and a mask excluding any non-brain content, which you can do with bet:

bet dwi_image betted_dwi_image -m -f 0.2

Then feed this into the eddy command (note that a bvecs and bvals image should be automatically generated if you imported your data using a tool such as dcm2niigui):

eddy --imain=dwi_image --mask=betted_dwi_image --index=index.txt --acqp=acqparams.txt --bvecs=bvecs --bvals=bvals --fwhm=0 --topup=topup_AP_PA_scan --flm=quadratic --out=eddy_unwarped_images

Note that the --fwhm and --flm arguments I chose here are the defaults that FSL recommends.

The differences before and after can be seen in fslview:




Of course, the distortion correction step isn't strictly necessary; and you can still do a much simpler version of eddy correction by simply selecting FDT Diffusion from the FSL menu and then selecting the Eddy Correction tab, which only requires input and output arguments. All I'm saying is that, if you're feeling particularly litigious, you should probably be safe and do both steps.



Wednesday, July 30, 2014

Introduction to Diffusion Tensor Imaging: From Hospital Horror Story to Neuroimaging

It is well known that one of the deepest human fears is to be a patient in a hospital late at night, all alone, while a psychotic nurse injects you with a paralyzing agent, opens up your skull with a bone saw, and begins peeling away layers of your cortex while you are still awake.*

As horrifying as this nightmare scenario may be, it also lends an important insight into an increasingly popular neuroimaging method, diffusion tensor imaging (DTI; pronounced "diddy"). To be more gruesomely specific, the psychotic nurse is able to peel away strips of your brain because it has preferred tear directions - just like string cheese. These strips follow the general direction of fascicles, or bundles of nerves, comprising grey and white matter pathways; and of these pathways, it is white matter that tends to exhibit a curious phenomenon called anisotropy.

Imagine, for example, that I release a gas - such as, let's say, deadly neurotoxin - into a spherical compartment, such as a balloon. The gas, through a process called Brownian motion (not to be confused with the Dr. Will Brown frequently mentioned here) will begin to diffuse randomly in all directions; in other words, as though it is unconstrained.

However, release the same gas into a cylindrical or tube-shaped compartment, such as one of those cardboard tubes you used to fight with when you were a kid,** and the gas particles will tend to move along the direction of the tube. This is what is known as anisotropy, meaning that the direction of the diffusion tends to go in a particular direction, as opposed to isotropy, where diffusion occurs in all directions with equal probability.


Left two figures: Ellipsoids showing different amounts of anisotropy, with lambda 1, 2, and 3 symbolizing eigenvalues. Eigenvalues represent the amount of diffusion along a particular direction. Right: A sphere representing isotropy, where diffusion occurs with equal probability in all directions.

This diffusion can be measured in DTI scans, which in turn can be used to indirectly measure white matter integrity and structural connectivity between different areas of the brain. A common use of DTI is to compare different populations, such as young and old, and to observe where fractional anisotropy (FA) differs between groups, possibly with the assumption that less FA can be indicative of less efficient communication between cortical regions. There are other applications as well, but this is the one we will focus on for the remainder of the tutorials.

The data that we will be using can be found on the FSL course website, after scrolling down to Data Files and downloading File 2 (melodic and diffusion). I haven't been able to find any good online repositories for DTI data, so we'll be working with a relatively small sample of three subjects in one group, and three subjects in the other. Also note that while we will focus on FSL, there are many other tools that process DTI data, including some new commands in AFNI, and also a program called TORTOISE. As with most things I post about, these methods have already been covered in detail by others; and in particular I recommend a blog called blog.cogneurostats.com, which covers both the AFNI and TORTOISE approaches to DTI, along with other tutorials that I thought I had been the first to cover, but which have actually already been discussed in detail. I encourage you to check it out - but also to come back, eventually.



*Or maybe that's just me.
**And maybe you still do!

Wednesday, June 4, 2014

Introduction to Independent Components Analysis

In the course of your FMRI studies, you may have at one point stumbled upon the nightmarish world of Independent Components Analysis (ICA), an intimidating-sounding technique often used by people who know far more than I do. Nevertheless, let us meditate upon it and see what manner of things we have here.

Components are simpler building blocks of a more complex signal. For example, in music, the soundwave profiles of chords can appear very complex; yet a Fourier analysis can filter it back into its constituent parts - simpler sine waves associated with each note that, combined together, create the chord's waveform.



A similar process happens when ICA is applied to neuroimaging data. Data which comes right off the scanner is horribly messy, a festering welter of voxels and timecourses that any right man would run away from as though his very life depended upon it. To make this more comprehensible, however, ICA can decompose it into more meaningful components, each one explaining some amount of the variance of the overall signal. 

Note also that we talk of spatial and temporal components, which will be extracted from each other; this may seem somewhat odd, as the two are inseparable in a typical FMRI dataset: each voxel (the spatial component) has a timecourse (the temporal component). However, ICA splits these apart and recombines them, in descending order, into components that explain the amount of variance of the original spatio-temporal maps. This is what is represented in the figures shown on the FSL website, reprinted below:



After these components have been extracted, something happens that some (like me) consider terrifying: You need to identify the components yourself, assigning each one to whatever condition seems most reasonable. Does that one look like a component related to visual processing? Then call it the visual component. Does that one look like a resting-state network? Then call it a resting-state network component. This may all seem rather cavalier, especially considering that you are the one making the judgments. Seriously; just think about that for a moment. Think about what you've done today.

In any case, that is a brief overview of ICA. To be fair, there are more rigorous ways of classifying what components actually represent - such as creating templates for connectivity networks or activation patterns and calculating the amount of fit between that and your component - but to be honest, you probably don't have the motivation to go through all of that. And by you, I mean me.


Next we will work through the example datasets on FSL's website, discussing such problems as over- and under-fitting, the Melodic GUI, and what options need to be changed; followed by using ICA to analyze resting-state data.

Friday, May 30, 2014

Automating 3dReHo

As a rider to our tale of Regional Homogeneity analysis, we last discuss here how to automate it over all the subjects of your neuroimaging fiefdom. Much of this will look similar to what we have done with other analyses, but in case you don't know where to start, this should help get you going.


#!/bin/tcsh

setenv mask mask_group #Set your own mask here
setenv subjects "0050773 0050774" #Replace with your own subject numbers within quotations

foreach subj ($subjects)

cd {$subj}/session_1/{$subj}.results #Note that this path may be different for you; change accordingly

3dReHo -prefix ReHo_{$subj} -inset errts.{$subj}+tlrc -mask mask_group+tlrc #Perform Regional Homogeneity analysis

#Convert data to NIFTI format
3dAFNItoNIFTI ReHo_{$subj}+tlrc.HEAD
3dAFNItoNIFTI {$mask}+tlrc.HEAD

#Normalize images using FSL commands
setenv meanReHo `fslstats ReHo_{$subj}.nii -M`
setenv stdReHo `fslstats ReHo_{$subj}.nii -S`

fslmaths ReHo_{$subj}.nii -sub $meanReHo -div $stdReHo -mul mask_group.nii ReHo_Norm_{$subj}

gunzip *.gz

#Convert back to AFNI format
3dcopy ReHo_Norm_{$subj}.nii ReHo_Norm_{$subj}

end

Sunday, May 18, 2014

ReHo Normalization with FSL

As a brief addendum to the previous post, ReHo maps can also be normalized using FSL tools instead of 3dcalc. Conceptually, it is identical to what was discussed previously; however, the ability to set variables as the output of FSL commands makes it more flexible for shell scripting. For example, using the same datasets as before, we could set the mean and standard deviation to variables using the following combination of AFNI and FSL commands:

3dAFNItoNIFTI ReHo_Test_Mask+tlrc
3dAFNItoNIFTI mask_group+tlrc

setenv meanReHo `fslstats ReHo_Test_Mask.nii -M`
setenv stdReHo `fslstats ReHo_Test_Mask.nii -S`
fslmaths ReHo_Test_Mask.nii -sub $meanReHo -div $stdReHo -mul mask_group.nii ReHo_Norm
gunzip *.gz
3dcopy ReHo_Norm.nii ReHo_Norm


An explanation of these commands is outlined in the video below. Also, suits!


Thursday, August 8, 2013

Future Functional Connectivity Tutorials, and Other Updates

A few notes:

1) The previous functional connectivity posts and tutorials are cribbed from Gang Chen's homepage, which is available here. Kind of like the way I crib quotations and passages from authors that no one reads anymore, and then pass it off as my own style to boost my pathologically low self-esteem. Keep in mind that most of these demonstrations deal with a single subject and simplified situations that you probably will not encounter in your research. Given these contrived examples, most of the results generated in these demos are relatively meaningless; it's up to you to learn and understand the concepts, and then apply them to your own data and make your own inferences. My task which I am trying to achieve is, by the power of Youtube tutorials, to make you hear, to make you feel — it is, before all, to make you understand. That — and no more, and it is everything. (That was Conrad, by the way.)

2) A lot of you - I'm talking a LOT of you players - have been making requests for MELODIC tutorials and resting state analyses in FSL. All I can say is, we'll get there, in time. Before that, however, I believe AFNI is better suited for building up one's intuition, and so we will be working through a few more connectivity topics in AFNI - specifically, context-dependent correlations, beta series correlations, and resting state connectivity. After that we will again cover the same concepts, but applied in FSL - by which time, given my glacial pace, either FMRI will have become a passé technique or the Andromeda galaxy will have crashed into us.

3) Recently you may have noticed the "Donate" button on the right sidebar of the blog. This was done at the request of one reader who felt the powerful, irrational urge to loosen his purse-strings and give some alms out of the goodness of his heart, which is located somewhere way, way down there, somewhere nearabouts the cockles. Although I can't fully understand this behavior - even less than I can understand why there is someone who still has purse-strings, or what cockles are, exactly - nevertheless it helps satisfy my cupidity and strokes my ego. Furthermore, in addition to serving Mammon, these tokens of gratitude motivate me to regularly produce new material and, as a bonus, help me to continue procrastinating on my dissertation. Now that's what I call a win-win-win.

4) Also, at least one of you has mailed me a two-pack of Nutella. This has pleased me greatly. My brain needs hazelnut spread for fuel, and the more it has, the hotter and better it burns.

5) If everything goes according to plan, we should cover context-dependent correlations this weekend, beta series correlations next week, and resting-state connectivity the week after that.

Lunch in Paris, dinner in London, comrade.

Monday, May 20, 2013

Combining ROIs

Once you've used a tool like fslmaths, 3dcalc, or Marsbar to create a single ROI, you can combine several of these ROIs using the same tools. This might be useful, for example, when creating a larger-scale masks encompassing several different areas.

In each case, combining ROIs is simply a matter of creating new images using a calculator-like tool; think of your TI-83 from the good old days, minus those frustrating yet addictive games such as FallDown. (Personal record: 1083.) With fslmaths, use the -add flag to concatenate several different ROIs together, e.g.:

fslmaths roi1 -add roi2 -add roi3 outputfile

With AFNI:

3dcalc -a roi1 -b roi2 -c roi3 -expr '(a+b+c)' -prefix outputfile

With Marsbar is a bit more involved, but also easier since you can do it from the GUI, as shown in the following video.




Many thanks to alert reader Anonymous, who is both too cool to register a username and once scored a 1362 on FallDown. Now all you gotta do is lay back and wait for the babe stampede!

Friday, May 10, 2013

Parameter Extraction in AFNI: 3dmaskave and 3dmaskdump

Previously we showed how to extract parameters using Marsbar in SPM and featquery in FSL, and the concept is identical for AFNI. Once you have created a mask (e.g., using 3dUndump or 3dcalc), you can then extract parameter estimates from that ROI either using the tool 3dmaskave or 3dmaskdump.
3dmaskave is quicker and more efficient, and is probably what you will need most of the time. Simply supply a mask and the dataset you wish to extract from, and it will generate a single number of the average parameter estimate across all the voxels within that ROI. For example, let's say that I want to extract beta weights from an ROI centered on the left nucleus accumbens, and I have already created a 5mm sphere around that structure stored in a dataset called LeftNaccMask+tlrc. Furthermore, let's say that the beta weights I want to extract are in a beta map contained in the second sub-brik of my statistical output dataset. (Remember that in AFNI, sub-briks start at 0, so the "second" sub-brik would be sub-brik #1.) To do this, use a command like the following:

3dmaskave -mask LeftNaccMask+tlrc stats.202+tlrc'[1]'

This will generate a single number, which is the average beta value across all the voxels in your ROI.

The second approach is to use 3dmaskdump, which provides more information than 3dmaskave. This command will generate a text file that contains a single beta value at each voxel within the ROI. A couple of useful options are -noijk, to suppress the output of voxel coordinates in native space, and -xyz, to output voxel coordinates in the orientation of the master dataset (usually in RAI orientation). For example, to output a list of beta values into a text file called LeftNaccDumpMask.txt,

3dmaskdump -o LeftNaccDumpMask.txt -noijk -xyz -mask LeftNaccMask+tlrc stats.202+tlrc'[1]'

This will produce a text file that contains four columns: The first three columns are the x-, y-, and z-coordinates, and the fourth column is the beta value at that triplet of coordinates. You can take the average of this column by exporting the text file to a spreadsheet like Excel, or use a command like awk from the command line, e.g.

awk '{sum += $4} END {print "Average = ", sum/NR}' LeftNaccDumpMask.txt


Keep in mind that this is only for a single subject; when you perform a second-level analysis, usually what you will want to do is loop this over all of the subjects in your experiment, and perform a statistical test (e.g., t-test) on the resulting beta values.






Concluding Unscientific Postscript

I recently came across this recording of Schubert's Wanderer Fantasie, and I can't help but share it here; this guy's execution is damn near flawless, and, given both the time of the recording and some of the inevitable mistakes that come up, I have good reason to believe it was done in a single take. It's no secret that I do not listen to that much modern music, but it isn't that modern music is bad, necessarily; it's just that classical music is so good. Check out the melodic line around 16:30 to hear what I'm talking about.



Saturday, April 27, 2013

FSL Tutorial: Creating ROIs from Coordinates

Previously we covered how to create regions of interest (ROIs) using both functional contrasts and anatomical landmarks; however, FSL can also create spheres around voxel coordinates, similar to AFNI's 3dcalc or SPM's marsbar.

  1. Step one is to find the corresponding voxel coordinates for your MNI coordinates, which may be based on peak voxel activation from another study, for example; to do this, open up FSLview, type in your MNI coordinates, and write down the corresponding voxel coordinates (these are shown in the bottom-left corner of FSLview). 
  2. After you have written down your voxel coordinates, create a point at those coordinates using the fslmaths command. This command requires the template space that you warped to, as well as the actual x-, y-, and z-coordinates corresponding to the MNI coordinates. Give the output file a name, and make sure that the output data type ('odt') is set to float. (Example command: fslmaths avg152T1.nii.gz -mul 0 -add 1 -roi 45 1 74 1 51 1 0 1 ACCpoint -odt float)
  3. Using fslmaths again, input the file containing the point created in the previous step, and specify a sphere of radius N (in millimeters) to expand around that point. Use the -fmean command, for reasons that are to remain mysterious, and provide a label for your output data set. (Example command: fslmaths ACCpoint -kernel sphere 5 -fmean ACCsphere -odt float)
  4. Update on 5/18/2016: To make it a binary mask, execute one more command: fslmaths ACCsphere.nii.gz -bin ACCsphere_bin.nii.gz. The previous step creates a sphere, but with small intensities; this can be problematic if you do a featquery analysis that allows weighting of the image.

Once that is all done, use fslview to open up a template in your normalized space, and overlay your newly created sphere; double-check to make sure that it is in roughly the location where you think it should be. Now you can extract data such as parameter estimates from this ROI, using techniques similar to those covered in previous tutorials about ROIs.

Thanks to alert viewer danieldickstein, which, due to its juvenile reference to the male member, cannot possibly be his real name. Grow up, Daniel.


Wednesday, November 21, 2012

Let's Talk about Masks (Live Video)

I've been experimenting more with Camtasia, and I've uploaded a new video showing how masks are drawn on an actual human, rubber brain, which involves the use of R studio, Excel, and colored pens. My hope is that this makes the learning experience more interactive; in addition, you get to see what my mug looks like.


Tuesday, November 20, 2012

FSL Tutorial: Featquery_gui

Now that we've created our masks, we can go ahead and extract data using FSL's featquery tool. You may want to run it from the command line when batching large numbers of subjects, but this tutorial will focus on Featquery_gui, a graphical interface for loading subjects and ROIs, and then performing data extraction from that ROI. The procedure is similar to Marsbar, and I hope that the video is clear on how to do this.

Also, I've attached a Black Dynamite video for your enjoyment. Nothing to do with ROIs, really, but we all need a break now and then.




A Note about FMRI Masks



Now that we have covered how to create masks using three separate software packages - FSL, SPM, and AFNI - I should probably take a step back and talk about what masks are all about. When I first read about masks, all I heard was a bunch of mumbo jumbo about zeros and ones, and unhelpful saran wrap metaphors. While this did remind me to purchase valuable kitchen supplies, it was unhelpful in understanding what a mask was, exactly, and how it was used.

Simply put, a mask is a subset of voxels you wish to analyze. Let's say I'm only interested in the right hemisphere of the brain; to create a mask of the right hemisphere, imagine using a papercutter to split the brain in half, and only taking the right hemisphere for further analysis, while discarding the left hemisphere into the trash can. The generation of masks follows this same logic - only focus on a specific part of the brain, and discard the rest.

Fortunately, we have come a long way since using office supplies to create masks, and now we have computers to do it for us. In order to create a mask using any of the listed software packages, usually you will use a tool to insert "1's" into the voxels that you wish to analyze, and "0's" everywhere else. Then, say that you want to do an ROI analysis only on those voxels that contain "1's". If you are trying to extract contrast estimates for a subject, the contrast estimate at each voxel will be multiplied by the mask, and you will be left with the contrast estimates in the "1's" voxels (since each estimate is being multiplied by 1), and zeros everywhere else.

Furthermore, ROI extraction within a mask often averages the contrast (or parameter) estimates across all of the voxels inside the mask. It is also possible to extract estimates from single voxels or a single triplet of coordinates - just think of this as ROI analysis of a very small mask.

I hope that this clarifies things a bit; I know that it took me a couple of years to wrap my head around the whole concept of masks and ROIs and severing hemispheres from each other. However, once you understand this, the whole process of ROI interrogation becomes much simpler and more intuitive, and analyses become easier to carry out. ROI analysis is the foundation for carrying out more complex analyses, such as double dissociations and connectivity analyses, and it is well to become familiar with this before tackling larger game.

Monday, November 19, 2012

Creating Masks In FSL

Due to a high number of requests (three), I have made some walkthroughs about how to create masks in FSL. There are a few different ways to do this:

  1. Anatomical ROI: These masks are generated from anatomical regions labeled by atlases. For example, you may decide to focus only on voxels within the V1 area of visual cortex. Using an atlas will create a mask of that region, based on the atlas-defined anatomical boundaries in a standardized space.
  2. Functional ROI (or contrast ROI): This is a mask created from a contrast thresholded at a specific statistic value. For example, you may wish to focus only on voxels that pass cluster correction for the contrast of left button presses minus right button presses.
  3. Painting ROIs: This is where the real fun starts; instead of being confined by the limitations of anatomical or contrast boundaries, let your imagination run wild and simply paint where you want to do an ROI analysis. Similar to what you did in first grade, but more high-tech and with less puking after eating your crayons. (Is it my fault that Razzmatazz Red sounds so delicious?)
Demonstrations of each approach can be found in the following videos:

 Anatomical ROIs

Functional ROIs

 ROIs created from FSLview. Pretend like you're Bob Ross.

Thursday, October 18, 2012

When Stuff Goes Wrong

One complaint I have with FMRI tutorials and manuals is this: The user is provided a downloadable dataset and given a tutorial to generate a specific result. There is some commentary about different aspects of the analysis pipeline, and there might be a nod to artifacts that show up in the data. But for the most part things are expected to be more or less uneventful, and if anything goes wrong during the tutorial, it is likely because your fat fingers made a typo somewhere. God, you are fat.

Another thing: When you first read theory textbooks about fMRI data analysis, a few boogie men are mentioned, such as head motion or experimental design confounds. However, nothing is mentioned about technicians or RAs screwing stuff up, or (more likely) you yourself screwing stuff up. Not because you are fat, necessarily, but it doesn't help.

Bottom line: Nobody tells you how to respond when stuff goes wrong - really wrong - which it inevitably will.

No, I'm not talking about waking up feeling violated next to your frat brother; I'm talking about the millions of tiny things that can derail data acquisition or data analysis or both. This can end up costing your lab and the American taxpayer literally thousands - that's thousands, with a "T" - of dollars. No wonder the Tea Party is pissed off. And while you were hoping to get that result showing that conservatives/liberals exhibit abnormal neural patterns when shown pictures of African-Americans, and are therefore bigoted/condescending scum that deserve mandatory neural resocialization, instead you end up with a statistical map of blobs that looks like the frenetic finger-painting of a toddler tripping balls from Nutella overdose. How could this happen? Might as well go ahead and dump all seventy activation clusters in a table somewhere in the supplementary material where it will never see the light of day, and argue that the neural mechanisms of prejudice arise from the unfortunate fact that the entire brain is, indeed, active. (If this happens, just use the anodyne phrase "frontal-parietal-temporal-occipital network" to describe results like these. It works - no lie.)

How to deal with this? The best approach, as you learned in your middle school health class, is prevention. (Or abstinence. But let's get real, kids these days are going to analyze FMRI data whether we like it or not, the little minks.) Here are some prophylactic measures you can take to ensure that you do not get scalded by unprotected data analysis:

1) Plan your experiment. This seems intuitive, but you would be surprised how many imaging experiments get rushed out the door without a healthy dose of deliberative planning. This is because of the following reasons:
  1. You will probably get something no matter what you do.
  2. See reason #1
2) Run a behavioral pilot. Unless the neural mechanism or process is entirely cognitive and therefore has no behavioral correlate (e.g., instructing the subject to fantasize about Nutella), try to obtain a performance measure of your conditions, such as reaction time. Doing this will also reinforce the previous point, which is to plan out your experiment. For example, the difference in reaction time between conditions can provide an estimate of how many trials you may need during your scanning session, and also lead to stronger hypotheses about what regions might be driving this effect.

3) Have a processing stream already in place before the data starts rolling in. After running your first pilot subject, have a script that extracts the data and puts everything in a neat, orderly file hierarchy. For example, create separate directories for your timing data and for your raw imaging data.

4) As part of your processing stream, use clear, understandable labels for each new analysis that you do. Suffixes such as "Last", "Final", "Really_The_Last_One", and "Goodbye_Cruel_World", although optimistic, can obscure what analysis was done when, and for what reason. This will protect you from disorganization, the bane of any scanning experiment.

5) Analyze the hell out of your pilot scan. Be like psychopath federal agent Jack Bauer and relentlessly interrogate your subject. Was anything unclear? What did they think about the study, besides the fact that it was so boring and uncomfortable that instead of doing it again they would rather have a vasectomy with a weed-whipper? You may believe your study is the bomb, but unless the subject can actually do it, your study is about as useful as a grocery bag full of armpit hair.

6) Buy a new printer. Chicks dig guys with printers, especially printers that print photos.

Your ticket to paradise

7) Check the results of each step of your processing stream. After you've had some experience looking at brain images, you should have an intuition about what looks reasonable and what looks suspect. Knowing which step failed is critical for troubleshooting.

8) Know how to ask questions on the message boards. AFNI, SPM, and FSL all have excellent message boards and listservs that will quickly answer your questions. However, you should make your question clear, concise, and provide enough detail about everything you did until your analysis went catastrophically wrong. Moderators get pissed when questions are vague, whiny, or unclear.

9) When all else fails, blame the technicians. FMRI has been around for a while now, but the magnets are still extremely large and unwieldy, cost millions to build and maintain, and we still can't get around the temporal resolution-spatial resolution tradeoff. Clearly, the physicists have failed us.


These are just a few pointers to help you address some of the difficulties and problems that waylay you at every turn. Obviously there are other dragons to slay once you have collected a good sample size and need to plan your interpretation and possible follow-up analysis. However, devoting time to planning your experiment and running appropriate behavioral studies can go a long way toward mitigating the suffering and darkness that follows upon our unhappy trade.

Saturday, October 13, 2012

FSL Tutorial 8: FAST

For countless aeons did neuroscientists burn with the perverse desire to segment human brains apart in vivo, while the juicy glands still pulsated with life within their unfortunate hosts. Numerous methods were attempted, as crude as they were unnatural - paint scrapers, lint rollers, zesters - but without success. And the neuroscientists did curse and they did rage and they did utter blasphemy of such wickedness as to make the ears of Satan himself bleed. With the terrible advent of FMRI did that all change; now, the tissue of the brain, the seat of consciousness, could be blasted apart while leaving its host intact; now could the grey be separated from the white, the gold from the dross. And then did the neuroscientists go down and slay the Canaanites, thirty thousand in number, and not a man survived as the neuroscientists did wade through swales of blood covered with the skins of their enemies and their eyes burned centroids of murder.

So goes the story of the creation of FAST. The tool is straightforward: Provide a skullstripped brain, decide how many tissue classes you wish to segment, and the rest of the defaults are usually fine. Often a researcher will want three tissue classes: White matter, grey matter, and cerebrospinal fluid (CSF). However, if you are dealing with a subject that presents with a brain abnormality, such as a lesion, you may want to increase the number of classes to four in order to segment the lesion into its own class.

FAST outputs a dataset for each tissue type. For example, if three tissue types have been segmented, there will be three output datasets, one corresponding to each tissue class; each dataset is a mask for each tissue type, and contains a fraction estimate at each voxel. The picture below shows a grey matter mask segmented with FAST. The intensity at the voxel centered at the crosshairs is 0.42, meaning that 42% of that voxel is estimated to be grey matter; presumably, the other 58% is white matter, as the voxel lies at the boundary between the head of the caudate nucleus (a grey matter structure), and the internal capsule (which is composed of white matter).


For some packages such as SPM, tissue masks can be used for normalization. For example, the grey matter and white matter masks will be normalized to mask templates in a standard space, such as MNI, and these warping parameters are then applied to the functional runs. However, the volume of these masks can also be calculated and compared across subjects or across groups. In order to calculate the total grey matter volume within a mask, for example, fslstats can be used:

fslstats s007a1001_brain_pve_1.nii.gz -M -V | awk '{ print $1 * $3 }'

This will return the volume of the mask in cubic millimeters; the same operation can be applied to the other masks by substituting s007a1001_brain_pve_1 with a different class (e.g., either 0 or 2).

However, for more sophisticated voxel-based morphometry comparing volumetric differences between focal cortical areas or specific subcortical structures, I recommend FreeSurfer. Brain segmentation is part of the default processing stream in FreeSurfer, and the volume of each area is output into a formatted table. This will be covered in a later tutorial; for now, use FAST and appreciate its bloody, violent history.

Wednesday, October 10, 2012

FSL 5.0 Released

I don't know how I missed this, but last month a major version of FSL was released: 5.0. This means that:
  1. Everything I had previously written about FSL is now obsolete, and you were a fool to read it; and
  2. There have also been changes to processing anatomical datasets, field maps, and independent component analysis, which look interesting. Interesting, as in, I don't completely understand all the changes they made, but they look impressive.
I haven't had much time to sink my paws into it, but it looks similar to FSL 4.x. More details to come.

Sunday, September 16, 2012

Slice Timing Correction

fMRI suffers from the disease of temporal uncertainty. The BOLD response is sluggish and unreliable; cognitive processes are variable and are difficult to model; and each slice of a volume is acquired at a different time. This last symptom is addressed by slice-timing correction (STC), which attempts to shift the data acquired at each slice in order to align them at the same time point. Without it, all would be lost.

Figure stolen from Sladky et al (2011): Assuming that the BOLD response is roughly equivalent across slices, each successive slice samples a different timepoint. STC rectifies this by interpolating what the value at time zero would have been if all slices had been acquired simultaneously.


"Madness!" you cry; "How can we know what happened at a time point that was not directly measured? How can we know anything? Is what I perceive the same as what everybody else perceives?" A valid criticism, but one that has already been hunted down and crushed by temporal interpolation - the estimation of a timepoint by looking at its neighbors. "But how reliable is it? Will the timecourse not be smoothed by simply averaging the neighboring points?" Then use a higher-order interpolation, whelp, and be silent.

The merits of STC have been debated, as well as when it should be used in the preprocessing stream. However, it is generally agreed that STC should be included in order to reduce estimation bias and increase sensitivity (Sladky et al, 2011; Calhoun et al, 2000; Hensen et al, 1999), and that it should occur before volume coregistration or any other spatial interpolations of the data. For example, consider a dataset acquired at an angle from the AC/PC line (cf. Deichmann et al, 2004): If STC is performed after realigning the slices to be parallel to the AC/PC line, then the corresponding slices for each part of the brain are altered and temporal interpolation becomes meaningless; that way lies darkness and suffering.

If unnecessary interpolations offend your sensibilities, other options are available, such as incorporating temporal derivatives into your model or constructing regressors for each slice (Hensen et al, 1999). However, standard STC appears to be the most straightforward approach and the lowest-maintenance relative to the other options.

Slice-Timing Correction in AFNI is done through 3dTshift. Supply it with the following:

  1. The slice you wish to align to (usually either the first, middle, or last slice);
  2. The sequence in which the slices are acquired (ascending, descending, sequential, interleaved, etc.);
  3. Preferred interpolation (the higher-order, the better, with Fourier being the Cadillac of interpolation methods); and
  4. Prefix for your output dataset.

Sample command:
3dTshift -tzero 0 -tpattern altplus -quintic -prefix tshift [[input dataset goes here]]

More details, along with an interactive example of how STC works, can be found in the following tutorial video.




Saturday, September 1, 2012

Unix for Neuroimagers: For Loops and Shell Scripting

With this tutorial we begin to enter into AFNI territory, as the more advanced Unix commands and procedures are necessary for running an AFNI analysis. First, we cover the basics of for loops. For loops in fMRI analysis are used to loop over subjects and execute preprocessing and postprocessing scripts for each subject individually. (By the way, I've heard of preprocessing and I've heard of postprocessing; but where does plain, regular processing take place? Has anyone ever thought of that? Does it ever happen at all? I feel like I'm taking crazy pills here.)

Within the t-shell (and I use the t-shell here because it is the default shell used by AFNI), a for loop has the following syntax:


foreach [variableName] ( [var1] [var2]...[varN])
     
     [Executable steps go here]

end



So, for example, if I wanted to loop over a list of values and have them assigned to variable "x" and then return those values, I could do something like the following:

foreach x (1 2 3 4 5)
    
     echo $x

end

Which would return the following:

1
2
3
4
5

Notice in this example that the for loop executes the line of code "echo $x", and assigns a new value to x for each step of the for loop. You can imagine how useful this can be when extended to processing individual subjects for an analysis, e.g.:

foreach subj ( subj1 subj2 subj3...subjN )

    tcsh afni_proc.py $subj

end


That is all you need to process a list of subjects automatically, and, after a little practice, for loops are easy and efficient to use. The same logic of for loops applies to FSL analyses as well, if you were to apply a feat or gfeat command to a list of feat directories. In the next batch of tutorials, we will begin covering the basics of AFNI, and eventually see how a typical AFNI script incorporates the use of for loops in its analysis.

The second part of the tutorial covers shell scripting. A shell script executes a series of commands within a text file (or, more formally, shell script), allowing the user more flexibility in applying a complex series of commands that would be unwieldy to type out in the command line. Just think of it as dumping everything you would have typed out explicitly into the command line, into a tidy little text file that can be altered as needed and executed repeatedly.

Let us say that we wish to execute the code in the previous example, and update it as more subjects are acquired. All that would be added would be a shebang, in order to specify the shell syntax used in the script:

#!/bin/tcsh

foreach subj (subj1 subj2 subj3)

     tcsh afni_proc.py $subj

end


After this file has been saved, make sure that it has executable permissions. Let's assume that the name of our shell script is AFNI_procScript.sh; in order to give it executable permissions, simply type

chmod +x AFNI_procScript.sh

And it should be able to be run from the command line. In order to run it, type the "./" before the name of the script, in order to signify that it should be executed from the shell, e.g.:

./AFNI_procScript.sh

Alternatively, if you wish to override the shebang, you can type the name of the shell you wish to execute the script. So, for example, if I wanted to use bash syntax, I could type:

bash AFNI_procScript.sh

However, since the for loop is written in t-shell syntax, this would return an error.


Due to popular demand, an optseq tutorial will be uploaded tomorrow. Comparisons between the output of optseq and AFNI's 1d_tool.py is encouraged, as there is no "right" sequence of stimulus presentations you should use; only reasonable ones.


Saturday, August 25, 2012

Unix for Neuroimagers: Shells and Variables

First, a few updates:

1) We just finished our first week of the semester here, and although things haven't been too busy, it may be a couple of weeks before I get back on a steady updating schedule. I'll do what I can to keep dropping that fatty knowledge on the regular, and educating your pale, soy-latte-white, Famous Dave's BBQ-stained faces on how to stay trill on that data and stack that cheddah to the ceiling like it's your job. And if you got one of those blogs dedicated to how you and your virgin-ass Rockband-playing frat brothers with names like Brady and Troy and Jason eating those cucumber salad sandwiches or whatever and you drop a link to this site, I'll know it. You show me that love, and I show it right the hell back.

2) While you're here, how about you donate a piece of that stack to the American Cancer Society. I mean, damn; I'm out there seven days a week on those roads, sweating and suffering, but you - you're at work procrastinating again, wringing your snow-bunny white hands over whether you should drop out of graduate school or just toughen it out and graduate in eight years, and while you're at it possibly take a swipe at that new Italian breezey who just entered the neuroscience program. Donate first, worry about those problems later.

3) We got another performance for you all this November, including Schumann's Adagio and Allegro for cello and piano, Resphigi's Adagio con Variazioni, and the Debussy cello sonata. Time and location TBA. Also, more music videos will be uploaded soon, but while you're waiting, you can listen to the latest Mozart Fantasie in D Minor, which has proved one of my most popular videos to date; last I checked, it had 57 views, which I think qualifies for viral status. We goin' worldwide, baby! World-WIDE!!

4) AFNI tutorials are next on the docket, after wrapping up the intro Unix tutorials for neuroimagers, and possibly doing a couple more FSL tutorials on featquery, FSL's ROI analysis tool. Beyond that, there isn't much else I have to say about it; now that you've mastered the basics, you should be able to get the program to jump through whatever hoops you set up for it and to do whatever else you need. There are more complex and sophisticated tools in FSL, to be sure, but that isn't my focus; I will, on the other hand, be going into quite a lot of details with AFNI, including how to run functional connectivity and MVPA analyses. It will take time, but we will get there; as with the FSL tutorials, I'll start from the bottom up.


Anyway, the latest Unix tutorial covers the basics on shells and variables. Shells are just ways of interfacing with the Unix OS; different shells, such as the t-shell (tcsh) and bash shell, do the same thing, but have different syntax and different nomenclature for how they execute commands. So, for example, an if/else statement in the t-shell looks different from a similar statement in the bash shell.

Overall, there's no need to worry too much about which shell you use, although AFNI's default is tcsh, so you may want to get yourself used to that before doing too much with AFNI. I myself use tcsh virtually all of the time, except for a few instances where bash is the only tool that works for the job (running processes on IU's supercomputer, Quarry, comes to mind). There are lots of tcsh haters out there for reasons that are beyond me, but for everything that I do, it works just fine.

As for variables, this is one of the first things you get taught in any intro computer science class, and those of you who have used other software packages, such as R or Matlab, already know what a variable is. In a nutshell, a variable is a thing that has a value. The value can be a string, or a letter, or a number, or pretty much anything. So, for example, when I type in the command
set x=10
in the t-shell, the variable is x, and the value is now 10. If I wish to extract the value from x at any time, I prepend a dollar sign ('$') to it, in order to tell Unix that what follows is a variable. You can also use the 'echo' command to dump the value of the variable to the standard output (i.e., your terminal). So, typing
echo $x
returns the following:
10
which is the value that I assigned to x.

From there, you can build up more complicated scripts and, by having the variable as a placeholder in various locations in your script, only have to change the value assigned to it in order to change the value in each of those locations. It makes your programming more flexible and easier to read and understand, and is critical to know if you wish to make sense of the example scripts generated by AFNI's "uber" scripts.

With all of the tutorials so far, you have essentially all of the fundamentals you need to operate FSL. Really, you only need to understand how to open up a terminal and make sure your path is pointing to the FSL binaries, but after that, all you need to do is understand the interface, and you can get by with pointing and clicking. However, a more sophisticated understanding is needed for AFNI, which will be covered soon. Very soon. Patience, my pretties.