def show_tract(segmented_tract, color_positive, segmented_tract_negative,
               color_negative, out_path):
    """Visualization of the segmented tract.
    """
    affine = utils.affine_for_trackvis(voxel_size=np.array([1.25, 1.25, 1.25]))
    bundle_native = transform_streamlines(segmented_tract,
                                          np.linalg.inv(affine))

    bundle_nativeNeg = transform_streamlines(segmented_tract_negative,
                                             np.linalg.inv(affine))

    renderer = window.Renderer()
    stream_actor2 = actor.line(bundle_native,
                               colors=color_positive,
                               linewidth=0.1)

    stream_actorNeg = actor.line(bundle_nativeNeg,
                                 colors=color_negative,
                                 opacity=0.01,
                                 linewidth=0.1)
    renderer.set_camera(position=(408.85, -26.23, 92.12),
                        focal_point=(0.42, -14.03, 0.82),
                        view_up=(-0.09, 0.85, 0.51))

    bar = actor.scalar_bar()
    renderer.add(stream_actor2)

    renderer.add(stream_actorNeg)
    renderer.add(bar)
    window.show(renderer, size=(1920, 1039), reset_camera=False)
    renderer.camera_info()
    """Take a snapshot of the window and save it
    """
    window.record(renderer, out_path=out_path, size=(1920, 1039))
def showsls(sls, values, outpath, show=False):
    from dipy.viz import window, actor, fvtk
    from dipy.data import fetch_bundles_2_subjects, read_bundles_2_subjects
    from dipy.tracking.streamline import transform_streamlines
    #renderer.clear()

    from dipy.tracking.streamline import length

    renderer = window.Renderer()

    hue = [0.5, 1]  # white to purple to red
    saturation = [0.0, 1.0]  # black to white

    lut_cmap = actor.colormap_lookup_table(
        scale_range=(values.min(), np.percentile(values, 50)),
        hue_range=hue,
        saturation_range=saturation)

    stream_actor5 = actor.line(sls,
                               values,
                               linewidth=0.1,
                               lookup_colormap=lut_cmap)

    renderer.add(stream_actor5)
    bar3 = actor.scalar_bar(lut_cmap)

    renderer.add(bar3)

    # window.show(renderer, size=(600, 600), reset_camera=False)
    if outpath:
        window.record(renderer, out_path=outpath, size=(600, 600))
    if show:
        fvtk.show(renderer)
    def change_text_callback(i_ren, obj, button):
        text2.message = str(i_coord) + ' ' + str(j_coord) + ' ' + str(k_coord)
        torusActor.SetPosition(i_coord, j_coord, k_coord)
        print(i_coord, j_coord, k_coord)
        lut, colors = change_TMS_effects(i_coord, j_coord, k_coord)
        scene.rm(actor_line_list[0])
        actor_line_list.append(
            actor.line(bundle_native,
                       colors,
                       linewidth=5,
                       fake_tube=True,
                       lookup_colormap=lut))
        scene.add(actor_line_list[1])

        nonlocal number_of_stimulations
        global bar
        if number_of_stimulations > 0:
            scene.rm(bar)
        else:
            number_of_stimulations = number_of_stimulations + 1

        bar = actor.scalar_bar(lut)
        bar.SetTitle("TMS effect")

        bar.SetHeight(0.3)
        bar.SetWidth(0.10)  # the width is set first
        bar.SetPosition(0.85, 0.3)
        scene.add(bar)

        actor_line_list.pop(0)
        i_ren.force_render()
Exemple #4
0
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()

    output_names = [
        'axial_superior', 'axial_inferior', 'coronal_posterior',
        'coronal_anterior', 'sagittal_left', 'sagittal_right'
    ]

    output_paths = [
        os.path.join(os.path.dirname(args.output),
                     '{}_' + os.path.basename(args.output)).format(name)
        for name in output_names
    ]
    assert_inputs_exist(parser, [args.bundle, args.map])
    assert_outputs_exists(parser, args, output_paths)

    assignment = np.load(args.map)['arr_0']
    lut = actor.colormap_lookup_table(scale_range=(np.min(assignment),
                                                   np.max(assignment)),
                                      hue_range=(0.1, 1.),
                                      saturation_range=(1, 1.),
                                      value_range=(1., 1.))

    tubes = actor.line(nib.streamlines.load(args.bundle).streamlines,
                       assignment,
                       lookup_colormap=lut)
    scalar_bar = actor.scalar_bar(lut)

    ren = window.Renderer()
    ren.add(tubes)
    ren.add(scalar_bar)

    window.snapshot(ren, output_paths[0])

    ren.pitch(180)
    ren.reset_camera()
    window.snapshot(ren, output_paths[1])

    ren.pitch(90)
    ren.set_camera(view_up=(0, 0, 1))
    ren.reset_camera()
    window.snapshot(ren, output_paths[2])

    ren.pitch(180)
    ren.set_camera(view_up=(0, 0, 1))
    ren.reset_camera()
    window.snapshot(ren, output_paths[3])

    ren.yaw(90)
    ren.reset_camera()
    window.snapshot(ren, output_paths[4])

    ren.yaw(180)
    ren.reset_camera()
    window.snapshot(ren, output_paths[5])
Exemple #5
0
def show_fascicles_wholebrain(s_list,
                              vec_vols,
                              folder_name,
                              mask_type,
                              downsamp=1,
                              scale=[3, 6],
                              hue=[0.25, -0.05],
                              saturation=[0.1, 1.0]):

    s_img = folder_name + r'\streamlines' + r'\fascicles_AxCaliber_weighted_3d_' + mask_type + '.png'
    #hue = [0.4, 0.7] # blues
    #hue = [0.25, -0.05] #Hot
    #hue = [0, 1] #All

    weighted = True
    '''
    if weighted:
        scale = [0, 3]


    else:
        scale = [0, 6]
        vec_vols = np.log(vec_vols)
        #vec_vols = vec_vols-np.nanmin(vec_vols)/(np.nanmax(vec_vols)-np.nanmin(vec_vols))
    '''

    if downsamp != 1:
        vec_vols = vec_vols[::downsamp]
        s_list = s_list[::downsamp]

    lut_cmap = actor.colormap_lookup_table(hue_range=hue,
                                           saturation_range=saturation,
                                           scale_range=scale)
    bar = actor.scalar_bar(lut_cmap)
    #w_actor = actor.line(s_list, vec_vols, linewidth=1.2, lookup_colormap=lut_cmap)
    w_actor = actor.streamtube(s_list,
                               vec_vols,
                               linewidth=0.6,
                               lookup_colormap=lut_cmap)

    #w_actor = actor.streamtube(s_list, vec_vols, linewidth=0.3, lookup_colormap=lut_cmap)
    #w_actor = actor.line(s_list, linewidth=1.0, lookup_colormap=lut_cmap)

    r = window.Renderer()
    #r.SetBackground(*window.colors.white)
    r.add(w_actor)
    r.add(bar)
    window.show(r)
    r.set_camera(r.camera_info())
    window.record(r, out_path=s_img, size=(800, 800))
def show_tract(segmented_tract, color):
    """Visualization of the segmented tract.
    """ 
    affine=utils.affine_for_trackvis(voxel_size=np.array([1.25,1.25,1.25]))
    bundle_native = transform_streamlines(segmented_tract, np.linalg.inv(affine))

    renderer = window.Renderer()
    stream_actor = actor.line(bundle_native, linewidth=0.1)
    bar = actor.scalar_bar()
    renderer.add(stream_actor)
    renderer.add(bar)
    window.show(renderer, size=(600, 600), reset_camera=False)          
    """Take a snapshot of the window and save it
    """
    window.record(renderer, out_path='bundle2.1.png', size=(600, 600))          
Exemple #7
0
def visualize_streamline(darray,
                         score,
                         save_able=False,
                         save_name='default.png',
                         control_par=1,
                         hue=[0.5, 1]):

    data_evl = darray

    streamlines_evl = Streamlines()

    for i in range(np.shape(data_evl)[0]):
        tmp = data_evl[i]
        tmp = zero_remove(tmp)
        #tmp = tmp[~np.all(tmp == 0, axis=-1)]
        #tmp = np.around(tmp, decimals=0)
        streamlines_evl.append(tmp)

    mse_nor = score

    # Visualize the streamlines, colored by cci
    ren = window.Scene()

    saturation = [0.0, 1.0]

    lut_cmap = actor.colormap_lookup_table(
        scale_range=(min(mse_nor), max(mse_nor) / control_par),
        hue_range=hue,
        saturation_range=saturation)

    bar3 = actor.scalar_bar(lut_cmap)
    ren.add(bar3)

    stream_actor = actor.line(streamlines_evl,
                              mse_nor,
                              linewidth=0.1,
                              lookup_colormap=lut_cmap)
    ren.add(stream_actor)

    if not save_able:
        interactive = True
        if interactive:
            window.show(ren)

    if save_able:
        window.record(ren, n_frames=1, out_path=save_name, size=(800, 800))
Exemple #8
0
def show_tracts(hue, saturation, scale, streamlines, mean_vol_per_tract,
                folder_name, fig_type):
    from dipy.viz import window, actor
    lut_cmap = actor.colormap_lookup_table(hue_range=hue,
                                           saturation_range=saturation,
                                           scale_range=scale)
    streamlines_actor = actor.streamtube(streamlines,
                                         mean_vol_per_tract,
                                         linewidth=0.5,
                                         lookup_colormap=lut_cmap)
    bar = actor.scalar_bar(lut_cmap)
    r = window.Scene()
    r.add(streamlines_actor)
    r.add(bar)
    mean_pasi_weighted_img = f'{folder_name}{os.sep}streamlines{os.sep}mean_pasi_weighted{fig_type}.png'
    window.show(r)
    r.set_camera(r.camera_info())
    window.record(r, out_path=mean_pasi_weighted_img, size=(800, 800))
Exemple #9
0
def cc_part_viz_running_script(n, folder_name):
    folder_name = folder_name + r'\streamlines'

    hue = [0.0, 1.0]
    saturation = [0.0, 1.0]
    scale = [3, 7]

    lut_cmap = actor.colormap_lookup_table(hue_range=hue,
                                           saturation_range=saturation,
                                           scale_range=scale)
    bar = actor.scalar_bar(lut_cmap)

    fascicle_name = '\cc_parts'
    g_mean, b_mean, s_mean = calc_mean_cc_vals(fascicle_name)

    g_path = folder_name + n + r'_genu_cortex_cleaned.trk'
    streamlines_g = load_ft(g_path)
    b_path = folder_name + n + r'_body_cortex_cleaned.trk'
    streamlines_b = load_ft(b_path)
    s_path = folder_name + n + r'_splenium_cortex_cleaned.trk'
    streamlines_s = load_ft(s_path)

    show_cc_parts_weighted(streamlines_g, streamlines_b, streamlines_s, g_mean,
                           b_mean, s_mean, folder_name, lut_cmap, bar)
Exemple #10
0
streamline bundle and visualize them.
"""

cci = cluster_confidence(long_streamlines)

# Visualize the streamlines, colored by cci
ren = window.Renderer()

hue = [0.5, 1]
saturation = [0.0, 1.0]

lut_cmap = actor.colormap_lookup_table(scale_range=(cci.min(), cci.max() / 4),
                                       hue_range=hue,
                                       saturation_range=saturation)

bar3 = actor.scalar_bar(lut_cmap)
ren.add(bar3)

stream_actor = actor.line(long_streamlines,
                          cci,
                          linewidth=0.1,
                          lookup_colormap=lut_cmap)
ren.add(stream_actor)
"""
If you set interactive to True (below), the rendering will pop up in an
interactive window.
"""

interactive = False
if interactive:
    window.show(ren)
Exemple #11
0
scene.camera_info()
"""
Show every point with a value from a volume with default colormap
=================================================================

Here we will need to input the ``fa`` map in ``streamtube`` or ``line``.
"""

scene.clear()
stream_actor2 = actor.line(bundle_native, fa, linewidth=0.1)
"""
We can also show the scalar bar.
"""

bar = actor.scalar_bar()

scene.add(stream_actor2)
scene.add(bar)

# window.show(scene, size=(600, 600), reset_camera=False)
window.record(scene, out_path='bundle2.png', size=(600, 600))
"""
.. figure:: bundle2.png
   :align: center

   Every point with a color from FA.

Show every point with a value from a volume with your colormap
==============================================================
Exemple #12
0
def test_bundle_maps():
    renderer = window.renderer()
    bundle = fornix_streamlines()
    bundle, shift = center_streamlines(bundle)

    mat = np.array([[1, 0, 0, 100], [0, 1, 0, 100], [0, 0, 1, 100],
                    [0, 0, 0, 1.]])

    bundle = transform_streamlines(bundle, mat)

    # metric = np.random.rand(*(200, 200, 200))
    metric = 100 * np.ones((200, 200, 200))

    # add lower values
    metric[100, :, :] = 100 * 0.5

    # create a nice orange-red colormap
    lut = actor.colormap_lookup_table(scale_range=(0., 100.),
                                      hue_range=(0., 0.1),
                                      saturation_range=(1, 1),
                                      value_range=(1., 1))

    line = actor.line(bundle, metric, linewidth=0.1, lookup_colormap=lut)
    window.add(renderer, line)
    window.add(renderer, actor.scalar_bar(lut, ' '))

    report = window.analyze_renderer(renderer)

    npt.assert_almost_equal(report.actors, 1)
    # window.show(renderer)

    renderer.clear()

    nb_points = np.sum([len(b) for b in bundle])
    values = 100 * np.random.rand(nb_points)
    # values[:nb_points/2] = 0

    line = actor.streamtube(bundle, values, linewidth=0.1, lookup_colormap=lut)
    renderer.add(line)
    # window.show(renderer)

    report = window.analyze_renderer(renderer)
    npt.assert_equal(report.actors_classnames[0], 'vtkLODActor')

    renderer.clear()

    colors = np.random.rand(nb_points, 3)
    # values[:nb_points/2] = 0

    line = actor.line(bundle, colors, linewidth=2)
    renderer.add(line)
    # window.show(renderer)

    report = window.analyze_renderer(renderer)
    npt.assert_equal(report.actors_classnames[0], 'vtkLODActor')
    # window.show(renderer)

    arr = window.snapshot(renderer)
    report2 = window.analyze_snapshot(arr)
    npt.assert_equal(report2.objects, 1)

    # try other input options for colors
    renderer.clear()
    actor.line(bundle, (1., 0.5, 0))
    actor.line(bundle, np.arange(len(bundle)))
    actor.line(bundle)
    colors = [np.random.rand(*b.shape) for b in bundle]
    actor.line(bundle, colors=colors)
"""


cci = cluster_confidence(long_streamlines)

# Visualize the streamlines, colored by cci
ren = window.Renderer()

hue = [0.5, 1]
saturation = [0.0, 1.0]

lut_cmap = actor.colormap_lookup_table(scale_range=(cci.min(), cci.max()/4),
                                       hue_range=hue,
                                       saturation_range=saturation)

bar3 = actor.scalar_bar(lut_cmap)
ren.add(bar3)

stream_actor = actor.line(long_streamlines, cci, linewidth=0.1,
                          lookup_colormap=lut_cmap)
ren.add(stream_actor)


"""
If you set interactive to True (below), the rendering will pop up in an
interactive window.
"""


interactive = False
if interactive:
Exemple #14
0
def weighting_streamlines(
    out_folder_name,
    streamlines,
    bvec_file,
    weight_by="1.5_2_AxPasi5",
    hue=[0.0, 1.0],
    saturation=[0.0, 1.0],
    scale=[2, 7],
    fig_type="",
):
    """
    weight_by = '1.5_2_AxPasi5'
    hue = [0.0,1.0]
    saturation = [0.0,1.0]
    scale = [3,6]
    """
    from dipy.viz import window, actor
    from dipy.tracking.streamline import values_from_volume

    weight_by_data, affine = load_weight_by_img(bvec_file, weight_by)

    stream = list(streamlines)
    vol_per_tract = values_from_volume(weight_by_data, stream, affine=affine)

    pfr_data = load_weight_by_img(bvec_file, "1.5_2_AxFr5")[0]

    pfr_per_tract = values_from_volume(pfr_data, stream, affine=affine)

    # Leave out from the calculation of mean value per tract, a chosen quantile:
    vol_vec = weight_by_data.flatten()
    q = np.quantile(vol_vec[vol_vec > 0], 0.95)
    mean_vol_per_tract = []
    for s, pfr in zip(vol_per_tract, pfr_per_tract):
        s = np.asanyarray(s)
        non_out = [s < q]
        pfr = np.asanyarray(pfr)
        high_pfr = [pfr > 0.5]
        mean_vol_per_tract.append(np.nanmean(s[tuple(non_out and high_pfr)]))

    lut_cmap = actor.colormap_lookup_table(hue_range=hue,
                                           saturation_range=saturation,
                                           scale_range=scale)
    streamlines_actor = actor.line(streamlines,
                                   mean_vol_per_tract,
                                   linewidth=1,
                                   lookup_colormap=lut_cmap)
    bar = actor.scalar_bar(lut_cmap)
    r = window.Renderer()
    r.add(streamlines_actor)
    r.add(bar)
    # mean_pasi_weighted_img = out_folder_name+'\streamlines\mean_pasi_weighted' + fig_type + '.png'
    mean_pasi_weighted_img = f"{out_folder_name}/mean_pasi_weighted{fig_type}.png"
    # window.show(r)
    # r.set_camera(r.camera_info())
    r.set_camera(
        position=(-389.00, 225.24, 62.02),
        focal_point=(1.78, -3.27, -12.65),
        view_up=(0.00, -0.31, 0.95),
    )
    # window.record(r, out_path=mean_pasi_weighted_img, size=(800, 800))
    window.snapshot(r, fname=mean_pasi_weighted_img, size=(800, 800))
    return r
Exemple #15
0
    weight_by_file = bvec_file[:-5:] + '_' + weight_by + '.nii'
    weight_by_img = nib.load(weight_by_file)
    weight_by_data = weight_by_img.get_data()
    affine = weight_by_img.affine
    stream = list(streamlines)
    vol_per_tract = values_from_volume(weight_by_data, stream, affine=affine)
    pfr_file = bvec_file[:-5:] + '_pfrS.nii'
    pfr_img = nib.load(pfr_file)
    pfr_data = pfr_img.get_data()

    lut_cmap = actor.colormap_lookup_table(hue_range=hue,
                                           saturation_range=saturation,
                                           scale_range=scale)
    streamlines_actor = actor.line(streamlines_native,
                                   pfr_data,
                                   lookup_colormap=lut_cmap)
    bar = actor.scalar_bar()

    r = window.Renderer()
    r.add(streamlines_actor)
    r.add(bar)
    window.show(r)
    fig_path = main_folder + r"\streamlines" + s + '_genu_dist.png'
    r.set_camera(r.camera_info())
    window.record(r,
                  path_numbering=True,
                  n_frames=3,
                  az_ang=30,
                  out_path=fig_path,
                  size=(800, 800))
Exemple #16
0
def test_bundle_maps():
    renderer = window.renderer()
    bundle = fornix_streamlines()
    bundle, shift = center_streamlines(bundle)

    mat = np.array([[1, 0, 0, 100],
                    [0, 1, 0, 100],
                    [0, 0, 1, 100],
                    [0, 0, 0, 1.]])

    bundle = transform_streamlines(bundle, mat)

    # metric = np.random.rand(*(200, 200, 200))
    metric = 100 * np.ones((200, 200, 200))

    # add lower values
    metric[100, :, :] = 100 * 0.5

    # create a nice orange-red colormap
    lut = actor.colormap_lookup_table(scale_range=(0., 100.),
                                      hue_range=(0., 0.1),
                                      saturation_range=(1, 1),
                                      value_range=(1., 1))

    line = actor.line(bundle, metric, linewidth=0.1, lookup_colormap=lut)
    window.add(renderer, line)
    window.add(renderer, actor.scalar_bar(lut, ' '))

    report = window.analyze_renderer(renderer)

    npt.assert_almost_equal(report.actors, 1)
    # window.show(renderer)

    renderer.clear()

    nb_points = np.sum([len(b) for b in bundle])
    values = 100 * np.random.rand(nb_points)
    # values[:nb_points/2] = 0

    line = actor.streamtube(bundle, values, linewidth=0.1, lookup_colormap=lut)
    renderer.add(line)
    # window.show(renderer)

    report = window.analyze_renderer(renderer)
    npt.assert_equal(report.actors_classnames[0], 'vtkLODActor')

    renderer.clear()

    colors = np.random.rand(nb_points, 3)
    # values[:nb_points/2] = 0

    line = actor.line(bundle, colors, linewidth=2)
    renderer.add(line)
    # window.show(renderer)

    report = window.analyze_renderer(renderer)
    npt.assert_equal(report.actors_classnames[0], 'vtkLODActor')
    # window.show(renderer)

    arr = window.snapshot(renderer)
    report2 = window.analyze_snapshot(arr)
    npt.assert_equal(report2.objects, 1)

    # try other input options for colors
    renderer.clear()
    actor.line(bundle, (1., 0.5, 0))
    actor.line(bundle, np.arange(len(bundle)))
    actor.line(bundle)
    colors = [np.random.rand(*b.shape) for b in bundle]
    actor.line(bundle, colors=colors)
Exemple #17
0
def main():
    global parser
    global args
    global model
    global bar
    global lut_cmap
    global list_x_file
    global max_weight
    global saturation
    global renderer
    global norm_fib
    global norm1
    global norm2
    global norm3
    global big_stream_actor
    global good_stream_actor
    global weak_stream_actor
    global big_Weight
    global good_Weight
    global weak_Weight
    global smallBundle_safe
    global smallWeight_safe
    global show_m
    global big_bundle
    global good_bundle
    global weak_bundle
    global nF
    global nIC
    global Ra
    global change_colormap_slider
    global remove_small_weights_slider
    global opacity_slider
    global remove_big_weights_slider
    global change_iteration_slider
    global num_computed_streamlines
    global numbers_of_streamlines_in_interval
    
    #defining the model used (Stick or cylinder)
    model = None
    if(os.path.isdir(args.commitOutputPath+"/Results_StickZeppelinBall") and os.path.isdir(args.commitOutputPath+"/Results_CylinderZeppelinBall")):
        model_index = input("Which model do you want to load (1 for 'Cylinder', 2 for 'Stick') : ")
        if(model_index==1): model = "Cylinder"
        else: model ="Stick"
    elif(os.path.isdir(args.commitOutputPath+"/Results_StickZeppelinBall")):
        model = "Stick"
    elif(os.path.isdir(args.commitOutputPath+"/Results_CylinderZeppelinBall")):
        model = "Cylinder"
    else:
        print("No valide model in this path")
        sys.exit(0)


    #formalizing the filenames of the iterations
    list_x_file = [file for file in os.listdir(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/") if (file.endswith('.npy') and (file[:-4]).isdigit() )]
    normalize_file_name(list_x_file)
    list_x_file.sort()
    num_iteration=len(list_x_file)

    #number of streamlines we want to load
    num_computed_streamlines = int(args.streamlinesNumber)
    #computing interval of weights
    max_weight = 0;
    if(model == "Cylinder"):
        file = open( args.commitOutputPath+"/Results_"+model+"ZeppelinBall/results.pickle",'rb' )
        object_file = pickle.load( file )

        Ra = np.linspace( 0.75,3.5,12 ) * 1E-6

        nIC = len(Ra)    # IC  atoms
        nEC = 4          # EC  atoms
        nISO = 1         # ISO atoms

        nF = object_file[0]['optimization']['regularisation']['sizeIC']
        nE = object_file[0]['optimization']['regularisation']['sizeEC']
        nV = object_file[0]['optimization']['regularisation']['sizeISO']


        num_ADI = np.zeros( nF )
        den_ADI = np.zeros( nF )

        dim = nib.load(args.commitOutputPath+"/Results_"+model+"ZeppelinBall/compartment_IC.nii.gz").get_data().shape
        norm_fib = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm_fib.npy")
        norm1 = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm1.npy")
        norm2 = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm2.npy")
        norm3 = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm3.npy")
        for itNbr in list_x_file:
            #computing diameter
            x = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/"+ itNbr +'.npy')
            x_norm = x / np.hstack( (norm1*norm_fib,norm2,norm3) )

            for i in range(nIC):
                den_ADI = den_ADI + x_norm[i*nF:(i+1)*nF]
                num_ADI = num_ADI + x_norm[i*nF:(i+1)*nF] * Ra[i]

            Weight = 2 * ( num_ADI / ( den_ADI + np.spacing(1) ) ) * 1E6
            smallWeight_safe = Weight[:num_computed_streamlines]
            itNbr_max = np.amax(smallWeight_safe)
            if(itNbr_max>max_weight):
                max_weight=itNbr_max
    else:#model==Stick
        file = open( args.commitOutputPath+"/Results_"+model+"ZeppelinBall/results.pickle",'rb' )
        object_file = pickle.load( file )
        norm_fib = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm_fib.npy")
        norm1 = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm1.npy")
        norm2 = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm2.npy")
        norm3 = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm3.npy")
        nF = object_file[0]['optimization']['regularisation']['sizeIC']
        for itNbr in list_x_file:
            x = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/"+ itNbr +'.npy')
            x_norm = x / np.hstack( (norm1*norm_fib,norm2,norm3) )

            Weight = x_norm[:nF]  #signal fractions
            smallWeight_safe = Weight[:num_computed_streamlines]
            itNbr_max = np.amax(smallWeight_safe)
            if(itNbr_max>max_weight):
                max_weight=itNbr_max
    #we need an interval slightly bigger than the max_weight
    max_weight = max_weight + 0.00001

    #computing initial weights
    if(model == "Cylinder"):#model==Cylinder
        file = open( args.commitOutputPath+"/Results_"+model+"ZeppelinBall/results.pickle",'rb' )
        object_file = pickle.load( file )

        Ra = np.linspace( 0.75,3.5,12 ) * 1E-6

        nIC = len(Ra)    # IC  atoms
        nEC = 4          # EC  atoms
        nISO = 1         # ISO atoms

        nF = object_file[0]['optimization']['regularisation']['sizeIC']
        nE = object_file[0]['optimization']['regularisation']['sizeEC']
        nV = object_file[0]['optimization']['regularisation']['sizeISO']

        dim = nib.load(args.commitOutputPath+"/Results_"+model+"ZeppelinBall/compartment_IC.nii.gz").get_data().shape


        norm_fib = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm_fib.npy")
        #add the normalisation
        x = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/"+list_x_file[0]+'.npy')
        norm1 = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm1.npy")
        norm2 = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm2.npy")
        norm3 = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm3.npy")
        x_norm = x / np.hstack( (norm1*norm_fib,norm2,norm3) )

        num_ADI = np.zeros( nF )
        den_ADI = np.zeros( nF )

        for i in range(nIC):
            den_ADI = den_ADI + x_norm[i*nF:(i+1)*nF]
            num_ADI = num_ADI + x_norm[i*nF:(i+1)*nF] * Ra[i]

        Weight = 2 * ( num_ADI / ( den_ADI + np.spacing(1) ) ) * 1E6
        smallWeight_safe = Weight[:num_computed_streamlines]
        weak_Weight = smallWeight_safe[:1]
        big_Weight = smallWeight_safe[:1]
        good_Weight = copy.copy(smallWeight_safe)
    else:#model==Stick
        file = open( args.commitOutputPath+"/Results_"+model+"ZeppelinBall/results.pickle",'rb' )
        object_file = pickle.load( file )
        nF = object_file[0]['optimization']['regularisation']['sizeIC']
        x = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/"+list_x_file[0]+'.npy')
        norm1 = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm1.npy")
        norm2 = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm2.npy")
        norm3 = np.load(args.commitOutputPath+"/Coeff_x_"+model+"ZeppelinBall/norm3.npy")
        x_norm = x / np.hstack( (norm1*norm_fib,norm2,norm3) )

        Weight = x_norm[:nF]  #signal fractions
        smallWeight_safe = Weight[:num_computed_streamlines]
        weak_Weight = smallWeight_safe[:1]
        big_Weight = smallWeight_safe[:1]
        good_Weight = copy.copy(smallWeight_safe)

    #load streamlines from the dictionary_TRK_fibers_trk file
    streams, hdr = nib.trackvis.read(args.commitOutputPath+"/dictionary_TRK_fibers.trk")
    streamlines = [s[0] for s in streams]
    smallBundle_safe = streamlines[:num_computed_streamlines]
    weak_bundle = smallBundle_safe[:1]
    big_bundle = smallBundle_safe[:1]
    good_bundle = copy.copy(smallBundle_safe)
    #number of good streamlines
    num_streamlines = len(smallBundle_safe)


    # mapping streamlines and initial weights(with a red bar) in a renderer
    hue = [0, 0]  # red only
    saturation = [0.0, 1.0]  # black to white

    lut_cmap = actor.colormap_lookup_table(
        scale_range=(0, max_weight),
        hue_range=hue,
        saturation_range=saturation)

    weak_stream_actor = actor.line(weak_bundle, weak_Weight,
                                   lookup_colormap=lut_cmap)
    big_stream_actor = actor.line(big_bundle, big_Weight,
                                lookup_colormap=lut_cmap)
    good_stream_actor = actor.line(good_bundle, good_Weight,
                               lookup_colormap=lut_cmap)

    bar = actor.scalar_bar(lut_cmap, title = 'weight')
    bar.SetHeight(0.5)
    bar.SetWidth(0.1)
    bar.SetPosition(0.85,0.45)

    renderer = window.Renderer()

    renderer.set_camera(position=(-176.42, 118.52, 128.20),
                        focal_point=(113.30, 100, 76.56),
                        view_up=(0.18, 0.00, 0.98))

    renderer.add(big_stream_actor)
    renderer.add(good_stream_actor)
    renderer.add(weak_stream_actor)
    renderer.add(bar)

    #adding sliders and renderer to a ShowManager
    show_m = window.ShowManager(renderer, size=(1200, 900))
    show_m.initialize()

    save_one_image_bouton = ui.LineSlider2D(min_value=0,
                                    max_value=1,
                                    initial_value=0,
                                    text_template="save",
                                    length=1)

    add_graph_bouton = ui.LineSlider2D(min_value=0,
                                    max_value=1,
                                    initial_value=0,
                                    text_template="graph",
                                    length=1)

    color_slider = ui.LineSlider2D(min_value=0.0,
                                     max_value=1.0,
                                     initial_value=0,
                                     text_template="{value:.1f}",
                                     length=140)

    change_colormap_slider = ui.LineSlider2D(min_value=0,
                                    max_value=1.0,
                                    initial_value=0,
                                    text_template="",
                                    length=40)

    change_iteration_slider = ui.LineSlider2D(min_value=0,
                    #we can't have max_value=num_iteration because
                    #list_x_file[num_iteration] lead to an error
                                    max_value=num_iteration-0.01,
                                    initial_value=0,
                                    text_template=list_x_file[0],
                                    length=140)

    remove_big_weights_slider = ui.LineSlider2D(min_value=0,
                                    max_value=max_weight,
                                    initial_value=max_weight,
                                    text_template="{value:.2f}",
                                    length=140)

    remove_small_weights_slider = ui.LineSlider2D(min_value=0,
                                    max_value=max_weight,
                                    initial_value=0,
                                    text_template="{value:.2f}",
                                    length=140)

    opacity_slider = ui.LineSlider2D(min_value=0.0,
                                     max_value=1.0,
                                     initial_value=0.5,
                                     text_template="{ratio:.0%}",
                                     length=140)

    save_one_image_bouton.add_callback(save_one_image_bouton.slider_disk,
                                "LeftButtonPressEvent", save_one_image)

    color_slider.add_callback(color_slider.slider_disk,
                                "MouseMoveEvent", change_streamlines_color)
    color_slider.add_callback(color_slider.slider_line,
                               "LeftButtonPressEvent", change_streamlines_color)
    add_graph_bouton.add_callback(add_graph_bouton.slider_disk,
                                "LeftButtonPressEvent", add_graph)

    change_colormap_slider.add_callback(change_colormap_slider.slider_disk,
                                "MouseMoveEvent", change_colormap)
    change_colormap_slider.add_callback(change_colormap_slider.slider_line,
                                "LeftButtonPressEvent", change_colormap)
    change_iteration_slider.add_callback(change_iteration_slider.slider_disk,
                                "MouseMoveEvent", change_iteration)
    change_iteration_slider.add_callback(change_iteration_slider.slider_line,
                               "LeftButtonPressEvent", change_iteration)

    remove_big_weights_slider.add_callback(remove_big_weights_slider.slider_disk,
                                "MouseMoveEvent", remove_big_weight)
    remove_big_weights_slider.add_callback(remove_big_weights_slider.slider_line,
                               "LeftButtonPressEvent", remove_big_weight)

    remove_small_weights_slider.add_callback(remove_small_weights_slider.slider_disk,
                                "MouseMoveEvent", remove_small_weight)
    remove_small_weights_slider.add_callback(remove_small_weights_slider.slider_line,
                               "LeftButtonPressEvent", remove_small_weight)
    opacity_slider.add_callback(opacity_slider.slider_disk,
                                "MouseMoveEvent", change_opacity)
    opacity_slider.add_callback(opacity_slider.slider_line,
                               "LeftButtonPressEvent", change_opacity)

    color_slider_label = ui.TextBlock2D()
    color_slider_label.message = 'color of streamlines'

    change_colormap_slider_label_weight = ui.TextBlock2D()
    change_colormap_slider_label_weight.message = 'weight color'
    change_colormap_slider_label_direction = ui.TextBlock2D()
    change_colormap_slider_label_direction.message = 'direction color'

    change_iteration_slider_label = ui.TextBlock2D()
    change_iteration_slider_label.message = 'number of the iteration'

    remove_big_weights_slider_label = ui.TextBlock2D()
    remove_big_weights_slider_label.message = 'big weights subdued'

    remove_small_weights_slider_label = ui.TextBlock2D()
    remove_small_weights_slider_label.message = 'small weights subdued'

    opacity_slider_label = ui.TextBlock2D()
    opacity_slider_label.message = 'Unwanted weights opacity'

    numbers_of_streamlines_in_interval = ui.TextBlock2D()
    numbers_of_streamlines_in_interval.message = "Number of streamlines in interval: "+str(num_streamlines)


    panel = ui.Panel2D(center=(300, 160),
                       size=(500, 280),
                       color=(1, 1, 1),
                       opacity=0.1,
                       align="right")

    panel.add_element(save_one_image_bouton, 'relative', (0.9, 0.9))
    panel.add_element(add_graph_bouton, 'relative', (0.9, 0.77))
    panel.add_element(color_slider_label, 'relative', (0.05, 0.85))
    panel.add_element(color_slider, 'relative', (0.7, 0.9))
    panel.add_element(numbers_of_streamlines_in_interval, 'relative', (0.05, 0.72))
    panel.add_element(change_colormap_slider_label_weight, 'relative', (0.05, 0.59))
    panel.add_element(change_colormap_slider_label_direction, 'relative', (0.5, 0.59))
    panel.add_element(change_colormap_slider, 'relative', (0.4, 0.64))
    panel.add_element(change_iteration_slider_label, 'relative', (0.05, 0.46))
    panel.add_element(change_iteration_slider, 'relative', (0.7, 0.51))
    panel.add_element(remove_big_weights_slider_label, 'relative', (0.05, 0.33))
    panel.add_element(remove_big_weights_slider, 'relative', (0.7, 0.37))
    panel.add_element(remove_small_weights_slider_label, 'relative', (0.05, 0.2))
    panel.add_element(remove_small_weights_slider, 'relative', (0.7, 0.24))
    panel.add_element(opacity_slider_label, 'relative', (0.05, 0.07))
    panel.add_element(opacity_slider, 'relative', (0.7, 0.11))

    panel.add_to_renderer(renderer)
    renderer.reset_clipping_range()

    show_m.render()
    show_m.start()
Exemple #18
0
else:
    Nativegroupstreamlines = Nativegroupstreamlines2
    groupLinesFA = groupLinesFA2
    name = 'Group_Old'

cmap = actor.colormap_lookup_table(scale_range=(np.min(groupLinesFA),
                                                np.max(groupLinesFA)))

renderer = window.Renderer()
stream_actor = actor.line(Nativegroupstreamlines,
                          np.array(groupLinesFA),
                          lookup_colormap=cmap)
fa_actor = actor.slicer(fa_control, np.eye(4))
renderer.add(stream_actor)
renderer.add(fa_actor)
bar = actor.scalar_bar(cmap)
renderer.add(bar)
# Uncomment the line below to show to display the window
window.show(renderer, size=(600, 600), reset_camera=False)
window.record(renderer,
              size=(600, 600),
              out_path=outpath + '/' + str(target_l) + '--' + str(target_r) +
              name + ' lineFA Viz.png')

# %%
##### color by points
group = 1

if group == 1:
    Nativegroupstreamlines = Nativegroupstreamlines1
    groupPointsFA = groupPointsFA1
Exemple #19
0
"""
Show every point with a value from a volume with default colormap
=================================================================

Here we will need to input the ``fa`` map in ``streamtube`` or ``line``.
"""

renderer.clear()
stream_actor2 = actor.line(bundle_native, fa, linewidth=0.1)

"""
We can also show the scalar bar.
"""

bar = actor.scalar_bar()

renderer.add(stream_actor2)
renderer.add(bar)

# window.show(renderer, size=(600, 600), reset_camera=False)
window.record(renderer, out_path="bundle2.png", size=(600, 600))

"""
.. figure:: bundle2.png
   :align: center

   **Every point with a color from FA**.

Show every point with a value from a volume with your colormap
==============================================================
Exemple #20
0
def plot_bundles_with_metric(bundle_path,
                             endings_path,
                             brain_mask_path,
                             bundle,
                             metrics,
                             output_path,
                             tracking_format="trk_legacy",
                             show_color_bar=True):
    import seaborn as sns  # import in function to avoid error if not installed (this is only needed in this function)
    from dipy.viz import actor, window
    from tractseg.libs import vtk_utils

    def _add_extra_point_to_last_streamline(sl):
        # Coloring broken as soon as all streamlines have same number of points -> why???
        # Add one number to last streamline to make it have a different number
        sl[-1] = np.append(sl[-1], [sl[-1][-1]], axis=0)
        return sl

    # Settings
    NR_SEGMENTS = 100
    ANTI_INTERPOL_MULT = 1  # increase number of points to avoid interpolation to blur the colors
    algorithm = "distance_map"  # equal_dist | distance_map | cutting_plane
    # colors = np.array(sns.color_palette("coolwarm", NR_SEGMENTS))  # colormap blue to red (does not fit to colorbar)
    colors = np.array(sns.light_palette(
        "red", NR_SEGMENTS))  # colormap only red, which fits to color_bar
    img_size = (1000, 1000)

    # Tractometry skips first and last element. Therefore we only have 98 instead of 100 elements.
    # Here we duplicate the first and last element to get back to 100 elements
    metrics = list(metrics)
    metrics = np.array([metrics[0]] + metrics + [metrics[-1]])

    metrics_max = metrics.max()
    metrics_min = metrics.min()
    if metrics_max == metrics_min:
        metrics = np.zeros(len(metrics))
    else:
        metrics = img_utils.scale_to_range(
            metrics,
            range=(0, 99))  # range needs to be same as segments in colormap

    orientation = dataset_specific_utils.get_optimal_orientation_for_bundle(
        bundle)

    # Load mask
    beginnings_img = nib.load(endings_path)
    beginnings = beginnings_img.get_data()
    for i in range(1):
        beginnings = binary_dilation(beginnings)

    # Load trackings
    if tracking_format == "trk_legacy":
        streams, hdr = trackvis.read(bundle_path)
        streamlines = [s[0] for s in streams]
    else:
        sl_file = nib.streamlines.load(bundle_path)
        streamlines = sl_file.streamlines

    # Reduce streamline count
    streamlines = streamlines[::2]

    # Reorder to make all streamlines have same start region
    streamlines = fiber_utils.add_to_each_streamline(streamlines, 0.5)
    streamlines_new = []
    for idx, sl in enumerate(streamlines):
        startpoint = sl[0]
        # Flip streamline if not in right order
        if beginnings[int(startpoint[0]),
                      int(startpoint[1]),
                      int(startpoint[2])] == 0:
            sl = sl[::-1, :]
        streamlines_new.append(sl)
    streamlines = fiber_utils.add_to_each_streamline(streamlines_new, -0.5)

    if algorithm == "distance_map" or algorithm == "equal_dist":
        streamlines = fiber_utils.resample_fibers(
            streamlines, NR_SEGMENTS * ANTI_INTERPOL_MULT)
    elif algorithm == "cutting_plane":
        streamlines = fiber_utils.resample_to_same_distance(
            streamlines,
            max_nr_points=NR_SEGMENTS,
            ANTI_INTERPOL_MULT=ANTI_INTERPOL_MULT)

    # Cut start and end by percentage
    # streamlines = FiberUtils.resample_fibers(streamlines, NR_SEGMENTS * ANTI_INTERPOL_MULT)
    # remove = int((NR_SEGMENTS * ANTI_INTERPOL_MULT) * 0.15)  # remove X% in beginning and end
    # streamlines = np.array(streamlines)[:, remove:-remove, :]
    # streamlines = list(streamlines)

    if algorithm == "equal_dist":
        segment_idxs = []
        for i in range(len(streamlines)):
            segment_idxs.append(list(range(NR_SEGMENTS * ANTI_INTERPOL_MULT)))
        segment_idxs = np.array(segment_idxs)

    elif algorithm == "distance_map":
        metric = AveragePointwiseEuclideanMetric()
        qb = QuickBundles(threshold=100., metric=metric)
        clusters = qb.cluster(streamlines)
        centroids = Streamlines(clusters.centroids)
        _, segment_idxs = cKDTree(centroids.data, 1,
                                  copy_data=True).query(streamlines, k=1)

    elif algorithm == "cutting_plane":
        streamlines_resamp = fiber_utils.resample_fibers(
            streamlines, NR_SEGMENTS * ANTI_INTERPOL_MULT)
        metric = AveragePointwiseEuclideanMetric()
        qb = QuickBundles(threshold=100., metric=metric)
        clusters = qb.cluster(streamlines_resamp)
        centroid = Streamlines(clusters.centroids)[0]
        # index of the middle cluster
        middle_idx = int(NR_SEGMENTS / 2) * ANTI_INTERPOL_MULT
        middle_point = centroid[middle_idx]
        segment_idxs = fiber_utils.get_idxs_of_closest_points(
            streamlines, middle_point)
        # Align along the middle and assign indices
        segment_idxs_eqlen = []
        for idx, sl in enumerate(streamlines):
            sl_middle_pos = segment_idxs[idx]
            before_elems = sl_middle_pos
            after_elems = len(sl) - sl_middle_pos
            base_idx = 1000  # use higher index to avoid negative numbers for area below middle
            r = range((base_idx - before_elems), (base_idx + after_elems))
            segment_idxs_eqlen.append(r)
        segment_idxs = segment_idxs_eqlen

    # Add extra point otherwise coloring BUG
    streamlines = _add_extra_point_to_last_streamline(streamlines)

    renderer = window.Renderer()
    colors_all = []  # final shape will be [nr_streamlines, nr_points, 3]
    for jdx, sl in enumerate(streamlines):
        colors_sl = []
        for idx, p in enumerate(sl):
            if idx >= len(segment_idxs[jdx]):
                seg_idx = segment_idxs[jdx][idx - 1]
            else:
                seg_idx = segment_idxs[jdx][idx]

            m = metrics[int(seg_idx / ANTI_INTERPOL_MULT)]
            color = colors[int(m)]
            colors_sl.append(color)
        colors_all.append(
            colors_sl
        )  # this can not be converted to numpy array because last element has one more elem

    sl_actor = actor.streamtube(streamlines,
                                colors=colors_all,
                                linewidth=0.2,
                                opacity=1)
    renderer.add(sl_actor)

    # plot brain mask
    mask = nib.load(brain_mask_path).get_data()
    cont_actor = vtk_utils.contour_from_roi_smooth(
        mask,
        affine=beginnings_img.affine,
        color=[.9, .9, .9],
        opacity=.2,
        smoothing=50)
    renderer.add(cont_actor)

    if show_color_bar:
        lut_cmap = actor.colormap_lookup_table(scale_range=(metrics_min,
                                                            metrics_max),
                                               hue_range=(0.0, 0.0),
                                               saturation_range=(0.0, 1.0))
        renderer.add(actor.scalar_bar(lut_cmap))

    if orientation == "sagittal":
        renderer.set_camera(position=(-412.95, -34.38, 80.15),
                            focal_point=(102.46, -16.96, -11.71),
                            view_up=(0.1806, 0.0, 0.9835))
    elif orientation == "coronal":
        renderer.set_camera(position=(-48.63, 360.31, 98.37),
                            focal_point=(-20.16, 92.89, 36.02),
                            view_up=(-0.0047, -0.2275, 0.9737))
    elif orientation == "axial":
        pass
    else:
        raise ValueError("Invalid orientation provided")

    # Use this to interatively get new camera angle
    # window.show(renderer, size=img_size, reset_camera=False)
    # print(renderer.get_camera())

    window.record(renderer, out_path=output_path, size=img_size)