{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n\n# Reconstruction of the diffusion signal with the Tensor model\n\nThe diffusion tensor model is a model that describes the diffusion within a\nvoxel. First proposed by Basser and colleagues [Basser1994]_, it has been very\ninfluential in demonstrating the utility of diffusion MRI in characterizing the\nmicro-structure of white matter tissue and of the biophysical properties of\ntissue, inferred from local diffusion properties and it is still very commonly\nused.\n\nThe diffusion tensor models the diffusion signal as:\n\n\\begin{align}rac{S(\\mathbf{g}, b)}{S_0} = e^{-b\\mathbf{g}^T \\mathbf{D} \\mathbf{g}}\\end{align}\n\nWhere $\\mathbf{g}$ is a unit vector in 3 space indicating the direction of\nmeasurement and b are the parameters of measurement, such as the strength and\nduration of diffusion-weighting gradient. $S(\\mathbf{g}, b)$ is the\ndiffusion-weighted signal measured and $S_0$ is the signal conducted in a\nmeasurement with no diffusion weighting. $\\mathbf{D}$ is a positive-definite\nquadratic form, which contains six free parameters to be fit. These six\nparameters are:\n\n\\begin{align}\\mathbf{D} = \begin{pmatrix} D_{xx} & D_{xy} & D_{xz} \\\n D_{yx} & D_{yy} & D_{yz} \\\n D_{zx} & D_{zy} & D_{zz} \\ \\end{pmatrix}\\end{align}\n\nThis matrix is a variance/covariance matrix of the diffusivity along the three\nspatial dimensions. Note that we can assume that diffusivity has antipodal\nsymmetry, so elements across the diagonal are equal. For example:\n$D_{xy} = D_{yx}$. This is why there are only 6 free parameters to estimate\nhere.\n\nIn the following example we show how to reconstruct your diffusion datasets\nusing a single tensor model.\n\nFirst import the necessary modules:\n\n``numpy`` is for numerical computation\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "``dipy.io.image`` is for loading / saving imaging datasets\n``dipy.io.gradients`` is for loading / saving our bvals and bvecs\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from dipy.io.image import load_nifti, save_nifti\nfrom dipy.io.gradients import read_bvals_bvecs\nfrom dipy.core.gradients import gradient_table" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "``dipy.reconst`` is for the reconstruction algorithms which we use to create\nvoxel models from the raw data.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import dipy.reconst.dti as dti" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "``dipy.data`` is used for small datasets that we use in tests and examples.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from dipy.data import get_fnames" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "``get_fnames`` will download the raw dMRI dataset of a single subject.\nThe size of the dataset is 87 MBytes. You only need to fetch once. It\nwill return the file names of our data.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "hardi_fname, hardi_bval_fname, hardi_bvec_fname = get_fnames('stanford_hardi')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next, we read the saved dataset. gtab contains a ``GradientTable``\nobject (information about the gradients e.g. b-values and b-vectors).\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "data, affine = load_nifti(hardi_fname)\n\nbvals, bvecs = read_bvals_bvecs(hardi_bval_fname, hardi_bvec_fname)\ngtab = gradient_table(bvals, bvecs)\n\nprint('data.shape (%d, %d, %d, %d)' % data.shape)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "data.shape ``(81, 106, 76, 160)``\n\nFirst of all, we mask and crop the data. This is a quick way to avoid\ncalculating Tensors on the background of the image. This is done using DIPY_'s\n``mask`` module.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from dipy.segment.mask import median_otsu\n\nmaskdata, mask = median_otsu(data, vol_idx=range(10, 50), median_radius=3,\n numpass=1, autocrop=True, dilate=2)\nprint('maskdata.shape (%d, %d, %d, %d)' % maskdata.shape)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "maskdata.shape ``(72, 87, 59, 160)``\n\nNow that we have prepared the datasets we can go forward with the voxel\nreconstruction. First, we instantiate the Tensor model in the following way.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "tenmodel = dti.TensorModel(gtab)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Fitting the data is very simple. We just need to call the fit method of the\nTensorModel in the following way:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "tenfit = tenmodel.fit(maskdata)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The fit method creates a ``TensorFit`` object which contains the fitting\nparameters and other attributes of the model. You can recover the 6 values\nof the triangular matrix representing the tensor D. By default, in DIPY, values\nare ordered as (Dxx, Dxy, Dyy, Dxz, Dyz, Dzz). The ``tensor_vals`` variable\ndefined below is a 4D data with last dimension of size 6.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "tensor_vals = dti.lower_triangular(tenfit.quadratic_form)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can also recover other metrics from the model. For example we can generate\nfractional anisotropy (FA) from the eigen-values of the tensor. FA is used to\ncharacterize the degree to which the distribution of diffusion in a voxel is\ndirectional. That is, whether there is relatively unrestricted diffusion in one\nparticular direction.\n\nMathematically, FA is defined as the normalized variance of the eigen-values of\nthe tensor:\n\n\\begin{align}FA = \\sqrt{\\frac{1}{2}\\frac{(\\lambda_1-\\lambda_2)^2+(\\lambda_1-\n \\lambda_3)^2+(\\lambda_2-\\lambda_3)^2}{\\lambda_1^2+\n \\lambda_2^2+\\lambda_3^2}}\\end{align}\n\nNote that FA should be interpreted carefully. It may be an indication of the\ndensity of packing of fibers in a voxel, and the amount of myelin wrapping\nthese axons, but it is not always a measure of \"tissue integrity\". For example,\nFA may decrease in locations in which there is fanning of white matter fibers,\nor where more than one population of white matter fibers crosses.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print('Computing anisotropy measures (FA, MD, RGB)')\nfrom dipy.reconst.dti import fractional_anisotropy, color_fa\n\nFA = fractional_anisotropy(tenfit.evals)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the background of the image the fitting will not be accurate there is no\nsignal and possibly we will find FA values with nans (not a number). We can\neasily remove these in the following way.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "FA[np.isnan(FA)] = 0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Saving the FA images is very easy using nibabel_. We need the FA volume and the\naffine matrix which transform the image's coordinates to the world coordinates.\nHere, we choose to save the FA in ``float32``.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "save_nifti('tensor_fa.nii.gz', FA.astype(np.float32), affine)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can now see the result with any nifti viewer or check it slice by slice\nusing matplotlib_'s ``imshow``. In the same way you can save the eigen values,\nthe eigen vectors or any other properties of the tensor.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "save_nifti('tensor_evecs.nii.gz', tenfit.evecs.astype(np.float32), affine)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Other tensor statistics can be calculated from the ``tenfit`` object. For\nexample, a commonly calculated statistic is the mean diffusivity (MD). This is\nsimply the mean of the eigenvalues of the tensor. Since FA is a normalized\nmeasure of variance and MD is the mean, they are often used as complimentary\nmeasures. In DIPY, there are two equivalent ways to calculate the mean\ndiffusivity. One is by calling the ``mean_diffusivity`` module function on the\neigen-values of the ``TensorFit`` class instance:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "MD1 = dti.mean_diffusivity(tenfit.evals)\nsave_nifti('tensors_md.nii.gz', MD1.astype(np.float32), affine)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The other is to call the ``TensorFit`` class method:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "MD2 = tenfit.md" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Obviously, the quantities are identical.\n\nWe can also compute the colored FA or RGB-map [Pajevic1999]_. First, we make\nsure that the FA is scaled between 0 and 1, we compute the RGB map and save it.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "FA = np.clip(FA, 0, 1)\nRGB = color_fa(FA, tenfit.evecs)\nsave_nifti('tensor_rgb.nii.gz', np.array(255 * RGB, 'uint8'), affine)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's try to visualize the tensor ellipsoids of a small rectangular\narea in an axial slice of the splenium of the corpus callosum (CC).\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print('Computing tensor ellipsoids in a part of the splenium of the CC')\n\nfrom dipy.data import get_sphere\nsphere = get_sphere('repulsion724')\n\nfrom dipy.viz import window, actor\n\n# Enables/disables interactive visualization\ninteractive = False\n\nscene = window.Scene()\n\nevals = tenfit.evals[13:43, 44:74, 28:29]\nevecs = tenfit.evecs[13:43, 44:74, 28:29]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can color the ellipsoids using the ``color_fa`` values that we calculated\nabove. In this example we additionally normalize the values to increase the\ncontrast.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "cfa = RGB[13:43, 44:74, 28:29]\ncfa /= cfa.max()\n\nscene.add(actor.tensor_slicer(evals, evecs, scalar_colors=cfa, sphere=sphere,\n scale=0.3))\n\nprint('Saving illustration as tensor_ellipsoids.png')\nwindow.record(scene, n_frames=1, out_path='tensor_ellipsoids.png',\n size=(600, 600))\nif interactive:\n window.show(scene)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. figure:: tensor_ellipsoids.png\n :align: center\n\n Tensor Ellipsoids.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "scene.clear()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, we can visualize the tensor Orientation Distribution Functions\nfor the same area as we did with the ellipsoids.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "tensor_odfs = tenmodel.fit(data[20:50, 55:85, 38:39]).odf(sphere)\n\nodf_actor = actor.odf_slicer(tensor_odfs, sphere=sphere, scale=0.5,\n colormap=None)\nscene.add(odf_actor)\nprint('Saving illustration as tensor_odfs.png')\nwindow.record(scene, n_frames=1, out_path='tensor_odfs.png', size=(600, 600))\nif interactive:\n window.show(scene)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. figure:: tensor_odfs.png\n :align: center\n\n Tensor ODFs.\n\nNote that while the tensor model is an accurate and reliable model of the\ndiffusion signal in the white matter, it has the drawback that it only has one\nprincipal diffusion direction. Therefore, in locations in the brain that\ncontain multiple fiber populations crossing each other, the tensor model may\nindicate that the principal diffusion direction is intermediate to these\ndirections. Therefore, using the principal diffusion direction for tracking in\nthese locations may be misleading and may lead to errors in defining the\ntracks. Fortunately, other reconstruction methods can be used to represent the\ndiffusion and fiber orientations in those locations. These are presented in\nother examples.\n\n## References\n\n.. [Basser1994] Basser PJ, Mattielo J, LeBihan (1994). MR diffusion tensor\n spectroscopy and imaging.\n\n.. [Pajevic1999] Pajevic S, Pierpaoli (1999). Color schemes to represent the\n orientation of anisotropic tissues from diffusion tensor data: application\n to white matter fiber tract mapping in the human brain.\n\n.. include:: ../links_names.inc\n\n\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.13" } }, "nbformat": 4, "nbformat_minor": 0 }