Пример #1
0
def complete(final_solution: Solution,
             correct_solution: Solution = None) -> None:
    """
    Will print result in 3D world
    :return: Noting
    """

    # init of plot-output #1
    figure = plot.figure()
    axes = figure.add_subplot(111, projection='3d')

    for part in final_solution.partitions:
        color = random.choice(list_of_colors)
        marker = random.choice(list_of_marker)
        for p in part:
            axes.scatter(p.x, p.y, p.z, marker=marker, c=color)

    axes.set_xlabel("X Achse")
    axes.set_ylabel("Y Achse")
    axes.set_zlabel("Z Achse")
    plot.show()

    # init 3D view
    ipv.current.containers.clear()
    ipv.current.figures.clear()

    extra_figures = list()
    # create correct solution
    if correct_solution is not None:
        figure_correct = ipv.figure("correct")
        ipv.pylab.xyzlim(-1, 11)
        for part in correct_solution.partitions:
            marker = random.choice(list_of_IPYVmarker)
            color = random.choice(list_of_colors)
            ipv.scatter(*convert.partition_to_IpyVolume(part),
                        marker=marker,
                        color=color)
        extra_figures.append(figure_correct)
    figure_result = ipv.figure("result")
    container = ipv.gcc()
    ipv.current.container = widgets.HBox(container.children)
    ipv.current.containers["result"] = ipv.current.container

    # crate computed solution
    for part in final_solution.partitions:
        marker = random.choice(list_of_IPYVmarker)
        color = random.choice(list_of_colors)
        ipv.scatter(*convert.partition_to_IpyVolume(part),
                    marker=marker,
                    color=color)

    ipv.pylab.xyzlim(-1, 11)
    ipv.current.container.children = list(
        ipv.current.container.children) + extra_figures
    ipv.show()
    # save in a separate file
    ipv.save("example.html")

    # destroy 3D views
    ipv.clear()
Пример #2
0
def plot_mesh(value_mesh_list, w1_mesh, w2_mesh, save, show_box, show_axes):
    ipv.clear()
    figs = []
    for mesh in value_mesh_list:
        fig = ipv.pylab.figure()
        fig.camera.up = (0, 0, 1)
        fig.camera.position = (-2, 1, -0.5)
        fig.camera_control = "trackball"
        if not show_axes:
            ipv.style.box_off()
        else:
            ipv.xlabel("w1")
            ipv.ylabel("w2")
            ipv.zlabel("f_lambda")
        if not show_box:
            ipv.pylab.style.axes_off()

        ipv.pylab.zlim(mesh.min(), mesh.max())
        ptp = (mesh - mesh.min()).ptp()

        col = []
        for m in mesh:
            znorm = (m - m.min()) / (m.max() - m.min() + 1e-8)
            color = np.asarray([[interpolate(darker(colors_alpha[0], 1.5 * x + 0.75),
                                             darker(colors_alpha[1], 1.5 * (1 - x) + 0.75), x) for x in y] for y in
                                znorm])
            col.append(color)
        color = np.array(col)
        surf = ipv.plot_surface(w1_mesh, w2_mesh, mesh, color=color[..., :3])
        ipv.animation_control(surf, interval=400)
        figs.append(fig)
        ipv.show()
    if save:
        ipv.save(f'renders/{datetime.datetime.now().strftime("%m%d-%H%M")}.html', offline=True)
    return figs
Пример #3
0
def PlotSkeleton(seg_name, plot_type='node', out_res=(30, 48, 48)):
    print('Read skeletons')
    skeletons = ReadSkeletons(seg_name,
                              skeleton_algorithm='thinning',
                              downsample_resolution=out_res,
                              read_edges=True)

    print('Plot skeletons')
    node_list = skeletons[1].get_nodes()
    nodes = np.stack(node_list).astype(float)
    junction_idx = skeletons[1].get_junctions()
    junctions = nodes[junction_idx, :]
    ends = skeletons[1].get_ends()
    jns_ends = np.vstack([junctions, ends])

    IX, IY, IZ = 2, 1, 0
    ipv.figure()
    if plot_type == 'nodes':
        nodes = ipv.scatter(nodes[:,IX], nodes[:,IY], nodes[:,IZ], \
                            size=0.5, marker='sphere', color='blue')
    elif plot_type == 'edges':
        edges = skeletons[1].get_edges().astype(float)
        for e1, e2 in edges:
            if not ((e1[IX] == e2[IX]) and (e1[IY] == e2[IY]) and
                    (e1[IZ] == e2[IZ])):
                ipv.plot([e1[IX], e2[IX]], [e1[IY], e2[IY]], [e1[IZ], e2[IZ]], \
                         color='blue')

    jns = ipv.scatter(jns_ends[:,IX], jns_ends[:,IY], jns_ends[:,IZ], \
                      size=0.85, marker='sphere', color='red')
    ipv.pylab.style.axes_off()
    ipv.pylab.style.box_off()

    ipv.save(seg_name + '_skel.html')
def particleSimulate(num_particles,
                     box_size,
                     total_time,
                     time_step,
                     particle_radius,
                     grav=False,
                     save=False):

    print("Running simulation...")
    """Run the simulation and extract the x,y,z coordinates to plot the particle's path"""
    particle_list = initialize_particles(num_particles, box_size, time_step,
                                         grav)  #Generate starting points

    x = np.zeros([total_time, num_particles, 1])
    y = np.zeros([total_time, num_particles, 1])
    z = np.zeros([total_time, num_particles, 1])

    time = 0

    #print(str(tot_eng(particle_list))) #Used to track the total energy of the particles

    while time < total_time:  #Loop through iterations of particle movements

        #Check to see if bouncing occurs
        isbounce(particle_list, particle_radius, time_step)

        for i in range(len(particle_list)):
            particle_list[i].pos_update(time_step)  #Update position

            x[time, i] = particle_list[i].pos[0]
            y[time, i] = particle_list[i].pos[1]
            z[time, i] = particle_list[i].pos[2]

        time += 1

        if (time / total_time) * 100 % 10 == 0:
            print(str(time / total_time * 100) + "% complete")
    """Plot the results of all of the particle movements"""

    colors = []
    for i in range(num_particles):
        colors.append(
            [np.random.random(),
             np.random.random(),
             np.random.random()])

    ipv.figure()
    s = ipv.scatter(x, z, y, color=colors, size=7, marker="sphere")
    ipv.animation_control(s, interval=1)
    ipv.xlim(-1, box_size + 1)
    ipv.ylim(-1, box_size + 1)
    ipv.zlim(-1, box_size + 1)

    ipv.style.axes_off()
    ipv.show()

    if save == True:
        print("Saving the video of the simulation in the current directory...")
        ipv.save('./particle_sim.html')
Пример #5
0
def SaveMeshAsHTML(cell_dir, stl_id, mesh_dir='./'):
    in_mesh = GetMesh(cell_dir, stl_id)
    IX, IY, IZ = 2, 1, 0
    x, y, z = in_mesh.vertices[:,IX].astype(float), \
                in_mesh.vertices[:,IY].astype(float), \
                in_mesh.vertices[:,IZ].astype(float)
    triangles = in_mesh.faces
    ipv.figure()
    mesh = ipv.plot_trisurf(x, y, z, triangles=triangles, color='skyblue')
    ipv.pylab.style.axes_off()
    ipv.pylab.style.box_off()
    ipv.save(os.path.join(mesh_dir, 'mesh' + str(stl_id) + '.html'))
Пример #6
0
def visualize_sphere_grids(s2_grids,
                           params,
                           folder='grid',
                           colors=["#7b0001", "#ff0001", "#ff8db4"]):
    fig = ipv.figure()
    for _, layer_grids in s2_grids:
        for i, (_, shell) in enumerate(layer_grids):
            shell = shell.reshape(-1, 3).transpose(0, 1)  # tensor([3, 4b^2]
            x_axis = shell[0, :].cpu().numpy()
            y_axis = shell[1, :].cpu().numpy()
            z_axis = shell[2, :].cpu().numpy()
            ipv.scatter(x_axis,
                        y_axis,
                        z_axis,
                        marker="sphere",
                        color=colors[i])
    ipv.save("./imgs/{}/s2_sphere_sphere.html".format(folder))
Пример #7
0
    def plot_3D(self,
                timestep=0,
                do_scatter=False,
                color_scheme="tab10",
                num_colors=13,
                do_vr=False):
        """! \brief Plots the dislocation system in 3D at the given timestep.

        \param timestep The timestep to plot
        \param do_scatter Whether to plot dislocation nodes or not
        \param color_scheme The color scheme for dislocation lines
        \param num_colors The number of colors in the given color_scheme
        \param do_vr Whether to save the link for using VR or not

        """

        # Creating the graph
        g = Graph(self.protobuf, timestep, color_scheme, num_colors)

        # Collect the information to plot
        lines, colors = g.dfs()

        # Segmenting data for the plot
        fig = ipv.figure()
        for line, color in zip(lines, colors):
            xs, ys, zs, x, y, z = self.convert_line_to_coordinates(line)
            ipv.pylab.plot(x,
                           y,
                           z,
                           color=color,
                           size=5,
                           connected=True,
                           visible_markers=True,
                           marker='diamond')

        # Draw dots
        if do_scatter:
            scatter = ipv.scatter(xs, ys, zs)

        # Save the figure for VR
        if do_vr:
            ipv.save("Plotter_VR.html")

        ipv.show()
Пример #8
0
import ipyvolume as ipv
import numpy as np

N = 10000
x, y, z = np.random.normal(0, 1, (3, N))

fig = ipv.figure()
scatter = ipv.scatter(x, y, z, marker="sphere")
ipv.save("here.html")
Пример #9
0
def visualize_sphere_sphere(origins,
                            data,
                            labels,
                            s2_grids,
                            params,
                            folder='sphere',
                            num_selections=5):
    """
    data :  list( list( Tensor([B, 1, 2b0, 2b0]) * num_grids ) * num_centers)
    s2_grids: [center, [(radius, tensor([2b, 2b, 3])) * num_grids]]
    """
    if params['use_static_sigma']:
        subfolder = "static_sigma_{}".format(params['static_sigma'])
    else:
        if params['sigma_layer_diff']:
            subfolder = "conv_sigma_diff_over_layer"
        else:
            subfolder = "conv_sigma_share_over_layer"

    for i in range(num_selections):
        label = str(labels[i].item())
        for j, grids in enumerate(data):
            fig, axs = plt.subplots(1, 3)
            for k, grid in enumerate(grids):
                grid = grid[i][0]
                grid = grid.detach().cpu().numpy()  # [2b, 2b]
                axs[k].set_title('Label {}, Center {}, Layer {}'.format(
                    label, j, k))
                axs[k].imshow(grid)
            plt.savefig(
                './imgs/{}/{}/map/sphere-label[{}]-center[{}]-map.png'.format(
                    folder, subfolder, label, j))
            plt.close()

    for i in range(num_selections):
        label = str(labels[i].item())
        fig = ipv.figure()
        image = origins[i].detach().cpu().numpy()
        ipv.scatter(image[:, 0],
                    image[:, 1],
                    image[:, 2],
                    marker='diamond',
                    color='red')

        for j, grids in enumerate(data):
            _, center_grid = s2_grids[j]
            center_data = data[j]
            for k, shell in enumerate(grids):
                _, shell_grid = center_grid[k]  # Tensor([2b, 2b, 3])
                shell_data = center_data[k][i]  # Tensor([1, 2b0, 2b0])
                shell_grid = shell_grid.view(-1, 3)
                x = shell_grid[:, 0].squeeze().cpu().numpy()
                y = shell_grid[:, 1].squeeze().cpu().numpy()
                z = shell_grid[:, 2].squeeze().cpu().numpy()

                # For Color Showing
                shell_data = shell_data.permute(1, 2,
                                                0)  # Tensor([2b0, 2b0, 1])
                shell_data = shell_data.view(
                    -1, 1)[:, 0].detach().cpu().numpy()  # Tensor([4b0^2])
                color_data = (shell_data - np.min(shell_data)) / (
                    np.max(shell_data) - np.min(shell_data))
                color_data = np.expand_dims(color_data,
                                            axis=-1).repeat(2, axis=-1)
                color = np.zeros((color_data.shape[0], 4))
                color[:, 0:2] = color_data
                color[:, 2] = 0.4  # Adjust Color [NEED NOT CHANGE]
                color[:, 3] = 1  # Transparancy [DO NOT CHANGE]

                ipv.scatter(x, y, z, marker='sphere', color=color)

        ipv.save('./imgs/{}/{}/grid/sphere-label[{}]-grid.html'.format(
            folder, subfolder, label))
Пример #10
0
fig = p3.figure()
# create a custom LUT
temp_tf = plt.cm.nipy_spectral(np.linspace(0, 1, 256))
# make transparency more aggressive
temp_tf[:, 3] = np.linspace(-0.3, 0.5, 256).clip(0, 1)
tf = p3.transferfunction.TransferFunction(rgba=temp_tf)
p3.volshow(
    (thickness_map[::2, ::2, ::2] / thickness_map.max()).astype(np.float32),
    lighting=True,
    max_opacity=0.5,
    tf=tf,
    controls=True,
)

p3.show()
p3.save("bubbles.html")

# # Interfaces / Surfaces
#
# Many physical and chemical processes occur at surfaces and interfaces and consequently these structures are important in material science and biology. For this lecture surface and interface will be used interchangebly and refers to the boundary between two different materials (calcified bone and soft tissue, magma and water, liquid and gas) Through segmentation we have identified the unique phases in the sample under investigation.
#
# - Segmentation identifying volumes (3D) or areas (2D)
# - Interfaces are one dimension lower corresponding to surface area (3D) or perimeter (2D)
# - Interfaces are important for
#  - connectivity of cell networks, particularly neurons
#  - material science processes like coarsening or rheological behavior
#  - chemical processes (surface-bound diffusion, catalyst action)

# # Surface Area / Perimeter
#
# We see that the dilation and erosion affects are strongly related to the surface area of an object: the more surface area the larger the affect of a single dilation or erosion step.
Пример #11
0
def display_widgets(
    widget_list,
    filename=None,
):
    assert options.mesh_method == 'ipyvolume'

    if not options.interactive:

        # For rendering run command in terminal:
        #    chromium-browser --remote-debugging-port=9222
        # try:
        # use headless chrome to save figure

        d = ipv.pylab._screenshot_data(headless=True, format='png')
        # except Exception as e:
        #     utils.warn_always('For rendering run command in terminal:\n\n    chromium-browser --remote-debugging-port=9222\n')
        #     raise(e)
        img = Image(d)
        #   img = Image(value=d, format='png')

        if options.save_images:
            if filename is None:
                pattern = str(options.filename_pattern_image)
                filename = pattern.format(
                    fig_number=options.fig_number) + '.png'
            filename = Path(filename)
            if not filename.parent.exists():
                filename.parent.mkdir(parents=True)

            with open(filename, "wb") as f:
                f.write(d)
                options.fig_number += 1
                if options.verbose:
                    display(
                        FileLink(filename,
                                 result_html_prefix="Saved to file: ",
                                 result_html_suffix=''))

        # TODO: save html
        if options.save_htmls:
            pattern = str(options.filename_pattern_image)
            filename = pattern.format(fig_number=options.fig_number) + '.html'
            filename = Path(filename)
            if not filename.parent.exists():
                filename.parent.mkdir(parents=True)

            title = filename.name[:-4]
            ipv.save(filename, title=title)
            if options.verbose:
                display(
                    FileLink(filename,
                             result_html_prefix="Saved to file: ",
                             result_html_suffix=''))

        return img

    if options.interactive:
        # TODO: save_html

        # ipv.save('test.html')
        return VBox(widget_list)