Beispiel #1
0
    def _run_interface(self, runtime):
        from dipy.reconst import dki
        from dipy.io.utils import nifti1_symmat
        gtab = self._get_gradient_table()

        img = nb.load(self.inputs.in_file)
        data = img.get_data()
        affine = img.affine
        mask = None
        if isdefined(self.inputs.mask_file):
            mask = nb.load(self.inputs.mask_file).get_data()

        # Fit the DKI model
        kurtosis_model = dki.DiffusionKurtosisModel(gtab)
        kurtosis_fit = kurtosis_model.fit(data, mask)
        lower_triangular = kurtosis_fit.lower_triangular()
        img = nifti1_symmat(lower_triangular, affine)
        out_file = self._gen_filename('dki')
        nb.save(img, out_file)
        IFLOGGER.info('DKI parameters image saved as {i}.format(i=out_file)')

        # FA, MD, RD, and AD
        for metric in ['fa', 'md', 'rd', 'ad', 'mk', 'ak', 'rk']:
            data = getattr(kurtosis_fit.metric).astype('float32')
            out_name = self._gen_filename(metric)
            nb.Nifti1Image(data, affine).to_filename(out_name)
            IFLOGGER.info('DKI {metric} image saved as {i}'.format(i=out_name,
                                                                   metric=metric))

        return runtime
Beispiel #2
0
    def _run_interface(self, runtime):
        from dipy.reconst import dti
        from dipy.io.utils import nifti1_symmat
        gtab = self._get_gradient_table()

        img = nb.load(self.inputs.in_file)
        data = img.get_data()
        affine = img.affine
        mask = None
        if isdefined(self.inputs.mask_file):
            mask = nb.load(self.inputs.mask_file).get_data()

        # Fit it
        tenmodel = dti.TensorModel(gtab)
        ten_fit = tenmodel.fit(data, mask)
        lower_triangular = ten_fit.lower_triangular()
        img = nifti1_symmat(lower_triangular, affine)
        out_file = self._gen_filename('dti')
        nb.save(img, out_file)
        IFLOGGER.info('DTI parameters image saved as {i}'.format(i=out_file))

        #FA MD RD and AD
        for metric in ["fa", "md", "rd", "ad"]:
            data = getattr(ten_fit,metric).astype("float32")
            out_name = self._gen_filename(metric)
            nb.Nifti1Image(data, affine).to_filename(out_name)
            IFLOGGER.info('DTI {metric} image saved as {i}'.format(i=out_name, metric=metric))

        return runtime
Beispiel #3
0
    def _run_interface(self, runtime):
        from dipy.reconst import dti
        from dipy.io.utils import nifti1_symmat
        gtab = self._get_gradient_table()

        img = nb.load(self.inputs.in_file)
        data = img.get_data()
        affine = img.affine
        mask = None
        if isdefined(self.inputs.mask_file):
            mask = nb.load(self.inputs.mask_file).get_data()

        # Fit it
        tenmodel = dti.TensorModel(gtab)
        ten_fit = tenmodel.fit(data, mask)
        lower_triangular = ten_fit.lower_triangular()
        img = nifti1_symmat(lower_triangular, affine)
        out_file = self._gen_filename('dti')
        nb.save(img, out_file)
        IFLOGGER.info('DTI parameters image saved as %s', out_file)

        # FA MD RD and AD
        for metric in ["fa", "md", "rd", "ad", "color_fa"]:
            data = getattr(ten_fit, metric).astype("float32")
            out_name = self._gen_filename(metric)
            nb.Nifti1Image(data, affine).to_filename(out_name)
            IFLOGGER.info('DTI %s image saved as %s', metric, out_name)

        return runtime
Beispiel #4
0
    def _run_interface(self, runtime):
        gtab = self._get_gtab()
        dwi_img = nb.load(self.inputs.dwi_file)
        dwi_data = dwi_img.get_fdata(dtype=np.float32)
        mask_img, mask_array = self._get_mask(dwi_img, gtab)

        # Fit it
        tenmodel = dti.TensorModel(gtab)
        ten_fit = tenmodel.fit(dwi_data, mask_array)
        lower_triangular = ten_fit.lower_triangular()
        tensor_img = nifti1_symmat(lower_triangular, dwi_img.affine)
        output_tensor_file = fname_presuffix(self.inputs.dwi_file,
                                             suffix='tensor',
                                             newpath=runtime.cwd,
                                             use_ext=True)
        tensor_img.to_filename(output_tensor_file)

        # FA MD RD and AD
        for metric in ["fa", "md", "rd", "ad", "color_fa"]:
            data = getattr(ten_fit, metric).astype("float32")
            out_name = fname_presuffix(self.inputs.dwi_file,
                                       suffix=metric,
                                       newpath=runtime.cwd,
                                       use_ext=True)
            nb.Nifti1Image(data, dwi_img.affine).to_filename(out_name)
            self._results[metric + "_image"] = out_name

        return runtime
Beispiel #5
0
 def _run_interface(self, runtime):
     ten_fit, affine = tensor_fitting(self.inputs.in_file,
                                      self.inputs.bvals, self.inputs.bvecs,
                                      self.inputs.mask_file)
     lower_triangular = tenfit.lower_triangular()
     img = nifti1_symmat(lower_triangular, affine)
     out_file = op.abspath(self._gen_outfilename())
     nb.save(img, out_file)
     iflogger.info('DTI parameters image saved as {i}'.format(i=out_file))
     return runtime
Beispiel #6
0
 def _run_interface(self, runtime):
     ten_fit, affine = tensor_fitting(
         self.inputs.in_file, self.inputs.bvals, self.inputs.bvecs, self.inputs.mask_file
     )
     lower_triangular = tenfit.lower_triangular()
     img = nifti1_symmat(lower_triangular, affine)
     out_file = op.abspath(self._gen_outfilename())
     nb.save(img, out_file)
     iflogger.info("DTI parameters image saved as {i}".format(i=out_file))
     return runtime
Beispiel #7
0
    def _run_interface(self, runtime):
        from dipy.reconst import dti
        from dipy.io.utils import nifti1_symmat
        gtab = self._get_gradient_table()

        img = nb.load(self.inputs.in_file)
        data = img.get_data()
        affine = img.affine
        mask = None
        if isdefined(self.inputs.mask_file):
            mask = nb.load(self.inputs.mask_file).get_data()

        # Fit it
        tenmodel = dti.TensorModel(gtab)
        ten_fit = tenmodel.fit(data, mask)
        lower_triangular = tenfit.lower_triangular()
        img = nifti1_symmat(lower_triangular, affine)
        out_file = self._gen_filename('dti')
        nb.save(img, out_file)
        IFLOGGER.info('DTI parameters image saved as {i}'.format(i=out_file))
        return runtime
Beispiel #8
0
    def run(self,
            input_files,
            bvalues_files,
            bvectors_files,
            mask_files,
            b0_threshold=50,
            bvecs_tol=0.01,
            save_metrics=[],
            out_dir='',
            out_tensor='tensors.nii.gz',
            out_fa='fa.nii.gz',
            out_ga='ga.nii.gz',
            out_rgb='rgb.nii.gz',
            out_md='md.nii.gz',
            out_ad='ad.nii.gz',
            out_rd='rd.nii.gz',
            out_mode='mode.nii.gz',
            out_evec='evecs.nii.gz',
            out_eval='evals.nii.gz',
            nifti_tensor=True):
        """ Workflow for tensor reconstruction and for computing DTI metrics.
        using Weighted Least-Squares.
        Performs a tensor reconstruction on the files by 'globing'
        ``input_files`` and saves the DTI metrics in a directory specified by
        ``out_dir``.

        Parameters
        ----------
        input_files : string
            Path to the input volumes. This path may contain wildcards to
            process multiple inputs at once.
        bvalues_files : string
            Path to the bvalues files. This path may contain wildcards to use
            multiple bvalues files at once.
        bvectors_files : string
            Path to the bvectors files. This path may contain wildcards to use
            multiple bvectors files at once.
        mask_files : string
            Path to the input masks. This path may contain wildcards to use
            multiple masks at once.
        b0_threshold : float, optional
            Threshold used to find b0 volumes.
        bvecs_tol : float, optional
            Threshold used to check that norm(bvec) = 1 +/- bvecs_tol
            b-vectors are unit vectors.
        save_metrics : variable string, optional
            List of metrics to save.
            Possible values: fa, ga, rgb, md, ad, rd, mode, tensor, evec, eval
        out_dir : string, optional
            Output directory. (default current directory)
        out_tensor : string, optional
            Name of the tensors volume to be saved.
            Per default, this will be saved following the nifti standard:
            with the tensor elements as Dxx, Dxy, Dyy, Dxz, Dyz, Dzz on the
            last (5th) dimension of the volume (shape: (i, j, k, 1, 6)). If
            `nifti_tensor` is False, this will be saved in an alternate format
            that is used by other software (e.g., FSL): a
            4-dimensional volume (shape (i, j, k, 6)) with Dxx, Dxy, Dxz, Dyy,
            Dyz, Dzz on the last dimension.
        out_fa : string, optional
            Name of the fractional anisotropy volume to be saved.
        out_ga : string, optional
            Name of the geodesic anisotropy volume to be saved.
        out_rgb : string, optional
            Name of the color fa volume to be saved.
        out_md : string, optional
            Name of the mean diffusivity volume to be saved.
        out_ad : string, optional
            Name of the axial diffusivity volume to be saved.
        out_rd : string, optional
            Name of the radial diffusivity volume to be saved.
        out_mode : string, optional
            Name of the mode volume to be saved.
        out_evec : string, optional
            Name of the eigenvectors volume to be saved.
        out_eval : string, optional
            Name of the eigenvalues to be saved.
        nifti_tensor : bool, optional
            Whether the tensor is saved in the standard Nifti format or in an
            alternate format
            that is used by other software (e.g., FSL): a
            4-dimensional volume (shape (i, j, k, 6)) with
            Dxx, Dxy, Dxz, Dyy, Dyz, Dzz on the last dimension.

        References
        ----------
        .. [1] Basser, P.J., Mattiello, J., LeBihan, D., 1994. Estimation of
           the effective self-diffusion tensor from the NMR spin echo. J Magn
           Reson B 103, 247-254.

        .. [2] Basser, P., Pierpaoli, C., 1996. Microstructural and
           physiological features of tissues elucidated by quantitative
           diffusion-tensor MRI.  Journal of Magnetic Resonance 111, 209-219.

        .. [3] Lin-Ching C., Jones D.K., Pierpaoli, C. 2005. RESTORE: Robust
           estimation of tensors by outlier rejection. MRM 53: 1088-1095

        .. [4] hung, SW., Lu, Y., Henry, R.G., 2006. Comparison of bootstrap
           approaches for estimation of uncertainties of DTI parameters.
           NeuroImage 33, 531-541.

        """
        io_it = self.get_io_iterator()

        for dwi, bval, bvec, mask, otensor, ofa, oga, orgb, omd, oad, orad, \
                omode, oevecs, oevals in io_it:

            logging.info('Computing DTI metrics for {0}'.format(dwi))
            data, affine = load_nifti(dwi)

            if mask is not None:
                mask = load_nifti_data(mask).astype(bool)

            tenfit, _ = self.get_fitted_tensor(data, mask, bval, bvec,
                                               b0_threshold, bvecs_tol)

            if not save_metrics:
                save_metrics = [
                    'fa', 'md', 'rd', 'ad', 'ga', 'rgb', 'mode', 'evec',
                    'eval', 'tensor'
                ]

            FA = fractional_anisotropy(tenfit.evals)
            FA[np.isnan(FA)] = 0
            FA = np.clip(FA, 0, 1)

            if 'tensor' in save_metrics:
                tensor_vals = lower_triangular(tenfit.quadratic_form)

                if nifti_tensor:
                    ten_img = nifti1_symmat(tensor_vals, affine=affine)
                else:
                    alt_order = [0, 1, 3, 2, 4, 5]
                    ten_img = nib.Nifti1Image(
                        tensor_vals[..., alt_order].astype(np.float32), affine)

                nib.save(ten_img, otensor)

            if 'fa' in save_metrics:
                save_nifti(ofa, FA.astype(np.float32), affine)

            if 'ga' in save_metrics:
                GA = geodesic_anisotropy(tenfit.evals)
                save_nifti(oga, GA.astype(np.float32), affine)

            if 'rgb' in save_metrics:
                RGB = color_fa(FA, tenfit.evecs)
                save_nifti(orgb, np.array(255 * RGB, 'uint8'), affine)

            if 'md' in save_metrics:
                MD = mean_diffusivity(tenfit.evals)
                save_nifti(omd, MD.astype(np.float32), affine)

            if 'ad' in save_metrics:
                AD = axial_diffusivity(tenfit.evals)
                save_nifti(oad, AD.astype(np.float32), affine)

            if 'rd' in save_metrics:
                RD = radial_diffusivity(tenfit.evals)
                save_nifti(orad, RD.astype(np.float32), affine)

            if 'mode' in save_metrics:
                MODE = get_mode(tenfit.quadratic_form)
                save_nifti(omode, MODE.astype(np.float32), affine)

            if 'evec' in save_metrics:
                save_nifti(oevecs, tenfit.evecs.astype(np.float32), affine)

            if 'eval' in save_metrics:
                save_nifti(oevals, tenfit.evals.astype(np.float32), affine)

            dname_ = os.path.dirname(oevals)
            if dname_ == '':
                logging.info('DTI metrics saved in current directory')
            else:
                logging.info('DTI metrics saved in {0}'.format(dname_))
Beispiel #9
0
    data = img.get_data()
    affine = img.get_affine()

    # Get the optional params:
    fit_method = metadata.get('fit_method', "WLS")
    fmask = metadata.get('fmask', None)
    if fmask is None:
        mask = None
    else:
        mask = nib.load(fmask).get_data().astype(bool)

    # Fit the model:
    tenmodel = dti.TensorModel(gtab, fit_method=fit_method)
    tenfit = tenmodel.fit(data, mask=mask)

    # Extract the nifti convention parameters:
    lower_triangular = tenfit.lower_triangular()
    lower_triangular = lower_triangular.astype('float32')
    tensor_img = nifti1_symmat(lower_triangular, affine)

    # The output will all have the same basic name as the data file-name:
    root = op.join("/output",
                   op.splitext(op.splitext(op.split(fdata)[-1])[0])[0])

    # Save to file:
    dpsave(tensor_img, root + '_tensor.nii.gz')
    for arr, label in zip([tenfit.ad, tenfit.rd, tenfit.md, tenfit.fa],
                          ["_ad", "_rd", "_md", "_fa"]):
        dpsave(nib.Nifti1Image(arr.astype("float32"), affine),
               op.join('/output/', root + '%s.nii.gz' % label))
def fit_dti_dipy(input_dwi,
                 input_bval,
                 input_bvec,
                 output_dir,
                 fit_type='',
                 mask='',
                 bmax='',
                 mask_tensor='F',
                 bids_fmt=False,
                 bids_id=''):

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    img = nib.load(input_dwi)
    axis_orient = nib.aff2axcodes(img.affine)

    ras_img = nib.as_closest_canonical(img)
    data = ras_img.get_data()

    bvals, bvecs = read_bvals_bvecs(input_bval, input_bvec)
    bvecs = reorient_vectors(bvecs,
                             axis_orient[0] + axis_orient[1] + axis_orient[2],
                             'RAS',
                             axis=1)

    if mask != '':
        mask_img = nib.as_closest_canonical(nib.load(mask))
        mask_data = mask_img.get_data()

    if bmax != "":
        jj = np.where(bvals >= bmax)
        bvals = np.delete(bvals, jj)
        bvecs = np.delete(bvecs, jj, 0)
        data = np.delete(data, jj, axis=3)

    values = np.array(bvals)
    ii = np.where(values == bvals.min())[0]
    b0_average = np.mean(data[:, :, :, ii], axis=3)

    gtab = gradient_table(bvals, bvecs)

    if fit_type == 'RESTORE':
        sigma = estimate_sigma(data)
        #calculate the average sigma from the b0's
        sigma = np.mean(sigma[ii])

        dti_model = dti.TensorModel(gtab, fit_method='RESTORE', sigma=sigma)

        if mask != '':
            dti_fit = dti_model.fit(data, mask_data)
        else:
            dti_fit = dti_model.fit(data)

    elif fit_type != 'RESTORE' and fit_type != '':
        dti_model = dti.TensorModel(gtab, fit_method=fit_type)

        if mask != '':
            dti_fit = dti_model.fit(data, mask_data)
        else:
            dti_fit = dti_model.fit(data)

    else:
        dti_model = dti.TensorModel(gtab)

        if mask != '':
            dti_fit = dti_model.fit(data, mask_data)
        else:
            dti_fit = dti_model.fit(data)

    estimate_data = dti_fit.predict(gtab, S0=b0_average)
    residuals = np.absolute(data - estimate_data)

    tensor = dti.lower_triangular(dti_fit.quadratic_form.astype(np.float32))
    evecs = dti_fit.evecs.astype(np.float32)
    evals = dti_fit.evals.astype(np.float32)

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    output_imgs = []

    #Define output imgs
    if bids_fmt:
        output_tensor_nifti = output_dir + '/' + bids_id + '_model-DTI_parameter-TENSOR.nii.gz'
        output_tensor_fsl = output_dir + '/' + bids_id + '_model-DTI_parameter-FSL_TENSOR.nii.gz'
        output_tensor_mrtrix = output_dir + '/' + bids_id + '_model-DTI_parameter-MRTRIX_TENSOR.nii.gz'

        output_V1 = output_dir + '/' + bids_id + '_model-DTI_parameter-V1.nii.gz'
        output_V2 = output_dir + '/' + bids_id + '_model-DTI_parameter-V2.nii.gz'
        output_V3 = output_dir + '/' + bids_id + '_model-DTI_parameter-V3.nii.gz'
        output_FSL_V1 = output_dir + '/' + bids_id + '_model-DTI_parameter-FSL_V1.nii.gz'
        output_FSL_V2 = output_dir + '/' + bids_id + '_model-DTI_parameter-FSL_V2.nii.gz'
        output_FSL_V3 = output_dir + '/' + bids_id + '_model-DTI_parameter-FSL_V3.nii.gz'

        output_L1 = output_dir + '/' + bids_id + '_model-DTI_parameter-L1.nii.gz'
        output_L2 = output_dir + '/' + bids_id + '_model-DTI_parameter-L2.nii.gz'
        output_L3 = output_dir + '/' + bids_id + '_model-DTI_parameter-L3.nii.gz'

        output_fa = output_dir + '/' + bids_id + '_model-DTI_parameter-FA.nii.gz'
        output_md = output_dir + '/' + bids_id + '_model-DTI_parameter-MD.nii.gz'
        output_rd = output_dir + '/' + bids_id + '_model-DTI_parameter-RD.nii.gz'
        output_ad = output_dir + '/' + bids_id + '_model-DTI_parameter-AD.nii.gz'
        output_tr = output_dir + '/' + bids_id + '_model-DTI_parameter-TRACE.nii.gz'

        output_ga = output_dir + '/' + bids_id + '_model-DTI_parameter-GA.nii.gz'
        output_color_fa = output_dir + '/' + bids_id + '_model-DTI_parameter-COLOR_FA.nii.gz'

        output_PL = output_dir + '/' + bids_id + '_model-DTI_parameter-PLANARITY.nii.gz'
        output_SP = output_dir + '/' + bids_id + '_model-DTI_parameter-SPHERICITY.nii.gz'
        output_MO = output_dir + '/' + bids_id + '_model-DTI_parameter-MODE.nii.gz'

        output_res = output_dir + '/' + bids_id + '_model-DTI_parameter-RESIDUALS.nii.gz'

    else:
        output_tensor_fsl = output_dir + '/dti_FSL_TENSOR.nii.gz'
        output_tensor_nifti = output_dir + '/dti_TENSOR.nii.gz'
        output_tensor_mrtrix = output_dir + '/dti_MRTRIX_TENSOR.nii.gz'

        output_V1 = output_dir + '/dti_V1.nii.gz'
        output_V2 = output_dir + '/dti_V2.nii.gz'
        output_V3 = output_dir + '/dti_V3.nii.gz'
        output_FSL_V1 = output_dir + '/dti_FSL_V1.nii.gz'
        output_FSL_V2 = output_dir + '/dti_FSL_V2.nii.gz'
        output_FSL_V3 = output_dir + '/dti_FSL_V3.nii.gz'

        output_L1 = output_dir + '/dti_L1.nii.gz'
        output_L2 = output_dir + '/dti_L2.nii.gz'
        output_L3 = output_dir + '/dti_L3.nii.gz'

        output_fa = output_dir + '/dti_FA.nii.gz'
        output_md = output_dir + '/dti_MD.nii.gz'
        output_rd = output_dir + '/dti_RD.nii.gz'
        output_ad = output_dir + '/dti_AD.nii.gz'
        output_tr = output_dir + '/dti_TRACE.nii.gz'

        output_ga = output_dir + '/dti_GA.nii.gz'
        output_color_fa = output_dir + '/dti_COLOR_FA.nii.gz'

        output_PL = output_dir + '/dti_PLANARITY.nii.gz'
        output_SP = output_dir + '/dti_SPHERICITY.nii.gz'
        output_MO = output_dir + '/dti_MODE.nii.gz'

        output_res = output_dir + '/dti_RESIDUALS.nii.gz'

    tensor_img = nifti1_symmat(tensor, ras_img.affine, ras_img.header)
    tensor_img.header.set_intent = 'NIFTI_INTENT_SYMMATRIX'
    tensor_img.to_filename(output_tensor_nifti)

    tensor_fsl = np.empty(tensor.shape)
    tensor_fsl[:, :, :, 0] = tensor[:, :, :, 0]
    tensor_fsl[:, :, :, 1] = tensor[:, :, :, 1]
    tensor_fsl[:, :, :, 2] = tensor[:, :, :, 3]
    tensor_fsl[:, :, :, 3] = tensor[:, :, :, 2]
    tensor_fsl[:, :, :, 4] = tensor[:, :, :, 4]
    tensor_fsl[:, :, :, 5] = tensor[:, :, :, 5]
    save_nifti(output_tensor_fsl, tensor_fsl, ras_img.affine, ras_img.header)

    tensor_mrtrix = np.empty(tensor.shape)
    tensor_mrtrix[:, :, :, 0] = tensor[:, :, :, 0]
    tensor_mrtrix[:, :, :, 1] = tensor[:, :, :, 2]
    tensor_mrtrix[:, :, :, 2] = tensor[:, :, :, 5]
    tensor_mrtrix[:, :, :, 3] = tensor[:, :, :, 1]
    tensor_mrtrix[:, :, :, 4] = tensor[:, :, :, 3]
    tensor_mrtrix[:, :, :, 5] = tensor[:, :, :, 4]
    save_nifti(output_tensor_mrtrix, tensor_mrtrix, ras_img.affine,
               ras_img.header)

    fa = dti_fit.fa
    color_fa = dti_fit.color_fa
    md = dti_fit.md
    rd = dti_fit.rd
    ad = dti_fit.ad
    ga = dti_fit.ga
    trace = dti_fit.trace
    dti_mode = dti_fit.mode
    dti_planarity = dti_fit.planarity
    dti_sphericity = dti_fit.sphericity

    #Remove any nan
    fa[np.isnan(fa)] = 0
    color_fa[np.isnan(color_fa)] = 0
    md[np.isnan(md)] = 0
    rd[np.isnan(rd)] = 0
    ad[np.isnan(ad)] = 0
    ga[np.isnan(ga)] = 0
    trace[np.isnan(trace)] = 0
    dti_mode[np.isnan(dti_mode)] = 0
    dti_planarity[np.isnan(dti_planarity)] = 0
    dti_sphericity[np.isnan(dti_sphericity)] = 0

    save_nifti(output_V1, evecs[:, :, :, :, 0], ras_img.affine, ras_img.header)
    save_nifti(output_V2, evecs[:, :, :, :, 1], ras_img.affine, ras_img.header)
    save_nifti(output_V3, evecs[:, :, :, :, 2], ras_img.affine, ras_img.header)

    save_nifti(output_L1, evals[:, :, :, 0], ras_img.affine, ras_img.header)
    save_nifti(output_L2, evals[:, :, :, 1], ras_img.affine, ras_img.header)
    save_nifti(output_L3, evals[:, :, :, 2], ras_img.affine, ras_img.header)

    save_nifti(output_fa, fa, ras_img.affine, ras_img.header)
    save_nifti(output_color_fa, color_fa, ras_img.affine, ras_img.header)
    save_nifti(output_md, md, ras_img.affine, ras_img.header)
    save_nifti(output_ad, ad, ras_img.affine, ras_img.header)
    save_nifti(output_rd, rd, ras_img.affine, ras_img.header)
    save_nifti(output_ga, ga, ras_img.affine, ras_img.header)
    save_nifti(output_tr, trace, ras_img.affine, ras_img.header)
    save_nifti(output_PL, dti_planarity, ras_img.affine, ras_img.header)
    save_nifti(output_SP, dti_sphericity, ras_img.affine, ras_img.header)
    save_nifti(output_MO, dti_mode, ras_img.affine, ras_img.header)
    save_nifti(output_res, residuals, ras_img.affine, ras_img.header)

    #Reorient back to the original
    output_imgs.append(output_tensor_nifti)
    output_imgs.append(output_tensor_fsl)
    output_imgs.append(output_tensor_mrtrix)
    output_imgs.append(output_V1)
    output_imgs.append(output_V2)
    output_imgs.append(output_V3)
    output_imgs.append(output_L1)
    output_imgs.append(output_L2)
    output_imgs.append(output_L3)
    output_imgs.append(output_fa)
    output_imgs.append(output_md)
    output_imgs.append(output_rd)
    output_imgs.append(output_ad)
    output_imgs.append(output_ga)
    output_imgs.append(output_color_fa)
    output_imgs.append(output_PL)
    output_imgs.append(output_SP)
    output_imgs.append(output_MO)
    output_imgs.append(output_res)

    #Change orientation back to the original orientation
    orig_ornt = nib.io_orientation(ras_img.affine)
    targ_ornt = nib.io_orientation(img.affine)
    transform = nib.orientations.ornt_transform(orig_ornt, targ_ornt)
    affine_xfm = nib.orientations.inv_ornt_aff(transform, ras_img.shape)
    trans_mat = affine_xfm[0:3, 0:3]

    for img_path in output_imgs:
        orig_img = nib.load(img_path)
        reoriented = orig_img.as_reoriented(transform)
        reoriented.to_filename(img_path)

    #Correct FSL tensor for orientation
    dirs = []
    dirs.append(np.array([[1], [0], [0]]))
    dirs.append(np.array([[1], [1], [0]]))
    dirs.append(np.array([[1], [0], [1]]))
    dirs.append(np.array([[0], [1], [0]]))
    dirs.append(np.array([[0], [1], [1]]))
    dirs.append(np.array([[0], [0], [1]]))

    tensor_fsl = nib.load(output_tensor_fsl)
    corr_fsl_tensor = np.empty(tensor_fsl.get_data().shape)

    for i in range(0, len(dirs)):

        rot_dir = np.matmul(trans_mat, dirs[i])
        sign = 1.0
        if np.sum(rot_dir) == 0.0:
            sign = -1.0

        if (np.absolute(rot_dir) == np.array([[1], [0], [0]])).all():
            tensor_ind = 0
        elif (np.absolute(rot_dir) == np.array([[1], [1], [0]])).all():
            tensor_ind = 1
        elif (np.absolute(rot_dir) == np.array([[1], [0], [1]])).all():
            tensor_ind = 2
        elif (np.absolute(rot_dir) == np.array([[0], [1], [0]])).all():
            tensor_ind = 3
        elif (np.absolute(rot_dir) == np.array([[0], [1], [1]])).all():
            tensor_ind = 4
        elif (np.absolute(rot_dir) == np.array([[0], [0], [1]])).all():
            tensor_ind = 5

        corr_fsl_tensor[:, :, :,
                        i] = sign * tensor_fsl.get_data()[:, :, :, tensor_ind]

    save_nifti(output_tensor_fsl, corr_fsl_tensor, tensor_fsl.affine,
               tensor_fsl.header)

    #Now correct the eigenvectors
    #Determine the order to rearrange
    vec_order = np.transpose(targ_ornt[:, 0]).astype(int)
    sign_order = np.transpose(targ_ornt[:, 1]).astype(int)

    fsl_v1 = nib.load(output_V1)
    corr_fsl_v1 = fsl_v1.get_data()[:, :, :, vec_order]
    for i in range(0, 2):
        corr_fsl_v1[:, :, :, i] = sign_order[i] * corr_fsl_v1[:, :, :, i]

    save_nifti(output_FSL_V1, corr_fsl_v1, fsl_v1.affine, fsl_v1.header)

    fsl_v2 = nib.load(output_V2)
    corr_fsl_v2 = fsl_v2.get_data()[:, :, :, vec_order]
    for i in range(0, 2):
        corr_fsl_v2[:, :, :, i] = sign_order[i] * corr_fsl_v2[:, :, :, i]

    save_nifti(output_FSL_V2, corr_fsl_v2, fsl_v2.affine, fsl_v2.header)

    fsl_v3 = nib.load(output_V3)
    corr_fsl_v3 = fsl_v3.get_data()[:, :, :, vec_order]
    for i in range(0, 2):
        corr_fsl_v3[:, :, :, i] = sign_order[i] * corr_fsl_v3[:, :, :, i]

    save_nifti(output_FSL_V3, corr_fsl_v3, fsl_v3.affine, fsl_v3.header)
Beispiel #11
0
    data = img.get_data()
    affine = img.get_affine()

    # Get the optional params:
    fit_method = metadata.get('fit_method', "WLS")
    fmask = metadata.get('fmask', None)
    if fmask is None:
        mask = None
    else:
        mask = nib.load(fmask).get_data().astype(bool)

    # Fit the model:
    tenmodel = dti.TensorModel(gtab, fit_method=fit_method)
    tenfit = tenmodel.fit(data, mask=mask)

    # Extract the nifti convention parameters:
    lower_triangular = tenfit.lower_triangular()
    lower_triangular = lower_triangular.astype('float32')
    tensor_img = nifti1_symmat(lower_triangular, affine)

    # The output will all have the same basic name as the data file-name:
    root = op.join("/output",
                   op.splitext(op.splitext(op.split(fdata)[-1])[0])[0])
    
    # Save to file:
    dpsave(tensor_img, root + '_tensor.nii.gz')
    for arr, label in zip([tenfit.ad, tenfit.rd, tenfit.md, tenfit.fa],
                          ["_ad", "_rd", "_md", "_fa"]):
        dpsave(nib.Nifti1Image(arr.astype("float32"), affine),
               op.join('/output/', root + '%s.nii.gz'%label))