示例#1
0
def test_streams2graph(fa_wei):
    from dipy.core.gradients import gradient_table
    from dipy.io import save_pickle

    base_dir = str(Path(__file__).parent/"examples")
    dwi_file = f"{base_dir}/003/test_out/003/dwi/sub-003_dwi_reor-RAS_res-2mm.nii.gz"
    conn_model = 'csd'
    min_length = 10
    error_margin = 2
    directget = 'prob'
    track_type = 'particle'
    target_samples = 500
    overlap_thr = 1
    min_span_tree = True
    prune = 3
    norm = 6
    binary = False
    roi = f"{base_dir}/miscellaneous/pDMN_3_bin.nii.gz"
    network = 'Default'
    ID = '003'
    parc = True
    disp_filt = False
    node_size = None
    dens_thresh = False
    atlas = 'whole_brain_cluster_labels_PCA200'
    uatlas = None
    coord_file_path = f"{base_dir}/miscellaneous/Default_func_coords_wb.pkl"
    coord_file = open(coord_file_path, 'rb')
    coords = pickle.load(coord_file)
    labels_file_path = f"{base_dir}/miscellaneous/Default_func_labelnames_wb.pkl"
    labels_file = open(labels_file_path, 'rb')
    labels = pickle.load(labels_file)
    # Not actually normalized to mni-space in this test.
    atlas_mni = f"{base_dir}/003/dmri/whole_brain_cluster_labels_PCA200_dwi_track.nii.gz"
    streams = f"{base_dir}/miscellaneous/003_streamlines_est-csd_nodetype-parc_samples-1000streams_tt-particle_dg-prob_ml-10.trk"
    B0_mask = f"{base_dir}/003/anat/mean_B0_bet_mask_tmp.nii.gz"
    dir_path = f"{base_dir}/003/dmri"
    bvals = f"{dir_path}/sub-003_dwi.bval"
    bvecs = f"{base_dir}/003/test_out/003/dwi/bvecs_reor.bvec"
    gtab_file = f"{base_dir}/gtab.pkl"
    gtab = gradient_table(bvals, bvecs)
    gtab.b0_threshold = 50
    gtab_bvals = gtab.bvals.copy()
    b0_thr_ixs = np.where(gtab_bvals < gtab.b0_threshold)[0]
    gtab_bvals[b0_thr_ixs] = 0
    gtab.b0s_mask = gtab_bvals == 0
    save_pickle(gtab_file, gtab)
    # Not actually normalized to mni-space in this test.
    warped_fa = tens_mod_fa_est(gtab_file, dwi_file, B0_mask)[0]

    conn_matrix = streams2graph(atlas_mni, streams, overlap_thr, dir_path, track_type, target_samples,
                                conn_model, network, node_size, dens_thresh, ID, roi, min_span_tree,
                                disp_filt, parc, prune, atlas, uatlas, labels, coords, norm, binary,
                                directget, warped_fa, error_margin, min_length, fa_wei)[2]
    assert conn_matrix is not None
示例#2
0
def test_tens_mod_fa_est(dmri_estimation_data):
    """Test tensor FA image estimation."""

    gtab = dmri_estimation_data['gtab']
    dwi_img = dmri_estimation_data['dwi_img']
    B0_mask_img = dmri_estimation_data['B0_mask_img']

    gtab_file = tempfile.NamedTemporaryFile(mode='w+', suffix='.pkl')
    dwi_file = tempfile.NamedTemporaryFile(mode='w+', suffix='.nii.gz')
    B0_mask_file = tempfile.NamedTemporaryFile(mode='w+', suffix='.nii.gz')

    save_pickle(gtab_file.name, gtab)
    nib.save(dwi_img, dwi_file.name)
    nib.save(B0_mask_img, B0_mask_file.name)

    [fa_path, _, _, _] = \
        tens_mod_fa_est(gtab_file.name, dwi_file.name, B0_mask_file.name)

    assert os.path.isfile(fa_path)

    gtab_file.close()
    dwi_file.close()
    B0_mask_file.close()
示例#3
0
def test_create_anisopowermap(dmri_estimation_data):
    """ Test creating an anisotropic power map."""

    gtab = dmri_estimation_data['gtab']
    dwi_img = dmri_estimation_data['dwi_img']
    B0_mask_img = dmri_estimation_data['B0_mask_img']

    gtab_file = tempfile.NamedTemporaryFile(mode='w+', suffix='.pkl')
    dwi_file = tempfile.NamedTemporaryFile(mode='w+', suffix='.nii.gz')
    B0_mask_file = tempfile.NamedTemporaryFile(mode='w+', suffix='.nii.gz')

    save_pickle(gtab_file.name, gtab)
    nib.save(dwi_img, dwi_file.name)
    nib.save(B0_mask_img, B0_mask_file.name)

    [anisopwr_path, _, _, _] = \
        create_anisopowermap(gtab_file.name, dwi_file.name, B0_mask_file.name)

    assert os.path.isfile(anisopwr_path)

    gtab_file.close()
    dwi_file.close()
    B0_mask_file.close()
示例#4
0
def test_streams2graph(fa_wei, dsn):
    from dipy.core.gradients import gradient_table
    from pynets.registration import register
    from pynets.core import nodemaker
    from dipy.io import save_pickle
    import os

    base_dir = str(Path(__file__).parent / "examples")
    dwi_file = f"{base_dir}/003/test_out/003/dwi/sub-003_dwi_reor-RAS_res-2mm.nii.gz"
    conn_model = 'csd'
    min_length = 10
    error_margin = 2
    directget = 'prob'
    track_type = 'particle'
    target_samples = 500
    overlap_thr = 1
    min_span_tree = True
    prune = 3
    norm = 6
    binary = False
    roi = f"{base_dir}/miscellaneous/pDMN_3_bin.nii.gz"
    network = 'Default'
    ID = '003'
    parc = True
    disp_filt = False
    node_size = None
    dens_thresh = False
    atlas = 'whole_brain_cluster_labels_PCA200'
    uatlas = f"{base_dir}/miscellaneous/whole_brain_cluster_labels_PCA200.nii.gz"
    t1_aligned_mni = f"{base_dir}/miscellaneous/whole_brain_cluster_labels_PCA200.nii.gz"
    atlas_dwi = f"{base_dir}/003/dmri/whole_brain_cluster_labels_PCA200_dwi_track.nii.gz"
    streams = f"{base_dir}/miscellaneous/003_streamlines_est-csd_nodetype-parc_samples-1000streams_tt-particle_" \
        f"dg-prob_ml-10.trk"
    B0_mask = f"{base_dir}/003/anat/mean_B0_bet_mask_tmp.nii.gz"
    dir_path = f"{base_dir}/003/dmri"
    bvals = f"{dir_path}/sub-003_dwi.bval"
    bvecs = f"{base_dir}/003/test_out/003/dwi/bvecs_reor.bvec"
    gtab_file = f"{base_dir}/gtab.pkl"
    gtab = gradient_table(bvals, bvecs)
    gtab.b0_threshold = 50
    gtab_bvals = gtab.bvals.copy()
    b0_thr_ixs = np.where(gtab_bvals < gtab.b0_threshold)[0]
    gtab_bvals[b0_thr_ixs] = 0
    gtab.b0s_mask = gtab_bvals == 0
    save_pickle(gtab_file, gtab)
    fa_path = tens_mod_fa_est(gtab_file, dwi_file, B0_mask)[0]

    coords = nodemaker.get_names_and_coords_of_parcels(uatlas)[0]
    labels = np.arange(len(coords) +
                       1)[np.arange(len(coords) + 1) != 0].tolist()

    # if dsn is True:
    #     os.makedirs(f"{dir_path}/dmri_reg/DSN", exist_ok=True)
    #     (streams_mni, dir_path, track_type, target_samples, conn_model, network, node_size, dens_thresh, ID, roi,
    #      min_span_tree, disp_filt, parc, prune, atlas, uatlas, labels, coords, norm, binary, atlas_mni, directget,
    #      warped_fa, min_length, error_margin) = register.direct_streamline_norm(streams, fa_path, fa_path, dir_path,
    #                                                                             track_type, target_samples, conn_model,
    #                                                                             network, node_size, dens_thresh, ID,
    #                                                                             roi, min_span_tree, disp_filt, parc,
    #                                                                             prune, atlas, atlas_dwi, uatlas,
    #                                                                             labels, coords, norm, binary, uatlas,
    #                                                                             dir_path, [0.1, 0.2], [40, 30],
    #                                                                             directget, min_length, t1_aligned_mni,
    #                                                                             error_margin)
    #
    #     conn_matrix = streams2graph(atlas_mni, streams_mni, overlap_thr, dir_path, track_type, target_samples,
    #                                 conn_model, network, node_size, dens_thresh, ID, roi, min_span_tree,
    #                                 disp_filt, parc, prune, atlas, uatlas, labels, coords, norm, binary,
    #                                 directget, warped_fa, error_margin, min_length, fa_wei)[2]
    # else:
    #     conn_matrix = streams2graph(atlas_dwi, streams, overlap_thr, dir_path, track_type, target_samples,
    #                                 conn_model, network, node_size, dens_thresh, ID, roi, min_span_tree,
    #                                 disp_filt, parc, prune, atlas, atlas_dwi, labels, coords, norm, binary,
    #                                 directget, fa_path, error_margin, min_length, fa_wei)[2]

    conn_matrix = streams2graph(
        atlas_dwi, streams, overlap_thr, dir_path, track_type, target_samples,
        conn_model, network, node_size, dens_thresh, ID, roi, min_span_tree,
        disp_filt, parc, prune, atlas, atlas_dwi, labels, coords, norm, binary,
        directget, fa_path, error_margin, min_length, fa_wei)[2]

    assert conn_matrix is not None
示例#5
0
文件: utils.py 项目: Mozihua/PyNets
def make_gtab_and_bmask(fbval, fbvec, dwi_file):
    """

    :param fbval:
    :param fbvec:
    :param dwi_file:
    :return:
    """
    import os
    from dipy.io import save_pickle
    import os.path as op
    from dipy.io import read_bvals_bvecs
    from dipy.core.gradients import gradient_table
    from nilearn.image import mean_img
    from pynets.utils import rescale_bvec
    # """
    # Takes bval and bvec files and produces a structure in dipy format
    # **Positional Arguments:**
    # """
    # Use b0's from the DWI to create a more stable DWI image for registration
    outdir = op.dirname(dwi_file)

    nodif_b0 = "{}/nodif_b0.nii.gz".format(outdir)
    nodif_b0_bet = "{}/nodif_b0_bet.nii.gz".format(outdir)
    nodif_b0_mask = "{}/nodif_b0_bet_mask.nii.gz".format(outdir)
    bvec_rescaled = "{}/bvec_scaled.bvec".format(outdir)
    gtab_file = "{}/gtab.pkl".format(outdir)

    # loading bvecs/bvals
    bvals, bvecs = read_bvals_bvecs(fbval, fbvec)
    bvecs[np.where(np.any(abs(bvecs) >= 10, axis=1) == True)] = [1, 0, 0]
    bvecs[np.where(bvals == 0)] = 0
    if len(bvecs[np.where(np.logical_and(bvals > 50, np.all(abs(bvecs) == np.array([0, 0, 0]), axis=1)))]) > 0:
        raise ValueError('WARNING: Encountered potentially corrupted bval/bvecs. Check to ensure volumes with a '
                         'diffusion weighting are not being treated as B0\'s along the bvecs')
    np.savetxt(fbval, bvals)
    np.savetxt(fbvec, bvecs)
    bvec_rescaled = rescale_bvec(fbvec, bvec_rescaled)
    if fbval and bvec_rescaled:
        bvals, bvecs = read_bvals_bvecs(fbval, bvec_rescaled)
    else:
        raise ValueError('Either bvals or bvecs files not found (or rescaling failed)!')

    # Creating the gradient table
    gtab = gradient_table(bvals, bvecs)

    # Correct b0 threshold
    gtab.b0_threshold = min(bvals)

    # Get b0 indices
    b0s = np.where(gtab.bvals == gtab.b0_threshold)[0]
    print("%s%s" % ('b0\'s found at: ', b0s))

    # Show info
    print(gtab.info)

    # Save gradient table to pickle
    save_pickle(gtab_file, gtab)

    # Extract and Combine all b0s collected
    print('Extracting b0\'s...')
    cmds = []
    b0s_bbr = []
    for b0 in b0s:
        print(b0)
        b0_bbr = "{}/{}_b0.nii.gz".format(outdir, str(b0))
        cmds.append('fslroi {} {} {} 1'.format(dwi_file, b0_bbr, str(b0), ' 1'))
        b0s_bbr.append(b0_bbr)

    for cmd in cmds:
        os.system(cmd)

    # Get mean b0
    mean_b0 = mean_img(b0s_bbr)
    nib.save(mean_b0, nodif_b0)

    # Get mean b0 brain mask
    os.system("bet {} {} -m -f 0.2".format(nodif_b0, nodif_b0_bet))
    return gtab_file, nodif_b0_bet, nodif_b0_mask, dwi_file
示例#6
0
 def save_affine(fname, affine_):
     dio.save_pickle('affine', affine_)
示例#7
0
def test_streams2graph(dmri_estimation_data,
                       tractography_estimation_data,
                       random_mni_roi_data,
                       dsn=False):
    from pynets.registration.register import direct_streamline_norm
    from dipy.core.gradients import gradient_table
    from dipy.io import save_pickle
    import random
    import pkg_resources

    tmp = tempfile.TemporaryDirectory()
    dir_path = str(tmp.name)
    os.makedirs(dir_path, exist_ok=True)

    dwi_file = dmri_estimation_data['dwi_file']
    conn_model = 'csd'
    min_length = 10
    error_margin = 5
    traversal = 'prob'
    track_type = 'local'
    min_span_tree = False
    prune = 3
    norm = 6
    binary = False
    roi = random_mni_roi_data['roi_file']
    subnet = 'Default'
    ID = '003'
    parc = True
    disp_filt = False
    node_radius = None
    dens_thresh = False
    atlas = 'whole_brain_cluster_labels_PCA200'
    parcellation = pkg_resources.resource_filename(
        "pynets", "templates/atlases/whole_brain_cluster_labels_PCA200.nii.gz")
    streams = tractography_estimation_data['trk']
    B0_mask = dmri_estimation_data['B0_mask']
    bvals = dmri_estimation_data['fbvals']
    bvecs = dmri_estimation_data['fbvecs']
    gtab_file = dmri_estimation_data['gtab_file']
    gtab = gradient_table(bvals, bvecs)
    gtab.b0_threshold = 50
    gtab_bvals = gtab.bvals.copy()
    b0_thr_ixs = np.where(gtab_bvals < gtab.b0_threshold)[0]
    gtab_bvals[b0_thr_ixs] = 0
    gtab.b0s_mask = gtab_bvals == 0
    save_pickle(gtab_file, gtab)
    fa_path = tens_mod_fa_est(gtab_file, dwi_file, B0_mask)[0]
    ap_path = create_anisopowermap(gtab_file, dwi_file, B0_mask)[0]
    t1w_brain = dmri_estimation_data['t1w_file']
    t1w_gm = dmri_estimation_data['f_pve_gm']
    atlas_in_dwi = fname_presuffix(ap_path,
                                   suffix="atlas_in_dwi",
                                   use_ext=True)
    resample_to_img(nib.load(parcellation),
                    nib.load(fa_path),
                    interpolation="nearest").to_filename(atlas_in_dwi)

    coords = [
        (random.random() * 2.0, random.random() * 2.0, random.random() * 2.0)
        for _ in range(len(np.unique(nib.load(atlas_in_dwi).get_fdata())) - 1)
    ]
    labels = np.arange(len(coords) +
                       1)[np.arange(len(coords) + 1) != 0].tolist()

    if dsn is True:
        os.makedirs(f"{dir_path}/dmri_reg/DSN", exist_ok=True)
        (streams, dir_path, track_type, conn_model, subnet, node_radius,
         dens_thresh, ID, roi, min_span_tree, disp_filt, parc, prune, atlas,
         parcellation, labels, coords, norm, binary, atlas_for_streams,
         traversal, fa_path,
         min_length) = direct_streamline_norm(streams,
                                              fa_path,
                                              ap_path,
                                              dir_path,
                                              track_type,
                                              conn_model,
                                              subnet,
                                              node_radius,
                                              dens_thresh,
                                              ID,
                                              roi,
                                              min_span_tree,
                                              disp_filt,
                                              parc,
                                              prune,
                                              atlas,
                                              atlas_in_dwi,
                                              parcellation,
                                              labels,
                                              coords,
                                              norm,
                                              binary,
                                              t1w_gm,
                                              dir_path, [0.1, 0.2], [40, 30],
                                              traversal,
                                              min_length,
                                              t1w_brain,
                                              run_dsn=True)

    conn_matrix = streams2graph(
        atlas_in_dwi, streams, os.path.dirname(streams), track_type,
        conn_model, subnet, node_radius, dens_thresh, ID, roi, min_span_tree,
        disp_filt, parc, prune, atlas, atlas_in_dwi, labels, coords, norm,
        binary, traversal, fa_path, min_length, error_margin)[2]

    assert conn_matrix is not None
示例#8
0
    def _run_interface(self, runtime):
        import os
        import time
        from dipy.io import save_pickle
        from dipy.io import read_bvals_bvecs
        from dipy.core.gradients import gradient_table
        from nipype.utils.filemanip import copyfile, fname_presuffix
        # from dipy.segment.mask import median_otsu
        from pynets.registration.utils import median
        from pynets.dmri.utils import normalize_gradients, extract_b0

        B0_bet = f"{runtime.cwd}/mean_B0_bet.nii.gz"
        B0_mask = f"{runtime.cwd}/mean_B0_bet_mask.nii.gz"
        fbvec_norm = f"{runtime.cwd}/bvec_normed.bvec"
        fbval_norm = f"{runtime.cwd}/bval_normed.bvec"
        gtab_file = f"{runtime.cwd}/gtab.pkl"
        all_b0s_file = f"{runtime.cwd}/all_b0s.nii.gz"

        fbval_tmp_path = fname_presuffix(self.inputs.fbval,
                                         suffix="_tmp",
                                         newpath=runtime.cwd)
        copyfile(self.inputs.fbval,
                 fbval_tmp_path,
                 copy=True,
                 use_hardlink=False)

        fbvec_tmp_path = fname_presuffix(self.inputs.fbvec,
                                         suffix="_tmp",
                                         newpath=runtime.cwd)
        copyfile(self.inputs.fbvec,
                 fbvec_tmp_path,
                 copy=True,
                 use_hardlink=False)

        # loading bvecs/bvals
        bvals, bvecs = read_bvals_bvecs(fbval_tmp_path, fbvec_tmp_path)
        bvecs_norm, bvals_norm = normalize_gradients(
            bvecs, bvals, b0_threshold=self.inputs.b0_thr)

        # Save corrected
        np.savetxt(fbval_norm, bvals_norm)
        np.savetxt(fbvec_norm, bvecs_norm)

        # Creating the gradient table
        gtab = gradient_table(bvals_norm, bvecs_norm)

        # Correct b0 threshold
        gtab.b0_threshold = self.inputs.b0_thr

        # Correct bvals to set 0's for B0 based on thresh
        gtab_bvals = gtab.bvals.copy()
        b0_thr_ixs = np.where(gtab_bvals < gtab.b0_threshold)[0]
        gtab_bvals[b0_thr_ixs] = 0
        gtab.b0s_mask = gtab_bvals == 0

        # Show info
        print(gtab.info)

        # Save gradient table to pickle
        save_pickle(gtab_file, gtab)

        dwi_file_tmp_path = fname_presuffix(self.inputs.dwi_file,
                                            suffix="_tmp",
                                            newpath=runtime.cwd)
        copyfile(self.inputs.dwi_file,
                 dwi_file_tmp_path,
                 copy=True,
                 use_hardlink=False)

        # Extract and Combine all b0s collected, make mean b0
        print("Extracting b0's...")
        all_b0s_file = extract_b0(dwi_file_tmp_path, b0_thr_ixs, all_b0s_file)
        med_b0_file = median(all_b0s_file)

        # TODO replace with bet and median_otsu with deep-learning classifier.

        # med_b0_img = nib.load(med_b0_file)
        # med_b0_data = np.asarray(med_b0_img.dataobj)
        # # Create mean b0 brain mask
        # b0_mask_data, mask_data = median_otsu(med_b0_data, median_radius=2,
        # numpass=1)
        #
        # hdr = med_b0_img.header.copy()
        # hdr.set_xyzt_units("mm")
        # hdr.set_data_dtype(np.float32)
        # nib.Nifti1Image(b0_mask_data, med_b0_img.affine,
        #                 hdr).to_filename(B0_bet)
        # nib.Nifti1Image(mask_data, med_b0_img.affine,
        #                 hdr).to_filename(B0_mask)

        # Get mean B0 brain mask
        cmd = f"bet {med_b0_file} {B0_bet} -m -f 0.2"
        os.system(cmd)
        time.sleep(2)

        self._results["gtab_file"] = gtab_file
        self._results["B0_bet"] = B0_bet
        self._results["B0_mask"] = B0_mask
        self._results["dwi_file"] = self.inputs.dwi_file

        tmp_files = [fbval_tmp_path, fbvec_tmp_path, dwi_file_tmp_path]
        for j in tmp_files:
            if j is not None:
                if os.path.isfile(j):
                    os.system(f"rm -f {j} &")

        return runtime
示例#9
0
def make_gtab_and_bmask(fbval,
                        fbvec,
                        dwi_file,
                        network,
                        node_size,
                        atlas,
                        b0_thr=50):
    """
    Create gradient table from bval/bvec, and a mean B0 brain mask.

    Parameters
    ----------
    fbval : str
        File name of the b-values file.
    fbvec : str
        File name of the b-vectors file.
    dwi_file : str
        File path to diffusion weighted image.
    network : str
        Resting-state network based on Yeo-7 and Yeo-17 naming (e.g. 'Default') used to filter nodes in the study of
        brain subgraphs.
    node_size : int
        Spherical centroid node size in the case that coordinate-based centroids
        are used as ROI's.
    atlas : str
        Name of a Nilearn-hosted coordinate or parcellation/label-based atlas supported for fetching.
        See Nilearn's datasets.atlas module for more detailed reference.

    Returns
    -------
    gtab_file : str
        File path to pickled DiPy gradient table object.
    nodif_b0_bet : str
        File path to mean brain-extracted B0 image.
    B0_mask : str
        File path to mean B0 brain mask.
    dwi_file : str
        File path to diffusion weighted image.
    """
    import os
    from dipy.io import save_pickle
    import os.path as op
    from dipy.io import read_bvals_bvecs
    from dipy.core.gradients import gradient_table
    from pynets.dmri.dmri_utils import make_mean_b0, normalize_gradients

    outdir = op.dirname(dwi_file)

    namer_dir = outdir + '/dmri_tmp'
    if not os.path.isdir(namer_dir):
        os.makedirs(namer_dir, exist_ok=True)

    B0_bet = "%s%s" % (namer_dir, "/mean_B0_bet.nii.gz")
    B0_mask = "%s%s" % (namer_dir, "/mean_B0_bet_mask.nii.gz")
    fbvec_norm = "%s%s" % (namer_dir, "/bvec_normed.bvec")
    fbval_norm = "%s%s" % (namer_dir, "/bval_normed.bvec")
    gtab_file = "%s%s" % (namer_dir, "/gtab.pkl")
    all_b0s_file = "%s%s" % (namer_dir, "/all_b0s.nii.gz")

    # loading bvecs/bvals
    bvals, bvecs = read_bvals_bvecs(fbval, fbvec)

    bvecs_norm, bvals_norm = normalize_gradients(bvecs,
                                                 bvals,
                                                 b0_threshold=b0_thr)

    # Save corrected
    np.savetxt(fbval_norm, bvals_norm)
    np.savetxt(fbvec_norm, bvecs_norm)

    # Creating the gradient table
    gtab = gradient_table(bvals_norm, bvecs_norm)

    # Correct b0 threshold
    gtab.b0_threshold = b0_thr

    # Get b0 indices
    b0s = np.where(gtab.bvals <= gtab.b0_threshold)[0]
    print("%s%s" % ('b0\'s found at: ', b0s))

    # Correct bvals to set 0's for B0 based on thresh
    gtab_bvals = gtab.bvals.copy()
    b0_thr_ixs = np.where(gtab_bvals < gtab.b0_threshold)[0]
    gtab_bvals[b0_thr_ixs] = 0
    gtab.b0s_mask = gtab_bvals == 0

    # Show info
    print(gtab.info)

    # Save gradient table to pickle
    save_pickle(gtab_file, gtab)

    # Extract and Combine all b0s collected, make mean b0
    print("Extracting b0's...")
    b0_vols = []
    dwi_img = nib.load(dwi_file)
    all_b0s_aff = dwi_img.affine.copy()
    dwi_data = np.asarray(dwi_img.dataobj)
    dwi_img.uncache()
    for b0 in b0s:
        print(b0)
        b0_vols.append(dwi_data[:, :, :, b0])

    all_b0s_aff[3][3] = len(b0_vols)
    nib.save(nib.Nifti1Image(np.stack(b0_vols, axis=3), affine=all_b0s_aff),
             all_b0s_file)
    mean_b0_file = make_mean_b0(all_b0s_file)

    # Create mean b0 brain mask
    cmd = 'bet ' + mean_b0_file + ' ' + B0_bet + ' -m -f 0.2'
    os.system(cmd)

    del dwi_data

    return gtab_file, B0_bet, B0_mask, dwi_file
示例#10
0
def make_gtab_and_bmask(fbval, fbvec, dwi_file):
    import os
    from dipy.io import save_pickle
    import os.path as op
    from dipy.io import read_bvals_bvecs
    from dipy.core.gradients import gradient_table
    from nilearn.image import mean_img
    from pynets.utils import rescale_bvec
    """
    Takes bval and bvec files and produces a structure in dipy format
    **Positional Arguments:**
    """
    # Use b0's from the DWI to create a more stable DWI image for registration
    outdir = op.dirname(dwi_file)

    nodif_b0 = "{}/nodif_b0.nii.gz".format(outdir)
    nodif_b0_bet = "{}/nodif_b0_bet.nii.gz".format(outdir)
    nodif_b0_mask = "{}/nodif_b0_bet_mask.nii.gz".format(outdir)
    bvec_rescaled = "{}/bvec_scaled.bvec".format(outdir)
    gtab_file = "{}/gtab.pkl".format(outdir)

    # loading bvecs/bvals
    bvals, bvecs = read_bvals_bvecs(fbval, fbvec)
    bvecs[np.where(np.any(abs(bvecs) >= 10, axis=1) == True)] = [1, 0, 0]
    bvecs[np.where(np.any(bvals == 0, axis=0) == True)] = 0
    np.savetxt(fbval, bvals)
    np.savetxt(fbvec, bvecs)
    bvec_rescaled = rescale_bvec(fbvec, bvec_rescaled)
    if fbval and bvec_rescaled:
        bvals, bvecs = read_bvals_bvecs(fbval, bvec_rescaled)
    else:
        raise ValueError(
            'Either bvals or bvecs files not found (or rescaling failed)!')

    # Creating the gradient table
    gtab = gradient_table(bvals, bvecs)

    # Correct b0 threshold
    gtab.b0_threshold = min(bvals)

    # Get b0 indices
    b0s = np.where(gtab.bvals == gtab.b0_threshold)[0]
    print("%s%s" % ('b0\'s found at: ', b0s))

    # Show info
    print(gtab.info)

    # Save gradient table to pickle
    save_pickle(gtab_file, gtab)

    # Extract and Combine all b0s collected
    print('Extracting b0\'s...')
    cmds = []
    b0s_bbr = []
    for b0 in b0s:
        print(b0)
        b0_bbr = "{}/{}_b0.nii.gz".format(outdir, str(b0))
        cmd = 'fslroi ' + dwi_file + ' ' + b0_bbr + ' ' + str(b0) + ' 1'
        cmds.append(cmd)
        b0s_bbr.append(b0_bbr)

    for cmd in cmds:
        os.system(cmd)

    # Get mean b0
    mean_b0 = mean_img(b0s_bbr)
    nib.save(mean_b0, nodif_b0)

    # Get mean b0 brain mask
    cmd = 'bet ' + nodif_b0 + ' ' + nodif_b0_bet + ' -m -f 0.2'
    os.system(cmd)
    return gtab_file, nodif_b0_bet, nodif_b0_mask, dwi_file
示例#11
0
文件: conftest.py 项目: dPys/PyNets
def dmri_estimation_data():
    """Fixture for dmri estimation tests."""

    dpd.fetcher.dipy_home = f"{os.environ['HOME']}/.dipy"
    os.makedirs(dpd.fetcher.dipy_home, exist_ok=True)
    files, folder = dpd.fetcher.fetch_stanford_hardi()
    dwi_file = f"{folder}/HARDI150.nii.gz"
    fbvals = f"{folder}/HARDI150.bval"
    fbvecs = f"{folder}/HARDI150.bvec"
    files, folder = dpd.fetcher.fetch_stanford_t1()
    t1w_file = f"{folder}/t1.nii.gz"

    files, folder = dpd.fetcher.fetch_stanford_pve_maps()
    f_pve_csf = f"{folder}/pve_csf.nii.gz"
    f_pve_gm = f"{folder}/pve_gm.nii.gz"
    f_pve_wm = f"{folder}/pve_wm.nii.gz"

    bvals = np.loadtxt(fbvals)

    b0_ixs = np.where(np.logical_and(bvals <= 50, bvals >= -50))[0]

    dwi_img = nib.load(dwi_file)
    dwi_data = dwi_img.get_fdata()

    b0_mask, mask = median_otsu(np.asarray(dwi_data,
                                           dtype=np.float32)[..., b0_ixs[0]],
                                median_radius=4,
                                numpass=2)
    mask_img = nib.Nifti1Image(mask.astype(np.float32), dwi_img.affine)
    B0_mask = fname_presuffix(dwi_file, suffix="_brain_mask", use_ext=True)
    nib.save(mask_img, B0_mask)

    mask_img_small = nib.Nifti1Image(mask[20:50, 55:85,
                                          38:39].astype('float32'),
                                     affine=mask_img.affine)
    B0_mask_small = fname_presuffix(dwi_file,
                                    suffix="_brain_mask_small",
                                    use_ext=True)
    nib.save(mask_img_small, B0_mask_small)

    del mask
    mask_img.uncache()
    mask_img_small.uncache()
    gc.collect()

    gtab = gradient_table(bvals, np.loadtxt(fbvecs))
    gtab.b0_threshold = 50
    gtab_bvals = gtab.bvals.copy()
    b0_thr_ixs = np.where(gtab_bvals < gtab.b0_threshold)[0]
    gtab_bvals[b0_thr_ixs] = 0
    gtab.b0s_mask = gtab_bvals == 0

    gtab_file_tmp = tempfile.NamedTemporaryFile(mode='w+',
                                                suffix='.pkl',
                                                delete=False)
    gtab_file = str(gtab_file_tmp.name)
    save_pickle(gtab_file, gtab)

    dwi_data_small = dwi_data.copy()
    dwi_data_small = dwi_data_small[20:50, 55:85, 38:39]
    dwi_img_small = nib.Nifti1Image(dwi_data_small,
                                    header=dwi_img.header,
                                    affine=dwi_img.affine)
    dwi_file_small = fname_presuffix(dwi_file, suffix="_small", use_ext=True)
    dwi_img_small.to_filename(dwi_file_small)

    del dwi_data, dwi_data_small
    dwi_img.uncache()
    dwi_img_small.uncache()
    gc.collect()

    yield {
        'dwi_file': dwi_file,
        'fbvals': fbvals,
        'fbvecs': fbvecs,
        'gtab': gtab,
        'gtab_file': gtab_file,
        'dwi_file_small': dwi_file_small,
        'B0_mask_small': B0_mask_small,
        'B0_mask': B0_mask,
        't1w_file': t1w_file,
        'f_pve_csf': f_pve_csf,
        'f_pve_wm': f_pve_wm,
        'f_pve_gm': f_pve_gm
    }
    gtab_file_tmp.close()