Ejemplo n.º 1
0
    def main(self):
        if isNifti(self.dwi):
            fsl_extract_b0(self.dwi, self.out)
        elif isNrrd(self.dwi):
            nrrd_extract_b0(self.dwi, self.out)
        else:
            raise Exception("Invalid dwi format, must be nrrd or nifti")

        if self.dwimask:
            from plumbum.cmd import ImageMath
            ImageMath(3, self.out, 'm', self.out, self.dwimask)
Ejemplo n.º 2
0
    def main(self):
        fshome = local.path(os.getenv('FREESURFER_HOME'))

        if not fshome:
            logging.error('Set FREESURFER_HOME first.')
            sys.exit(1)

        if not self.force and self.out.exists():
            logging.error(
                'Output directory exists, use -f/--force to force an overwrite.'
            )
            sys.exit(1)

        with TemporaryDirectory() as tmpdir, local.env(SUBJECTS_DIR=tmpdir,
                                                       FSFAST_HOME='',
                                                       MNI_DIR=''):

            if self.t1mask:
                logging.info('Mask the t1')
                ImageMath('3', tmpdir / 't1masked.nii.gz', 'm', self.t1,
                          self.t1mask)
                t1 = tmpdir / 't1masked.nii.gz'
                skullstrip = '-noskullstrip'
            else:
                skullstrip = ''
                if '.nrrd' in self.t1.suffixes or '.nhdr' in self.t1.suffixes:
                    logging.info('t1 is in nrrd format, convert to nifti')
                    t1 = tmpdir / 't1.nii.gz'
                    ConvertBetweenFileFormats(self.t1, t1)

            logging.info("Run freesurfer on " + t1)
            subjid = t1.stem

            from plumbum.cmd import bash
            bash['-c',
                 'source ' + fshome + '/FreeSurferEnv.sh; recon-all -s ' +
                 subjid + ' -i ' + t1 + ' -autorecon1 ' + skullstrip] & FG
            (tmpdir / subjid / 'mri/T1.mgz').copy(tmpdir / subjid /
                                                  'mri/brainmask.mgz')
            bash['-c', 'source ' + fshome +
                 '/FreeSurferEnv.sh; recon-all -autorecon2 -subjid ' +
                 subjid] & FG
            bash['-c', 'source ' + fshome +
                 '/FreeSurferEnv.sh; recon-all -autorecon3 -subjid ' +
                 subjid] & FG
            logging.info("Freesurfer done.")

            (tmpdir / subjid).copy(self.out,
                                   override=True)  # overwrites existing
            logging.info("Made " + self.out)
Ejemplo n.º 3
0
    def main(self):

        prefix = self.dwi.name.split('.')[0]
        directory = self.dwi.parent

        self.b0_threshold = float(self.b0_threshold)

        if self.out is None:
            self.out = os.path.join(directory, prefix + '_bse.nii.gz')

        if self.dwi.endswith('.nii') or self.dwi.endswith('.nii.gz'):

            if not self.bval_file:
                self.bval_file = os.path.join(directory, prefix + '.bval')

            bvals = read_bvals(self.bval_file)
            idx = np.where([bval < self.b0_threshold for bval in bvals])[0]

            if len(idx) > 1:

                # default is the first b0
                if not (self.minimum or self.average or self.all):
                    fslroi[self.dwi, self.out, idx, 1] & FG

                elif self.minimum:
                    fslroi[self.dwi, self.out, idx, np.argsort(bvals)[0]] & FG

                elif self.average:
                    # Load the given dwi to get image data
                    dwi = load_nifti(self.dwi._path)
                    hdr = dwi.header
                    mri = dwi.get_data()

                    avg_bse = np.mean(mri[:, :, :, idx], axis=3)

                    # Now write back the average bse
                    save_nifti(self.out, avg_bse, dwi.affine, hdr)

                elif self.all:
                    fslroi[self.dwi, self.out, idx, len(idx)] & FG

            else:
                raise Exception('No b0 image found. Check the bval file.')

        else:
            raise Exception("Invalid dwi format, must be a nifti image")

        if self.dwimask:
            ImageMath(3, self.out, 'm', self.out, self.dwimask)
Ejemplo n.º 4
0
    def main(self):

        with tempfile.TemporaryDirectory() as tmpdir:

            tmpdir = local.path(tmpdir)

            b0masked = tmpdir / "b0masked.nii.gz"  # Sylvain wants both
            b0maskedbrain = tmpdir / "b0maskedbrain.nii.gz"

            t2masked = tmpdir / 't2masked.nii.gz'
            print('Masking the T2')
            ImageMath(3, t2masked, 'm', self.t2, self.t2mask)

            brain = tmpdir / "brain.nii.gz"
            wmparc = tmpdir / "wmparc.nii.gz"

            brainmgz = self.parent.fsdir / 'mri/brain.mgz'
            wmparcmgz = self.parent.fsdir / 'mri/wmparc.mgz'

            wmparcindwi = tmpdir / 'wmparcInDwi.nii.gz'  # Sylvain wants both
            wmparcinbrain = tmpdir / 'wmparcInBrain.nii.gz'

            print(
                "Making brain.nii.gz and wmparc.nii.gz from their mgz versions"
            )

            vol2vol = local[self.parent.fshome / 'bin/mri_vol2vol']
            label2vol = local[self.parent.fshome / 'bin/mri_label2vol']

            with local.env(SUBJECTS_DIR=''):
                vol2vol('--mov', brainmgz, '--targ', brainmgz, '--regheader',
                        '--o', brain)
                label2vol('--seg', wmparcmgz, '--temp', brainmgz,
                          '--regheader', wmparcmgz, '--o', wmparc)

            print('Extracting B0 from DWI and masking it')
            check_call((' ').join([
                pjoin(FILEDIR, 'bse.py'), '-i', self.parent.dwi, '-m',
                self.parent.dwimask, '-o', b0masked
            ]),
                       shell=True)
            print('Made masked B0')

            # rigid registration from t2 to brain.nii.gz
            pre = tmpdir / 'BrainToT2'
            BrainToT2Affine = pre + '0GenericAffine.mat'

            print('Computing rigid registration from brain.nii.gz to t2')
            rigid_registration(3, brain, t2masked, pre)
            # generates three files for rigid registration:
            # pre0GenericAffine.mat  preInverseWarped.nii.gz  preWarped.nii.gz

            # generates five files for default(rigid+affine+deformable syn) registration:
            # pre0GenericAffine.mat  pre1Warp.nii.gz  preWarped.nii.gz   pre1InverseWarp.nii.gz  preInverseWarped.nii.gz

            dwi_res = load_nifti(
                str(b0masked)).header['pixdim'][1:4].round(decimals=2)
            brain_res = load_nifti(
                str(brain)).header['pixdim'][1:4].round(decimals=2)
            print(f'DWI resolution: {dwi_res}')
            print(f'FreeSurfer brain resolution: {brain_res}')

            print('Registering wmparc to B0 through T2')
            registerFs2Dwi_T2(tmpdir, 'fsbrainToT2ToB0', b0masked, t2masked,
                              BrainToT2Affine, wmparc, wmparcindwi)

            if (dwi_res != brain_res).any():
                print(
                    'DWI resolution is different from FreeSurfer brain resolution'
                )
                print(
                    'wmparc wil be registered to both DWI and brain resolution'
                )
                print(
                    'Check output files wmparcInDwi.nii.gz and wmparcInBrain.nii.gz'
                )

                print('Resampling B0 to brain resolution')

                ResampleImageBySpacing('3', b0masked, b0maskedbrain,
                                       brain_res.tolist())

                print('Registering wmparc to resampled B0')
                registerFs2Dwi_T2(tmpdir, 'fsbrainToT2ToResampledB0',
                                  b0maskedbrain, t2masked, BrainToT2Affine,
                                  wmparc, wmparcinbrain)

            # copying images to outDir
            b0masked.copy(self.parent.out)
            wmparcindwi.copy(self.parent.out)

            if b0maskedbrain.exists():
                b0maskedbrain.copy(self.parent.out)
                wmparcinbrain.copy(self.parent.out)

            if self.parent.debug:
                tmpdir.copy(self.parent.out,
                            'fs2dwi-debug-' + str(os.getpid()))

        print('See output files in ', self.parent.out._path)
Ejemplo n.º 5
0
    def main(self):
        fshome = local.path(os.getenv('FREESURFER_HOME'))

        if not fshome:
            logging.error('Set FREESURFER_HOME first.')
            sys.exit(1)

        if not self.force and os.path.exists(self.out):
            logging.error(
                'Output directory exists, use -f/--force to force an overwrite.'
            )
            sys.exit(1)

        if self.t2mask and not self.t2:
            raise AttributeError('--t2mask is invalid without --t2')

        with TemporaryDirectory() as tmpdir, local.env(SUBJECTS_DIR=tmpdir,
                                                       FSFAST_HOME='',
                                                       MNI_DIR=''):

            tmpdir = local.path(tmpdir)

            if self.t1mask:
                logging.info('Mask the t1')
                t1 = tmpdir / 't1masked.nii.gz'
                ImageMath('3', t1, 'm', self.t1, self.t1mask)

            else:
                t1 = tmpdir / 't1.nii.gz'
                self.t1.copy(t1)

            subjid = self.t1.stem
            common_params = ['-s', subjid]

            autorecon3_params = []
            if self.t2:
                if self.t2mask:
                    logging.info('Mask the t2')
                    t2 = tmpdir / 't2masked.nii.gz'
                    ImageMath('3', t2, 'm', self.t2, self.t2mask)

                else:
                    t2 = tmpdir / 't2.nii.gz'
                    self.t2.copy(t2)

                autorecon3_params = ['-T2', t2, '-T2pial']

            if self.subfields:
                autorecon3_params += ['-subfields']

            logging.info("Running freesurfer on " + t1)

            if self.ncpu == '-1':
                self.ncpu = str(N_CPU)

            if int(self.ncpu) > 1:
                common_params += ['-parallel', '-openmp', self.ncpu]

            autorecon1_params = []
            if not self.no_hires:
                common_params.append('-hires')
                autorecon1_params = ['-expert', self.expert_file]

            if self.no_rand:
                common_params.append('-norandomness')

            # run recon_all in three steps so we can overwrite/provide MABS masked T1
            # -noskullstrip is used with -autorecon1 only, so we need to check whether T1 is masked/T1 mask is provided
            # irrespective of masked/unmasked T2
            if self.t1mask or self.no_skullstrip:
                recon_all['-i', t1, common_params, '-autorecon1',
                          autorecon1_params, '-noskullstrip'] & FG
                (tmpdir / subjid / 'mri/T1.mgz').copy(tmpdir / subjid /
                                                      'mri/brainmask.mgz')
            else:
                recon_all['-i', t1, common_params, '-autorecon1',
                          autorecon1_params] & FG

            recon_all[common_params, '-autorecon2'] & FG
            recon_all[common_params, '-autorecon3', autorecon3_params] & FG

            logging.info("Freesurfer done.")

            (tmpdir / subjid).copy(
                self.out, override=True)  # overwrites any existing directory
            logging.info("Made " + self.out)
Ejemplo n.º 6
0
    def main(self):

        ImageMath(self.dim, self.out, 'm', self.img, self.mask)
Ejemplo n.º 7
0
    def main(self):
        fshome = local.path(os.getenv('FREESURFER_HOME'))

        if not fshome:
            logging.error('Set FREESURFER_HOME first.')
            sys.exit(1)

        if not self.force and os.path.exists(self.out):
            logging.error(
                'Output directory exists, use -f/--force to force an overwrite.'
            )
            sys.exit(1)

        with TemporaryDirectory() as tmpdir, local.env(SUBJECTS_DIR=tmpdir,
                                                       FSFAST_HOME='',
                                                       MNI_DIR=''):

            if self.t1mask:
                logging.info('Mask the t1')
                t1 = tmpdir / 't1masked.nii.gz'
                ImageMath('3', t1, 'm', self.t1, self.t1mask)
                skullstrip = '-noskullstrip'

            else:
                skullstrip = '-skullstrip'
                t1 = tmpdir / 't1.nii.gz'
                self.t1.copy(t1)

            if self.t2mask:
                logging.info('Mask the t2')
                t2 = tmpdir / 't2masked.nii.gz'
                ImageMath('3', t2, 'm', self.t2, self.t2mask)
                skullstrip = '-noskullstrip'

            else:
                skullstrip = '-skullstrip'
                t2 = tmpdir / 't2.nii.gz'
                self.t2.copy(t2)

            logging.info("Run freesurfer on " + t1)
            subjid = t1.stem

            if self.ncpu == '-1':
                self.ncpu = N_CPU

            if int(self.ncpu) > 1:

                if self.t2:
                    bash['-c', 'recon-all -s ' + subjid + ' -i ' + t1 +
                         ' -T2 ' + t2 + ' -autorecon1 ' + skullstrip +
                         ' -parallel -openmp ' + self.ncpu] & FG
                else:
                    bash['-c', 'recon-all -s ' + subjid + ' -i ' + t1 +
                         ' -autorecon1 ' + skullstrip + ' -parallel -openmp ' +
                         self.ncpu] & FG
                (tmpdir / subjid / 'mri/T1.mgz').copy(tmpdir / subjid /
                                                      'mri/brainmask.mgz')
                bash['-c', 'recon-all -autorecon2 -subjid ' + subjid +
                     ' -parallel -openmp ' + self.ncpu] & FG
                bash['-c', 'recon-all -autorecon3 -subjid ' + subjid +
                     ' -parallel -openmp ' + self.ncpu] & FG

            else:  # intentionally writing a separate block omitting parallelization attributes
                if self.t2:
                    bash['-c', 'recon-all -s ' + subjid + ' -i ' + t1 +
                         ' -T2 ' + t2 + ' -autorecon1 ' + skullstrip] & FG
                else:
                    bash['-c', 'recon-all -s ' + subjid + ' -i ' + t1 +
                         ' -autorecon1 ' + skullstrip] & FG
                (tmpdir / subjid / 'mri/T1.mgz').copy(tmpdir / subjid /
                                                      'mri/brainmask.mgz')
                bash['-c', 'recon-all -autorecon2 -subjid ' + subjid] & FG
                bash['-c', 'recon-all -autorecon3 -subjid ' + subjid] & FG

            logging.info("Freesurfer done.")

            (tmpdir / subjid).copy(
                self.out, override=True)  # overwrites any existing directory
            logging.info("Made " + self.out)