Ejemplo n.º 1
0
def _tract_profiles(row,
                    wm_labels,
                    bundle_dict,
                    reg_template,
                    odf_model="DTI",
                    directions="det",
                    n_seeds=2,
                    random_seeds=False,
                    scalars=["dti_fa", "dti_md"],
                    weighting=None,
                    force_recompute=False):
    profiles_file = _get_fname(row, '_profiles.csv')
    if not op.exists(profiles_file) or force_recompute:
        bundles_file = _clean_bundles(row,
                                      wm_labels,
                                      bundle_dict,
                                      reg_template,
                                      odf_model=odf_model,
                                      directions=directions,
                                      n_seeds=n_seeds,
                                      random_seeds=random_seeds,
                                      force_recompute=force_recompute)
        keys = []
        vals = []
        for k in bundle_dict.keys():
            keys.append(bundle_dict[k]['uid'])
            vals.append(k)
        reverse_dict = dict(zip(keys, vals))

        bundle_names = []
        profiles = []
        node_numbers = []
        scalar_names = []

        trk = nib.streamlines.load(bundles_file)
        for scalar in scalars:
            scalar_file = _scalar_dict[scalar](row,
                                               force_recompute=force_recompute)
            scalar_data = nib.load(scalar_file).get_data()
            for b in np.unique(trk.tractogram.data_per_streamline['bundle']):
                idx = np.where(
                    trk.tractogram.data_per_streamline['bundle'] == b)[0]
                this_sl = list(trk.streamlines[idx])
                bundle_name = reverse_dict[b]
                this_profile = seg.calculate_tract_profile(
                    scalar_data, this_sl, affine=row['dwi_affine'])
                nodes = list(np.arange(this_profile.shape[0]))
                bundle_names.extend([bundle_name] * len(nodes))
                node_numbers.extend(nodes)
                scalar_names.extend([scalar] * len(nodes))
                profiles.extend(list(this_profile))

        profile_dframe = pd.DataFrame(
            dict(profiles=profiles,
                 bundle=bundle_names,
                 node=node_numbers,
                 scalar=scalar_names))
        profile_dframe.to_csv(profiles_file)

    return profiles_file
Ejemplo n.º 2
0
def test_segment():
    dpd.fetch_stanford_hardi()
    hardi_dir = op.join(fetcher.dipy_home, "stanford_hardi")
    hardi_fdata = op.join(hardi_dir, "HARDI150.nii.gz")
    hardi_fbval = op.join(hardi_dir, "HARDI150.bval")
    hardi_fbvec = op.join(hardi_dir, "HARDI150.bvec")
    file_dict = afd.read_stanford_hardi_tractography()
    mapping = file_dict['mapping.nii.gz']
    streamlines = file_dict['tractography_subsampled.trk']
    templates = afd.read_templates()
    bundles = {'CST_L': {'ROIs': [templates['CST_roi1_L'],
                                  templates['CST_roi2_L']],
                         'rules': [True, True]},
               'CST_R': {'ROIs': [templates['CST_roi1_R'],
                                  templates['CST_roi1_R']],
                         'rules': [True, True]}}

    fiber_groups = seg.segment(hardi_fdata,
                               hardi_fbval,
                               hardi_fbvec,
                               streamlines,
                               bundles,
                               mapping=mapping,
                               as_generator=True)

    # We asked for 2 fiber groups:
    npt.assert_equal(len(fiber_groups), 2)
    # There happen to be 8 fibers in the right CST:
    CST_R_sl = list(fiber_groups['CST_R'])
    npt.assert_equal(len(CST_R_sl), 8)
    # Calculate the tract profile for a volume of all-ones:
    tract_profile = seg.calculate_tract_profile(
        np.ones(nib.load(hardi_fdata).shape[:3]),
        CST_R_sl)
    npt.assert_equal(tract_profile, np.ones(100))
def showAfq():
    FA_img = nib.load(img)
    FA_data = FA_img.get_data()

    print("Tract profiles...")

    fig, ax = plt.subplots(1)
    profile = seg.calculate_tract_profile(FA_data, T_A.tolist())
    ax.plot(profile)
    #ax.set_title('100307_af.left')
    #plt.savefig("F:\Thesis\DATA\\103414_af.left.png")
    plt.show()
Ejemplo n.º 4
0
def _tract_profiles(row, wm_labels, odf_model="DTI", directions="det",
                    scalars=["dti_fa", "dti_md"], weighting=None,
                    force_recompute=False):
    profiles_file = _get_fname(row, '_profiles.csv')
    if not op.exists(profiles_file) or force_recompute:
        bundles_file = _bundles(row,
                                wm_labels,
                                odf_model=odf_model,
                                directions=directions,
                                force_recompute=force_recompute)
        bundle_dict = make_bundle_dict()
        keys = []
        vals = []
        for k in bundle_dict.keys():
            keys.append(bundle_dict[k]['uid'])
            vals.append(k)
        reverse_dict = dict(zip(keys, vals))

        bundle_names = []
        profiles = []
        node_numbers = []
        scalar_names = []

        trk = nib.streamlines.load(bundles_file)
        for scalar in scalars:
            scalar_file = _scalar_dict[scalar](row,
                                               force_recompute=force_recompute)
            scalar_data = nib.load(scalar_file).get_data()
            for b in np.unique(trk.tractogram.data_per_streamline['bundle']):
                idx = np.where(
                    trk.tractogram.data_per_streamline['bundle'] == b)[0]
                this_sl = list(trk.streamlines[idx])
                bundle_name = reverse_dict[b]
                this_profile = seg.calculate_tract_profile(
                    scalar_data,
                    this_sl,
                    affine=row['dwi_affine'])
                nodes = list(np.arange(this_profile.shape[0]))
                bundle_names.extend([bundle_name] * len(nodes))
                node_numbers.extend(nodes)
                scalar_names.extend([scalar] * len(nodes))
                profiles.extend(list(this_profile))

        profile_dframe = pd.DataFrame(dict(profiles=profiles,
                                           bundle=bundle_names,
                                           node=node_numbers,
                                           scalar=scalar_names))
        profile_dframe.to_csv(profiles_file)

    return profiles_file
Ejemplo n.º 5
0
def main():
    with open('config.json') as config_json:
        config = json.load(config_json)

    data_file = str(config['data_file'])
    data_bval = str(config['data_bval'])
    data_bvec = str(config['data_bvec'])
    tracks = str(config['tracks'])

    print("Calculating DTI...")
    if not os.path.exists('./dti_FA.nii.gz'):
        dti_params = dti.fit_dti(data_file, data_bval, data_bvec, out_dir='.')
    else:
        dti_params = {'FA': './dti_FA.nii.gz', 'params': './dti_params.nii.gz'}
    FA_img = nib.load(dti_params['FA'])
    FA_data = FA_img.get_data()
    print("Extracting tract profiles...")

    path = os.getcwd() + '/profile/'
    if not os.path.exists(path):
        os.makedirs(path)

    for t in os.listdir(tracks):
        if t.endswith('.tck'):
            tg = nib.streamlines.load(tracks + '/' + t)
            streamlines = list(tg.streamlines)
            profile = seg.calculate_tract_profile(FA_data, streamlines)
            profile = profile.tolist()
            t = os.path.splitext(
                os.path.basename(t))[0]  #remove the .tck from string
            p = path + '/' + t + '.json'
            json.dump(profile,
                      codecs.open(p, 'w', encoding='utf-8'),
                      separators=(',', ':'),
                      sort_keys=True,
                      indent=4)

T_A_filename = 'F:\Thesis\data\\100307\\100307_af.left.trk'
T_filename='F:\Thesis\data\\100307\\100307_af.left.trk'


T_A= loadtrkfile(T_A_filename, threshold_short_streamlines=10.0) 



FA_img = nib.load('F:\Thesis\data\\100307\\100307_data_b1k_1.25mm_FA.nii.gz')
FA_data = FA_img.get_data()

print("Extracting tract profiles...")
#fig, ax = plt.subplots(1)
profile1 = seg.calculate_tract_profile(FA_data, T_A.tolist())
#ax.plot(profile1)
#####################################################################

T_A_filename = 'F:\Thesis\data\\201111\\201111_af.left.trk'
T_filename='F:\Thesis\data\\201111\\201111_af.left.trk'


T_A= loadtrkfile(T_A_filename, threshold_short_streamlines=10.0) 



FA_img = nib.load('F:\Thesis\data\\201111\\201111_data_b1k_1.25mm_FA.nii.gz')
FA_data = FA_img.get_data()

print("Extracting tract profiles...")
Ejemplo n.º 7
0
print("Registering to template...")
MNI_T2_img = dpd.read_mni_template()
if not op.exists('mapping.nii.gz'):
    import dipy.core.gradients as dpg
    gtab = dpg.gradient_table(hardi_fbval, hardi_fbvec)
    mapping = reg.syn_register_dwi(hardi_fdata, gtab)
    reg.write_mapping(mapping, './mapping.nii.gz')
else:
    mapping = reg.read_mapping('./mapping.nii.gz', img, MNI_T2_img)

print("Segmenting fiber groups...")
fiber_groups = seg.segment(hardi_fdata,
                           hardi_fbval,
                           hardi_fbvec,
                           streamlines,
                           bundles,
                           reg_template=MNI_T2_img,
                           mapping=mapping,
                           as_generator=False,
                           affine=img.affine)

FA_img = nib.load(dti_params['FA'])
FA_data = FA_img.get_data()

print("Extracting tract profiles...")
for bundle in bundles:
    fig, ax = plt.subplots(1)
    profile = seg.calculate_tract_profile(FA_data, fiber_groups[bundle])
    ax.plot(profile)
    ax.set_title(bundle)
Ejemplo n.º 8
0
                           prob_threshold=5)


print("Getting tract profiles")
n_points = 100

dfs = []
for bundle in fiber_groups:
    print("Getting profile for: %s" % bundle)
    if len(fiber_groups[bundle]) > 0:
        bundle_df = pd.DataFrame(data={
            'tractID': [bundle] * n_points,
            'nodeID': np.arange(1, n_points + 1)})

        for stat_key in dti_params.keys():
            if stat_key == 'params':
                pass
            else:
                stat_data = nib.load(dti_params[stat_key]).get_data()
                fgarray = seg._resample_bundle(fiber_groups[bundle], n_points)
                weights = seg.gaussian_weights(fgarray)
                profile = seg.calculate_tract_profile(stat_data,
                                                      fgarray,
                                                      weights=weights)
                bundle_df[stat_key] = profile
        dfs.append(bundle_df)
    else:
        print("There are no fibers in %s" % bundle)

result = pd.concat(dfs)
Ejemplo n.º 9
0
def test_segment():
    dpd.fetch_stanford_hardi()
    hardi_dir = op.join(fetcher.dipy_home, "stanford_hardi")
    hardi_fdata = op.join(hardi_dir, "HARDI150.nii.gz")
    hardi_img = nib.load(hardi_fdata)
    hardi_fbval = op.join(hardi_dir, "HARDI150.bval")
    hardi_fbvec = op.join(hardi_dir, "HARDI150.bvec")
    file_dict = afd.read_stanford_hardi_tractography()
    mapping = file_dict['mapping.nii.gz']
    streamlines = file_dict['tractography_subsampled.trk']
    streamlines = dts.Streamlines(
        dtu.move_streamlines(streamlines[streamlines._lengths > 10],
                             np.linalg.inv(hardi_img.affine)))

    templates = afd.read_templates()
    bundles = {
        'CST_L': {
            'ROIs': [templates['CST_roi1_L'], templates['CST_roi2_L']],
            'rules': [True, True],
            'prob_map': templates['CST_L_prob_map'],
            'cross_midline': None
        },
        'CST_R': {
            'ROIs': [templates['CST_roi1_R'], templates['CST_roi1_R']],
            'rules': [True, True],
            'prob_map': templates['CST_R_prob_map'],
            'cross_midline': None
        }
    }

    fiber_groups = seg.segment(hardi_fdata, hardi_fbval, hardi_fbvec,
                               streamlines, bundles, mapping)

    # We asked for 2 fiber groups:
    npt.assert_equal(len(fiber_groups), 2)
    # Here's one of them:
    CST_R_sl = fiber_groups['CST_R']
    # Let's make sure there are streamlines in there:
    npt.assert_(len(CST_R_sl) > 0)
    # Calculate the tract profile for a volume of all-ones:
    tract_profile = seg.calculate_tract_profile(
        np.ones(nib.load(hardi_fdata).shape[:3]), CST_R_sl)
    npt.assert_almost_equal(tract_profile, np.ones(100))

    # Test providing an array input to calculate_tract_profile:
    tract_profile = seg.calculate_tract_profile(
        np.ones(nib.load(hardi_fdata).shape[:3]),
        seg._resample_bundle(CST_R_sl, 100))

    npt.assert_almost_equal(tract_profile, np.ones(100))
    clean_sl = seg.clean_fiber_group(CST_R_sl)
    # Since there are only 8 streamlines here, nothing should happen:
    npt.assert_equal(clean_sl, CST_R_sl)

    # Setting minimum number of streamlines to a smaller number and
    # threshold to a relatively small number will exclude some streamlines:
    clean_sl = seg.clean_fiber_group(CST_R_sl, min_sl=2, clean_threshold=2)
    npt.assert_equal(len(clean_sl), 3)

    # What if you don't have probability maps?
    bundles = {
        'CST_L': {
            'ROIs': [templates['CST_roi1_L'], templates['CST_roi2_L']],
            'rules': [True, True],
            'cross_midline': False
        },
        'CST_R': {
            'ROIs': [templates['CST_roi1_R'], templates['CST_roi1_R']],
            'rules': [True, True],
            'cross_midline': False
        }
    }

    fiber_groups = seg.segment(hardi_fdata, hardi_fbval, hardi_fbvec,
                               streamlines, bundles, mapping)

    # This condition should still hold
    npt.assert_equal(len(fiber_groups), 2)
    npt.assert_(len(fiber_groups['CST_R']) > 0)
Ejemplo n.º 10
0
else:
    mapping = reg.read_mapping('./mapping.nii.gz', img, MNI_T2_img)

print("Segmenting fiber groups...")
fiber_groups = seg.segment(hardi_fdata,
                           hardi_fbval,
                           hardi_fbvec,
                           streamlines,
                           bundles,
                           reg_template=MNI_T2_img,
                           mapping=mapping,
                           as_generator=False,
                           affine=img.affine)


print("Cleaning fiber groups...")
for bundle in bundles:
    fiber_groups[bundle] = seg.clean_fiber_group(fiber_groups[bundle])

FA_img = nib.load(dti_params['FA'])
FA_data = FA_img.get_data()

print("Extracting tract profiles...")
for bundle in bundles:
    fig, ax = plt.subplots(1)
    profile = seg.calculate_tract_profile(FA_data, fiber_groups[bundle])
    ax.plot(profile)
    ax.set_title(bundle)

plt.show()
Ejemplo n.º 11
0
def main():
    with open('config.json') as config_json:
        config = json.load(config_json)

    data_file = config['data_file']
    data_bval = config['data_bval']
    data_bvec = config['data_bvec']

    img = nib.load(data_file)

    print("Calculating DTI...")
    if not op.exists('./dti_FA.nii.gz'):
        dti_params = dti.fit_dti(data_file, data_bval, data_bvec, out_dir='.')
    else:
        dti_params = {'FA': './dti_FA.nii.gz', 'params': './dti_params.nii.gz'}

    tg = nib.streamlines.load('csa_prob.trk').tractogram
    streamlines = tg.apply_affine(np.linalg.inv(img.affine)).streamlines

    # Use only a small portion of the streamlines, for expedience:
    streamlines = streamlines[::100]

    templates = afd.read_templates()
    bundle_names = ["CST", "ILF"]

    bundles = {}
    for name in bundle_names:
        for hemi in ['_R', '_L']:
            bundles[name + hemi] = {
                'ROIs': [
                    templates[name + '_roi1' + hemi],
                    templates[name + '_roi1' + hemi]
                ],
                'rules': [True, True]
            }

    print("Registering to template...")
    MNI_T2_img = dpd.read_mni_template()
    bvals, bvecs = read_bvals_bvecs(data_bval, data_bvec)
    gtab = gradient_table(bvals, bvecs, b0_threshold=100)
    mapping = reg.syn_register_dwi(data_file, gtab)
    reg.write_mapping(mapping, './mapping.nii.gz')

    print("Segmenting fiber groups...")
    fiber_groups = seg.segment(data_file,
                               data_bval,
                               data_bvec,
                               streamlines,
                               bundles,
                               reg_template=MNI_T2_img,
                               mapping=mapping,
                               as_generator=False,
                               affine=img.affine)

    FA_img = nib.load(dti_params['FA'])
    FA_data = FA_img.get_data()

    print("Extracting tract profiles...")
    for bundle in bundles:
        fig, ax = plt.subplots(1)
        profile = seg.calculate_tract_profile(FA_data, fiber_groups[bundle])
        ax.plot(profile)
        ax.set_title(bundle)
    plt.savefig('bundle.png')
Ejemplo n.º 12
0
def test_segment():
    dpd.fetch_stanford_hardi()
    hardi_dir = op.join(fetcher.dipy_home, "stanford_hardi")
    hardi_fdata = op.join(hardi_dir, "HARDI150.nii.gz")
    hardi_fbval = op.join(hardi_dir, "HARDI150.bval")
    hardi_fbvec = op.join(hardi_dir, "HARDI150.bvec")
    file_dict = afd.read_stanford_hardi_tractography()
    mapping = file_dict['mapping.nii.gz']
    streamlines = file_dict['tractography_subsampled.trk']
    templates = afd.read_templates()
    bundles = {'CST_L': {'ROIs': [templates['CST_roi1_L'],
                                  templates['CST_roi2_L']],
                         'rules': [True, True],
                         'prob_map': templates['CST_L_prob_map'],
                         'cross_midline': False},
               'CST_R': {'ROIs': [templates['CST_roi1_R'],
                                  templates['CST_roi1_R']],
                         'rules': [True, True],
                         'prob_map': templates['CST_R_prob_map'],
                         'cross_midline': False}}

    fiber_groups = seg.segment(hardi_fdata,
                               hardi_fbval,
                               hardi_fbvec,
                               streamlines,
                               bundles,
                               mapping=mapping,
                               as_generator=True)

    # We asked for 2 fiber groups:
    npt.assert_equal(len(fiber_groups), 2)
    # There happen to be 5 fibers in the right CST:
    CST_R_sl = fiber_groups['CST_R']
    npt.assert_equal(len(CST_R_sl), 5)
    # Calculate the tract profile for a volume of all-ones:
    tract_profile = seg.calculate_tract_profile(
        np.ones(nib.load(hardi_fdata).shape[:3]),
        CST_R_sl)
    npt.assert_almost_equal(tract_profile, np.ones(100))

    # Test providing an array input to calculate_tract_profile:
    tract_profile = seg.calculate_tract_profile(
        np.ones(nib.load(hardi_fdata).shape[:3]),
        seg._resample_bundle(CST_R_sl, 100))


    npt.assert_almost_equal(tract_profile, np.ones(100))
    clean_sl = seg.clean_fiber_group(CST_R_sl)
    # Since there are only 5 streamlines here, nothing should happen:
    npt.assert_equal(clean_sl, CST_R_sl)

    # Setting minimum number of streamlines to a smaller number and
    # threshold to a relatively small number will exclude some streamlines:
    clean_sl = seg.clean_fiber_group(CST_R_sl, min_sl=2, clean_threshold=2)
    npt.assert_equal(len(clean_sl), 3)

    # What if you don't have probability maps?
    bundles = {'CST_L': {'ROIs': [templates['CST_roi1_L'],
                                  templates['CST_roi2_L']],
                         'rules': [True, True],
                         'cross_midline': False},
               'CST_R': {'ROIs': [templates['CST_roi1_R'],
                                  templates['CST_roi1_R']],
                         'rules': [True, True],
                         'cross_midline': False}}

    fiber_groups = seg.segment(hardi_fdata,
                               hardi_fbval,
                               hardi_fbvec,
                               streamlines,
                               bundles,
                               mapping=mapping,
                               as_generator=True)

    # This condition should still hold
    npt.assert_equal(len(fiber_groups), 2)
    # But one of the streamlines has switched identities without the
    # probability map to guide selection
    npt.assert_equal(len(fiber_groups['CST_R']), 6)
import AFQ.dti as dti
import AFQ.segmentation as seg
from nibabel import trackvis


def loadtrkfile(T_filename, threshold_short_streamlines=10.0):
    """Load tractogram from TRK file and remove short streamlines with
    length below threshold.
    """
    print("Loading %s" % T_filename)
    T, hdr = trackvis.read(T_filename, as_generator=False)
    T = np.array([s[0] for s in T], dtype=np.object)

    return T


T_A_filename = 'F:\Thesis\data\\100307\\100307_af.left.trk'
T_filename = 'F:\Thesis\data\\100307\\100307_af.left.trk'

T_A = loadtrkfile(T_A_filename, threshold_short_streamlines=10.0)

FA_img = nib.load('F:\Thesis\data\\100307\\100307_data_b1k_1.25mm_FA.nii.gz')
FA_data = FA_img.get_data()

print("Extracting tract profiles...")
fig, ax = plt.subplots(1)
profile = seg.calculate_tract_profile(FA_data, T_A.tolist())
ax.plot(profile)
ax.set_title('bundle')

plt.show()