Tuesday, November 27, 2012

SPM: Setting the Origin and Normalization (Feat. Chad)

Of all the preprocessing steps in FMRI data, normalization is most susceptible to errors, failure, mistakes, madness, and demonic possession. This step involves the application of warps (just another term for transformations) of your anatomical and functional datasets in order to match a standardized space; in other words, all of your images will be squarely placed within a bounding box that has the same dimensions for each image, and each image will be oriented similarly.

To visualize this, imagine that you have twenty individual shoes - possibly, those single shoes you find discarded along the highways of America - each corresponding to an individual anatomical image. You also have a shoe box, corresponding to the standardized space, or template. Now, some of the shoes are big, some are small, and some have bizarre contours which prevent their fitting comfortably in the box.

However, due to a perverted Procrustean desire, you want all of those shoes to fit inside the box exactly; each shoe should have the toe and heel just touching the front and back of the box, and the sides of the shoes should barely graze the cardboard. If a particular shoe does not fit these requirements, you make it fit; excess length is hacked off*, while smaller footwear is stretched to the boundaries; extra rubber on the soles is either filed down or padded, until the shoe fits inside the box perfectly; and the resulting shoes, while bearing little similarity to their original shape, will all be roughly the same size.

This, in a nutshell, is what happens during normalization. However, it can easily fail and lead to wonky-looking normalized brains, usually with abnormal skewing of a particular dimension. This can often by explained by a faulty starting location, which can then lead to getting trapped in what is called a local minimum.

To visualize this concept, imagine a boulder rolling down valleys. The lowest point that the boulder can fall into represents the best solution; the boulder - named Chad - is happiest when he is at the lowest point he can find. However, there are several dips and dells and dales and swales that Chad can roll into, and if he doesn't search around far enough, he may imagine himself to be in the lowest place in the valley - even if that is not necessarily the case. In the picture below, let's say that Chad starts between points A and B; if he looks at the two options, he chooses B, since it is lower, and Chad is therefore happier. However, Chad, in his shortsightedness, has failed to look beyond those two options and descry option C, which in truth is the lowest point of all the valleys.



This represents a faulty starting position; and although Chad could extend the range of his search, the range of his gaze, and behold all of the options underneath the pandemonium of the dying sun, this would take far longer. Think of this as corresponding to the search space; expanding this space requires more computing time, which is undesirable.

To mitigate this problem, we can give Chad a hand by placing him in a location where he is more likely to find the optimal solution. For example, let us place Chad closer to C - conceivably, even within C itself - and he will find it much easier to roll his rotund, rocky little body into the soft, warm, womb-like crater of option C, and thus obtain a boulder's beggar's bliss.

(For the mathematically inclined, the contours of the valley represent the cost function; the boulder represents the cost function ratio between the source image and the template image; and each letter (A, B, and C) represents a possible minimum in the cost function.)


As with Chad, so with your anatomical images. It is well for the neuroimager to know that the origin (i.e., coordinates 0,0,0) of both Talairach and MNI space is roughly located at the anterior commissure of the brain; therefore, it behooves you to set the origins of your anatomical images to the anterior commissure as well. The following tutorial will show you how to do this in SPM, where this technique is most important:




Once we have successfully warped our anatomical image to a template space, the reason for coregistration becomes apparent: Since our T2-weighted functional images were in roughly the same space as the anatomical image, we can apply the same warps used on the anatomical image to the functional images. This is where the "Other Images" option comes into play in the SPM interface.



As always, check your registration. Then, check it again. Then, ask someone else to check it. (This is a great way to meet girls.) In particular, check to make sure that the internal structures (such as the ventricles) are properly aligned between the template image and your warped images; matching the internal variability of the template image is much trickier, and therefore much more susceptible to failure - even if the outer boundaries of the brain look as though they match up.


*Actually, it's more accurate to say that it is compressed. However, once I started with the Procrustean thing, I just had to roll with it.
 

39 comments:

  1. Thanks for help! This is my question that the image is truncated after normalization. Just without reorientation.

    ReplyDelete
  2. thank you for your helpful subject , but I have a question.

    I have a dataset which the writers of paper said for normalization wh did this step
    >>>Structural images were normalized (spatially warped) to a standard
    template brain (the MNI avg152T1.img) using SPM2 software (Wellcome Department of
    Cognitive Neurology, UCL) using default options (7 x 8 x 7 nonlinear basis functions), and the
    warping parameters were applied to functional images for each subject.

    my question is: how can I do this in SPM? I should normalize structural image to MNIavg152T1, but in spm12 , normalization (estimate), there is no chois for MNI template!!!

    ReplyDelete
    Replies
    1. Hi Safa,

      Aside from knowing that SPM12 will normalize to MNI space, I don't know what template SPM12 uses. However, if you can still use the old normalize module by clicking on Batch -> SPM -> Tools -> Old Normalise.

      -Andy

      Delete
  3. Hi! Is it normal that after normalization individual images are not exactly registered? Also, I have images acquired in 2009, and for some reason, after coregistration with structural images, the top of the brain is considering the skull as brain tissue, something it is not happening with the frontal part. What do you think is the problem? Or, shall I consider it a problem?
    Thank you for all help!

    ReplyDelete
    Replies
    1. After normalization, different subjects will still have slightly different brain structures, so that's normal if that's what you are talking about. But within-subject, the functional should be (almost) perfectly coregistered to the structural, if that's not the case, you can manually reorient and translate the functional images using Checkreg > Select T1 and one T2 image > Right click on the functional image > Reorient this image. Then translate/reorient and save this for all T2 images of this subject (not just the selected image). Then you can continue the standard SPM preprocessing pipeline (realignment, auto coregistration, normalization, smoothing, segmentation, etc.).

      Delete
  4. hi Andy, I need to perform spatial normalisation of FDG-PET scans, what should my 'source image' be..? I have no structural image
    thanks! Vale

    ReplyDelete
    Replies
    1. Hi Vale,

      It's been a while since I worked with PET data, but you might want to consider using the avg152_T2.nii template; I think that the contrast of T2-weighted images is similar to PET images. You can use SPM's Old Normalise option through the Batch Editor; select the SPM dropdown menu, then Tools -> Old Normalise.


      Best,

      -Andy

      Delete
  5. Hi Andy, thank you for this great video. Since I'm an absolute beginner with SPM, your vids have helped me a lot so far!
    However, I'm still uncertain about when it's necessary to rotate the structural image in addition to setting the origin. Do I have to adjust my image's rotation to the one of the template (“canonical\avg152T1.nii”) as soon as there is a (slight) difference visible? Also, do you know an easier/ more efficient way to rotate an image than just playing around with the values until it looks okay? (That's how it feels to me at the moment since the angles are specified in radians.)
    Thanks a lot!
    Henriette

    ReplyDelete
    Replies
    1. Hi Henriette,

      The alignment doesn't have to be exact; there won't be a perfect correspondence between your anatomical and the template anyway. All you have to do is make sure that the major anatomical landmarks - such as the anterior commissure, cingulate sulcus, and calcarine sulcus - are all reasonably close to each other. If the anterior commissures line up, and the rotations of both images are within a few degrees of each other, then you shouldn't have any problem with your normalization.


      Best,

      -Andy

      Delete
    2. Thank you very much, Andy!
      Best,
      Henriette

      Delete
  6. Hi Andy,
    I have normalized 20 subjects using the same batch in spm8. However, I get different sizes for the normalized images: half of the subjects have [79x95x68], but the other half present small variations, like [79x *96* x68] or [79x *99* x 68]. Do you know how to tackle this? Thank you so much for all your help!

    ReplyDelete
    Replies
    1. Hi Rebecca,

      I'm not sure why that is; usually the normalization scripts across all the major software packages (SPM, FSL, and AFNI) will have standard dimensions for the normalized images. If you're using a batch for all the subjects, what are the parameters of the Bounding Box for the Normalise step?

      One option is to use a resampling program, like AFNI's 3dresample, to make all the images uniform in size. However, I would start with trying to figure out why this is happening in the first place. Are you using segmentation to help with the normalization step?

      -Andy

      Delete
    2. Hi Andy,

      thank you so much for your reply. The bounding box is [-78 -112 -50; 78 76 85]. I haven't used segmentation

      It's certainly strange, I will try to figure the problem out

      Best,
      Rebecca

      Delete
    3. Hey Rebecca,

      One workaround would be to use Coregister -> Reslice, then select a representative image as the Image Defining Space, then select all the images with slight variations as Images to Reslice. I would use Nearest Neighbor interpolation. This resamples the images to match your defining image, and will match up the resolution and image size.

      You can also use SPM's old Normalize (under Batch -> SPM -> Tools -> Old Normalise), which isn't as good as their newer version, but doesn't have the same issues with bounding boxes and image size.

      -Andy

      Delete
  7. Hi,
    I am attempting to analyse EEG data using MatLab and an extension known as EEGLAB. In order to carry out DIPFIT in this programme I need to first convert the fMRI images, which were collected as the same time as the EEG data, from MR head images to the MNI brain template. I am using SPM12 to do so, I understand your video tutorials use an older version and I have tried to follow them but am struggling to understand what template SPM12 uses as there is no option to select T1 as your template image when normalising images. Do you have any advice?
    Thanks

    ReplyDelete
    Replies
    1. Hi Alice,

      If you want to use the old method of normalization, from the GUI you can select Batch, then from the dropdown menu select SPM -> Tools -> Old Normalise. This will allow you to use the T1.nii image as a template.

      -Andy

      Delete
  8. Hi Andy, can I "de-normalize" an image? If I found an ROI in an normalized image but want to know how big this ROI is in non-normalized image? Can I return the process of nromalization? Thanks

    ReplyDelete
    Replies
    1. Hey there,

      Which software are you using? I don't know how to do that with SPM, but here's how to do it with FSL:

      1. If you've run the preprocessing of your functional data to a standardized space, in the "reg" folder you will find many transformations matrices - not only the transformation matrix to bring the functional data to standardized space, but also a matrix to reverse the process and bring standardized space to the subject's native space. You can find the latter in standard2example_func.mat.

      2. Use flirt to transform the ROI to subject space: flirt -in ROI_StandardizedSpace.nii.gz -ref example_func.nii.gz -init standard2example_func.mat -applyxfm -out ROI_SubjectSpace.nii.gz


      Let me know if you need to do this for AFNI, and I'll give you the code for that.

      Best,

      -Andy

      Delete
  9. Hi Andy,
    thank you for your vedios which help me a lot. right now, i am processing the fetal brain data with the combination of FSL and AFNI. I have been quite confused about the normalization in 2 aspects:
    1, the fatal anatomic image is seriously affected by motion, so i decided to register the functional image to the EPI template which i 'steal' from the SPM12 directly. Do i need to reorient the functional volumes? It is so hard to secify the AC PC in the fatal functional brain.
    2.The fetal brain i extracted from the womb image is so small that it can hardly register to the template. Then i scale it manully with a global factor , is it Ok? What's more, i can hardly evaluate the results of registration as the image is too blur. I can't figure out which action is better when comparing flirt with fnirt.

    ReplyDelete
    Replies
    1. Hey there,

      I don't have experience with fetal brains, so I can't say; it would be much safer to have a fetal brain template to warp to, as many of the steps you outline can introduce a lot of distortions (and normalization already distorts the image to some degree). I would ask around to see if anyone has such a template (although I don't know where I would start). It may be worth doing the analyses in each subjects' individual space, if you only have a few of them.

      -Andy

      Delete
  10. For visualizing data, why dont you use a diagram tool which you can input data of each set and get the output illustration.

    ReplyDelete
  11. Hi Andy,

    Have you ever built a study specific template? I have a considerable amount of subjects (around 115) and I would like to make a template out of my sample. Do you have any idea how to perform this?

    Best regards,

    ReplyDelete
    Replies
    1. Hi Nick,

      You can do this by using an image calculator. In the case of SPM, I use spm_imcalc_ui:

      P1 = '/path/to/image.nii';
      P2 = '/path/to/image2.nii';

      spm_imalc_ui([P1; P2], 'average.nii', '(i1+i2)/2'


      You can expand this to include as many image as you have. Note that if you are taking the average of your normalized images, then the output will also be in normalized space; alternatively, you could register all of your anatomicals to a reference anatomical (e.g., one chosen at random) and then take the average of the registered anatomicals. However, this would not be in normalized space, which would preclude direct comparisons across studies.

      -Andy

      Delete
  12. Hi Andrew,

    Your videos and explanations are so helpful. I'm working with SPM, but I'm making all the preprocessing steps using the command line and I'm doing my own scripts. My question is... How I can do normalization using the command line? I cannot find the functions that perform normalization.

    Thanks!

    Abel González

    ReplyDelete
  13. Hey Abel,

    Open up Normalise (Estimate and Write) from the GUI, and fill it in like you would when analyzing a single subject. Once you've filled in all the fields, click on File -> Save Batch and Script. This will create a "job" file containing the Matlab code you need to submit to spm_jobman to automate it.

    Best,

    -Andy

    ReplyDelete
  14. Thanks for answering. I have not used "job" files until now, but what I am doing is write the script using only the purely functions. For example: in motion correction I used spm_realign.mat and spm_reslice.mat; in slice-timing correction I used spm_slice_timing; for smoothing spm_smooth.mat; etc..) My second question: Is there any function or group of functions (like mentioned above) to perform normalization?

    Thank you again,

    Abel González

    ReplyDelete
    Replies
    1. Hey Abel,

      See spm_normalise for that; I think the help should be straightforward.


      Best,

      -Andy

      Delete
  15. Hi Andy,

    I'm a noob and I need help.
    I wrote the following script using an SPM batch to normalise data to MNI space. I use pre-existing y-files and loop over 77 patiënts. When I run the script, it does run but it says the following: Item 'Deformation Field', field 'val': Number of matching files larger than max allowed, keeping 1/77 file After running 'normalise: write' it gives an error: 'Index exceeds matrix dimensions'

    It looks like it only uses 1 of 77 y-files for all 77 patients, which results in faulty normalization. Even though the path_yfile is a 77x1 cell and all other variables seem well defined looking at the workspace.

    the script:
    List of open inputs
    % Normalise: Write: Deformation Field - cfg_files
    % Normalise: Write: Images to Write - cfg_files
    wd='/Data/users/ano/verbgen_seg/';
    ID_CODES=dir([wd '*.MRI.1']);
    N=length(ID_CODES);
    path_yfile = cell(N, 1); % predefines the size of the matrix
    Images=cell(N, 1);
    for i = 1:length(ID_CODES) % Loop over patients
    dp=char(strcat('/Data/users/ano/verbgen_seg/',ID_CODES(i).name,'/Images/'));
    d=dir([dp '*T1W*']);
    d1=d(1);
    Images(i, 1)= {char(strcat(dp, d1.name))};
    dp=char(strcat('/Data/users/ano/verbgen_seg/', ID_CODES(i).name,'/Images/'));
    d=dir([dp,'*y_*']);
    path_yfile(i, 1) = {char(strcat(dp, d.name))};
    end
    for i=1:length(ID_CODES)
    nrun = 1; % enter the number of runs here
    jobfile = {'/Data/users/ano/SPM_analysis_GK/normaliseseg_job_test.m'};
    jobs = repmat(jobfile, 1, nrun);
    inputs = cell(2, nrun);
    for crun = 1:nrun
    inputs{1, crun} = path_yfile(:, i); % Normalise: Write: Deformation Field - cfg_files
    inputs{2, crun} = Images(:, i); % Normalise: Write: Images to Write - cfg_files
    end
    spm('defaults', 'FMRI');
    spm_jobman('run', jobs, inputs{:});
    end

    ReplyDelete
  16. This comment has been removed by the author.

    ReplyDelete
  17. Hi Andy,
    I'm normalizing my data to the segmented Cincinnati pediatric template. Should I change the bounding box values? What values should I use, if not the SPM default?
    Thank you,
    Yael

    ReplyDelete
  18. Hi Andy, if I don't have structural data in fMRI, should I use the Old normalization or is there a more accurate method? thanks

    ReplyDelete
    Replies
    1. Hello Anonymous, I have made a script to ease/automate reorientation and coregistration. If you don't have a T1, you can coregister your functionals on the provided template, or use SPM's one. It's suboptimal compared to having a structural per subject, but it should work.

      https://github.com/lrq3000/spm_auto_reorient_coregister

      Now the biggest problem you will face is not reorientation and coregistration of fmri, since you can use a template, but rather the fact that segmentation will have to be done on the functional data, which is suboptimal since functional images have very low resolution (compared to structural at least). Segmentation is particularly useful for denoising, so essentially you won't be able to denoise. What you can try to do is again to segment from a template (or rather directly use SPM's tissue probability maps, just threshold them to make binary maps) and feed that to your ICA or CompCor denoising tool. But do note that this is very suboptimal, if you can reacquire the subjects with structural images (or acquire a new dataset), it would be far better. But if you don't have any other choices, you can give this template-based approach a try.

      Delete
  19. Hey there,
    So I've set my origin at the anterior commissure, and then run co-registration.
    Now i'm ready to normalise the data.

    However - I've noticed that if I display the T1s and click on "origin" it is no longer the anterior commissure, which makes some sense since the images have been slid to match the functional scans.

    However, I am confused. Should I re-adjust the origin to the commissure before warping to MNI space?

    Thanks so much for all your content. hugely helpful.

    ReplyDelete
    Replies
    1. Hi there,

      No, you won't need to reset the origin; that is done mainly to help the coregistration step.


      Best,

      -Andy

      Delete
  20. Hi Andy.

    I work with mouse fMRI and I'm trying to use SPM12 to normalize my data to the Allen Atlas. I'm using the old normalize function and was wondering if you could give me an explanation of what the nonlinear freq cutoff and regularization means? I assume iterations means how many times it tries to match (so more would be better in a sense?). Thanks for all your content. Made learning fMRI processing very easy even in mouse fMRI.

    ReplyDelete
    Replies
    1. Hi Andrew,

      I actually don't know exactly what those mean, but your intuition is probably correct. I don't know if there's a downside to using more iterations, aside from longer computation time; this should be relatively simple to check though by comparing it with a high versus a low number of iterations.


      Best,

      -Andy

      Delete
  21. Hi Andy, I have a NIFTI image which is not in a standard MNI space (I guess it is in native space). How could I normalize it to the standard space? Is there a tool or code I could use for this purpose? I am attempting to view this native image in third-party software, but it wouldn't let me unless it is in MNI space.

    ReplyDelete
  22. Now I have managed to use the tool as you explain (it only took me the whole day! :D). Now I wonder if there is a way to do this via console using Matlab functions instead of using a display. I have been searching in the SPM12 folder but couldn't find anything.

    ReplyDelete
    Replies
    1. Hey Emmanu,

      Unfortunately I don't know of an automatic tool to do it; you'll need to do it manually. I would only do it for the subjects that seem to need it, though; i.e., if the origins of the functional and anatomical images are very far apart.

      By the way, an updated tutorial has been made here: https://andysbrainbook.readthedocs.io/en/latest/SPM/SPM_Overview.html

      -Andy

      Delete