Ejemplo n.º 1
0
def viz_dimer_positions_ipv(positions,
                            size=5,
                            cmap_name="tab20c",
                            color_feature_name=None):

    try:
        import ipyvolume as ipv
    except ImportError:
        mess = "YOu need to install the ipyvolume library. "
        mess += "Please follow the official instructions at https://github.com/maartenbreddels/ipyvolume."
        raise ImportError(mess)

    # Only show visible dimers
    selected_dimers = positions[positions["visible"]]

    x, y, z = selected_dimers[["x", "y", "z"]].values.astype("float").T

    if color_feature_name:
        # TODO: that code should be much simpler...
        cmap = matplotlib.cm.get_cmap(cmap_name)
        categories = selected_dimers[color_feature_name].unique()
        color_indices = cmap([i / len(categories) for i in categories])

        color = np.zeros((len(selected_dimers[color_feature_name]), 4))
        for color_index, _ in enumerate(categories):
            mask = selected_dimers[color_feature_name] == categories[
                color_index]
            color[mask] = color_indices[color_index]
    else:
        color = "#e4191b"

    ipv.figure(height=800, width=1000)
    ipv.scatter(x, y, z, size=size, marker="sphere", color=color)
    ipv.squarelim()
    ipv.show()
Ejemplo n.º 2
0
    def plot_clusters(self, threshold, rcut=28, size=5.):
        ipv.clear()

        s = self.trace <= threshold
        xyz = self.stress_coord[s]

        x, y, z = xyz[:, 0], xyz[:, 1], xyz[:, 2]
        clustering = DBSCAN(eps=rcut, min_samples=1).fit(xyz)
        labels = np.unique(clustering.labels_)

        counts, edges = np.histogram(clustering.labels_,
                                     bins=np.arange(labels.min(),
                                                    labels.max() + 1))

        largest = edges[counts.argmax()]

        color_dict = {}
        for l in labels:
            color_dict[l] = tuple(np.random.uniform(0, 1, size=3))

        color_dict[largest] = (1, 1, 1)
        colors = np.array([color_dict[c] for c in clustering.labels_])

        color = np.array([(x - x.min()) / x.ptp(),
                          np.ones_like(x),
                          np.ones_like(x)]).T
        ipv.scatter(x, y, z, size=size, marker="sphere", color=colors)

        ipv.show()
Ejemplo n.º 3
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()
def FCC(L_x, L_y, L_z, Color='red'):
    Ax = []
    Ay = []
    Az = []
    #for each layer of the atom in the x direction. the *2-1 is so that L_x is the number of unit cells
    for O in range(L_x * 2 - 1):
        #for each layer in the y direction.
        for S in range(L_y * 2 - 1):
            #for each layer in the z direction.
            for A in range(L_z * 2 - 1):
                if (O + S + A) % 2 == 0:
                    #the 0.5 is becasue L_xyz was multiplied by 2
                    Ax.append(float(O * .5))
                    Ay.append(float(S * .5))
                    Az.append(float(A * .5))
                elif S % 2 == 1 and O % 2 == 1 and A % 2 == 0:
                    Ax.append(float(O * .5))
                    Ay.append(float(S * .5))
                    Az.append(float(A * .5))
                #if there should not be an atom
                #in theory this could be used to remove other atoms to make cubic or BCC structure
    #the x, y, z limits
    ipv.xyzlim(0, 10)  #define as a function highest of L_xyz
    ipv.scatter(np.array(Ax),
                np.array(Ay),
                np.array(Az),
                marker='sphere',
                size=6.5,
                color=Color)
    ipv.show()
Ejemplo n.º 5
0
def show_colorspace(cspace: np.array,
                    clip=True,
                    size=0.5,
                    marker='sphere',
                    **kwargs) -> None:
    """
    Visualise colorspace vector as an interactive 3D figure. Colorspace can have extra columns
     
    By default RGB channels are clipped to the range [0,1]. 
    Extra arguments can be used to control the appearance of ipyvolume.scatter
    """

    assert isinstance(cspace, DataFrame), "Colorspace must be a dataframe"
    assert all(np.isin(['R', 'G', 'B'],
                       cspace.columns)), "Colorspace must contain RGB columns"

    fig = ipv.figure()
    if clip:
        ipv.scatter(cspace.loc[:, 'R'].values,
                    cspace.loc[:, 'G'].values,
                    cspace.loc[:, 'B'].values,
                    color=np.clip(cspace[['R', 'G', 'B']].values, 0, 1),
                    s=size,
                    marker=marker,
                    *kwargs)
    else:
        ipv.scatter(cspace.loc[:, 'R'].values,
                    cspace.loc[:, 'G'].values,
                    cspace.loc[:, 'B'].values,
                    color=cspace[['R', 'G', 'B']].values,
                    s=size,
                    marker=marker,
                    *kwargs)
    ipv.show()
Ejemplo n.º 6
0
def viz_dimer_positions(positions,
                        size=5,
                        cmap_name="tab20c",
                        color_feature_name=None):
    import ipyvolume as ipv

    # Only show visible dimers
    selected_dimers = positions[positions['visible'] is True]

    x, y, z = selected_dimers[['x', 'y', 'z']].values.astype('float').T

    if color_feature_name:
        # TODO: that code should be much simpler...
        cmap = matplotlib.cm.get_cmap(cmap_name)
        categories = selected_dimers[color_feature_name].unique()
        color_indices = cmap([i / len(categories) for i in categories])

        color = np.zeros((len(selected_dimers[color_feature_name]), 4))
        for color_index in enumerate(categories):
            color[selected_dimers[color_feature_name] ==
                  categories[color_index]] = color_indices[color_index]
    else:
        color = '#e4191b'

    ipv.figure(height=800, width=1000)
    ipv.scatter(x, y, z, size=size, marker='sphere', color=color)
    ipv.squarelim()
    ipv.show()
Ejemplo n.º 7
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')
Ejemplo n.º 8
0
    def _display_sphere(
        self,
        fluxes,
        distances,
        theta,
        phi,
        cmap="magma",
        distance_transform=None,
        use_log=False,
        fig=None,
        background_color="white",
        show=True,
        **kwargs,
    ):

        if len(fluxes) == 0:
            log.warning("There are no detections to display")

            return

        if fig is None:

            fig = ipv.figure()

        ipv.pylab.style.box_off()
        ipv.pylab.style.axes_off()
        ipv.pylab.style.set_style_dark()
        ipv.pylab.style.background_color(background_color)

        if distance_transform is not None:

            distance = distance_transform(distances)

        else:

            distance = distances

        x, y, z = _create_sphere_variables(self._r_max, distance, theta, phi)

        _, colors = array_to_cmap(fluxes, cmap, use_log=True)

        ipv.scatter(x, y, z, color=colors, marker="sphere", **kwargs)

        r_value = fig

        if show:

            ipv.xyzlim(self._r_max)
            fig.camera.up = [1, 0, 0]
            control = pythreejs.OrbitControls(controlling=fig.camera)
            fig.controls = control
            control.autoRotate = True
            fig.render_continuous = True
            # control.autoRotate = True
            # toggle_rotate = widgets.ToggleButton(description="Rotate")
            # widgets.jslink((control, "autoRotate"), (toggle_rotate, "value"))
            # r_value = toggle_rotate

        return fig
Ejemplo n.º 9
0
    def plot_geometry(self,
                      plot_e_r=True,
                      plot_e_phi=True,
                      plot_e_theta=True,
                      plot_bezier=True,
                      bezier_order=3):
        """Generates 3D ipyvolume plot
        """
        fig = ipv.figure()

        scatter = ipv.scatter(self.center[:, 0],
                              self.center[:, 1],
                              self.center[:, 2],
                              color='#ff0000',
                              size=5)

        if plot_e_r:
            self._my_ipv_vectorplot(np.repeat(self.center,
                                              len(self.points),
                                              axis=0),
                                    self.e_r,
                                    length=1,
                                    N=1000,
                                    size=0.2,
                                    color='#00ff00')

        if plot_e_theta:
            self._my_ipv_vectorplot(self.points,
                                    self.e_theta,
                                    length=0.05,
                                    N=100,
                                    size=0.2,
                                    color='#ff0000')

        if plot_e_phi:
            self._my_ipv_vectorplot(self.points,
                                    self.e_phi,
                                    length=0.05,
                                    N=100,
                                    size=0.2,
                                    color='#ff0000')

        if plot_bezier:
            assert 1 <= bezier_order <= 3
            p = self._arrange_bezier_points(self.bezier_points,
                                            order=bezier_order)
            self._plot_bezier_curves(p, N=100, size=0.5, color='#ff00ff')

        scatter = ipv.scatter(self.points[:, 0],
                              self.points[:, 1],
                              self.points[:, 2],
                              color='#0000bb',
                              size=1)

        ipv.xlim(0, 1)
        ipv.ylim(0, 1)
        ipv.zlim(0, 1)

        return fig
Ejemplo n.º 10
0
def plot_voxel(voxels_position, marker="box", color="green", size=2.0):
    if len(voxels_position) > 0:
        x, y, z = (voxels_position[:,
                                   0], voxels_position[:,
                                                       1], voxels_position[:,
                                                                           2])

        ipyvolume.scatter(x, y, z, size=size, marker=marker, color=color)
Ejemplo n.º 11
0
 def _plot_bezier_curves(list_p, N=10, **kwargs):
     """Plot neurites as bezier curves.
     """
     curves = []
     for t in np.linspace(0, 1, N):
         tmp = volutils.bezier(t, list_p)
         curves.append(tmp)
     curves = np.concatenate(curves, axis=0)
     ipv.scatter(curves[:, 0], curves[:, 1], curves[:, 2], **kwargs)
Ejemplo n.º 12
0
def ipv_draw_point_cloud(ipv, pts, colors, pt_size=10):
    pts = pts.reshape((-1, 3))
    colors = colors.reshape((-1, 3))
    assert colors.shape[0] == pts.shape[0]
    ipv.scatter(x=pts[:, 0],
                y=pts[:, 1],
                z=pts[:, 2],
                color=colors.reshape(-1, 3),
                marker='sphere',
                size=pt_size)
Ejemplo n.º 13
0
def show_centerline(pred):
    pred[pred == 255] = 0
    mesh = np.meshgrid(*[range(pred.shape[i]) for i in range(1, 4)],
                       indexing='ij')
    cents = mesh + pred[1:]
    centdots = cents.transpose([1, 2, 3, 0])[pred[0] > 0]
    ipv.figure()
    ipv.scatter(centdots[:, 0], centdots[:, 1], centdots[:, 2], size=0.1)
    # ipv.volshow(pred[0])
    ipv.show()
def NACL(L_x, L_y=None, L_z=None, ColorNa='red', ColorCl='green'):
    if L_y == None:
        L_y = L_x
    if L_z == None:
        L_z = L_x
    if L_x > L_y:
        Max = L_x
    else:
        Max = L_y
    if L_z > Max:
        Max = L_z  #defined as a function highest of L_xyz
    #define a list of positions to append to
    Clx = []
    Cly = []
    Clz = []
    Nax = []
    Nay = []
    Naz = []
    #for each layer of the atom in the x direction. the *2-1 is so that L_x is the number of unit cells
    for O in range(L_x * 2 - 1):
        #for each layer in the y direction.
        for S in range(L_y * 2 - 1):
            #for each layer in the z direction.
            for A in range(L_z * 2 - 1):
                #if in this position there shoud be a Cl atom
                if (O + S + A) % 2 == 0:
                    #the 0.5 is becasue L_xyz was multiplied by 2
                    Clx.append(float(O * .5))
                    Cly.append(float(S * .5))
                    Clz.append(float(A * .5))
                #if there should be a Na atom
                elif (O + S + A) % 2 == 1:
                    Nax.append(float(O * .5))
                    Nay.append(float(S * .5))
                    Naz.append(float(A * .5))
                #if there should not be an atom
                #in theory this could be used to remove other atoms to make cubic or BCC structure
    #the x, y, z limits
    ipv.xyzlim(0, Max)
    #the color and size the Na and Cl atoms
    ipv.scatter(np.array(Clx),
                np.array(Cly),
                np.array(Clz),
                marker='sphere',
                size=6.5,
                color=ColorCl)
    ipv.scatter(
        np.array(Nax),
        np.array(Nay),
        np.array(Naz),
        marker='sphere',
        size=4,
        color=ColorNa,
    )
    ipv.show()
Ejemplo n.º 15
0
def ipv_plot_coils ( coil1, coil2, maxSamplesToPlot = 10000):
    assert( type(coil1) == np.ndarray and type(coil2) == np.ndarray)    
    maxSamplesToPlot = min( ( coil1.shape[0], maxSamplesToPlot ) )
    stride = np.max((1, coil1.shape[0]//maxSamplesToPlot))
    
    print( '\t plotting data - stride = {} '.format( stride ) )
    ipv.figure()
    ipv.scatter( coil1[::stride,0], coil1[::stride,1], coil1[::stride,2], size = .5, marker = 'sphere', color = 'lightgreen')
    ipv.scatter( coil2[::stride,0], coil2[::stride,1], coil2[::stride,2], size = .5, marker = 'sphere', color = 'purple')
    ipv.pylab.squarelim()
    ipv.show()
Ejemplo n.º 16
0
def ipv_plot_data(data, colorStack='purple', holdOnFlag=False, markerSize=.25):
    if not holdOnFlag:
        ipv.figure(
            width=600, height=600
        )  # create a new figure by default, otherwise append to existing
    ipv.scatter(data[:, 0],
                data[:, 1],
                data[:, 2],
                size=markerSize,
                marker='sphere',
                color=colorStack)
    if not holdOnFlag: ipv.show()
Ejemplo n.º 17
0
def initalize_hpo(nTimesteps,
                  nParticles,
                  nWorkers,
                  paramRanges,
                  nParameters=3,
                  plotFlag=True):
    accuracies = np.zeros((nTimesteps, nParticles))
    bestParticleIndex = {}

    globalBestParticleParams = np.zeros((nTimesteps, 1, nParameters))
    particles = np.zeros((nTimesteps, nParticles, nParameters))
    velocities = np.zeros((nTimesteps, nParticles, nParameters))
    particleBoostingRounds = np.zeros((nTimesteps, nParticles))

    # initial velocity is one
    velocities[0, :, :] = np.ones((nParticles, nParameters)) * .25

    # randomly initialize particle colors
    particleColors = np.random.uniform(size=(1, nParticles, 3))

    # best initialized to middle [ fictional particle ] -- is this necessary
    bestParticleIndex[0] = -1

    # grid initialize particles
    x = np.linspace(paramRanges[0][1], paramRanges[0][2], nWorkers)
    y = np.linspace(paramRanges[1][1], paramRanges[1][2], nWorkers)
    z = np.linspace(paramRanges[2][1], paramRanges[2][2], nWorkers)

    xx, yy, zz = np.meshgrid(x, y, z, indexing='xy')

    xS = xx.reshape(1, -1)[0]
    yS = yy.reshape(1, -1)[0]
    zS = zz.reshape(1, -1)[0]

    # clip middle particles
    particles[0, :, 0] = np.hstack([xS[-nWorkers**2:], xS[:nWorkers**2]])
    particles[0, :, 1] = np.hstack([yS[-nWorkers**2:], yS[:nWorkers**2]])
    particles[0, :, 2] = np.hstack([zS[-nWorkers**2:], zS[:nWorkers**2]])

    if plotFlag:
        ipv.figure()
        ipv.scatter(particles[0, :, 0],
                    particles[0, :, 1],
                    particles[0, :, 2],
                    marker='sphere',
                    color=particleColors)
        ipv.xlim(paramRanges[0][1], paramRanges[0][2])
        ipv.ylim(paramRanges[1][1], paramRanges[1][2])
        ipv.zlim(paramRanges[2][1], paramRanges[2][2])
        ipv.show()

    return particles, velocities, accuracies, bestParticleIndex, globalBestParticleParams, particleBoostingRounds, particleColors
Ejemplo n.º 18
0
def scatter_nd(xs: t.Tensor):
    xs = full_detach(xs)

    if xs.shape[1] == 1:
        plt.hist(xs[:, 0], bins=100)
    elif xs.shape[1] == 2:
        plt.scatter(*xs.T, s=.1)
    elif xs.shape[1] == 3:
        ipv.clear()
        ipv.scatter(*xs.T)
        ipv.show()
    else:
        assert False, f"Wrong dimensionality: {xs.shape=}"
Ejemplo n.º 19
0
    def ShowAnimation3D(self, size=15):
        ipv.figure()
        ipv.style.use("dark")

        x_Part = []
        y_Part = []
        z_Part = []

        for Part in self.Parts:
            temp_x = Part.x
            temp_y = Part.y
            temp_z = Part.z

            x_Part.append(temp_x)
            y_Part.append(temp_y)
            z_Part.append(temp_z)

        x = combine(self.speed * 5, *x_Part)
        y = combine(self.speed * 5, *y_Part)
        z = combine(self.speed * 5, *z_Part)

        u = ipv.scatter(x, y, z, marker="sphere", size=10, color="green")

        ipv.animation_control(u, interval=100)

        ipv.xyzlim(-size, size)
        ipv.show()
Ejemplo n.º 20
0
    def _my_ipv_vectorplot(xyz, uvw, N=10, length=1, **kwargs):
        """Generates a scatter plot of small points along a vector.

        Args:
            xyz: start point
            uvw: direction
            N: number of points rendered
            length: length of the line
            **kwargs: additional arguments of ipv.scatter
        """
        points = []
        for x in np.linspace(0, length, N):
            tmp = xyz + uvw * x
            points.append(tmp)
        points = np.concatenate(points, axis=0)
        ipv.scatter(points[:, 0], points[:, 1], points[:, 2], **kwargs)
Ejemplo n.º 21
0
def spherical_galaxy_orbit(orbit_x,
                           orbit_y,
                           orbit_z,
                           N_stars=100,
                           sigma_r=1,
                           orbit_visible=False,
                           orbit_line_interpolate=5,
                           N_star_orbits=10,
                           color=[255, 220, 200],
                           size_star=1,
                           scatter_kwargs={}):
    """Create a fake galaxy around the points orbit_x/y/z with N_stars around it"""
    if orbit_line_interpolate > 1:
        x = np.linspace(0, 1, len(orbit_x))
        x_smooth = np.linspace(0, 1, len(orbit_x) * orbit_line_interpolate)
        kind = 'quadratic'
        orbit_x_line = scipy.interpolate.interp1d(x, orbit_x, kind)(x_smooth)
        orbit_y_line = scipy.interpolate.interp1d(x, orbit_y, kind)(x_smooth)
        orbit_z_line = scipy.interpolate.interp1d(x, orbit_z, kind)(x_smooth)
    else:
        orbit_x_line = orbit_x
        orbit_y_line = orbit_y
        orbit_z_line = orbit_z
    line = ipv.plot(orbit_x_line,
                    orbit_y_line,
                    orbit_z_line,
                    visible=orbit_visible)
    x = np.repeat(orbit_x, N_stars).reshape((-1, N_stars))
    y = np.repeat(orbit_y, N_stars).reshape((-1, N_stars))
    z = np.repeat(orbit_z, N_stars).reshape((-1, N_stars))
    xr, yr, zr = np.random.normal(0, scale=sigma_r, size=(3, N_stars))  # +
    r = np.sqrt(xr**2 + yr**2 + zr**2)

    for i in range(N_stars):
        a = np.linspace(0, 1, x.shape[0]) * 2 * np.pi * N_star_orbits
        xo = r[i] * np.sin(a)
        yo = r[i] * np.cos(a)
        zo = a * 0
        xo, yo, zo = np.dot(_randomSO3(), [xo, yo, zo])
        #print(x.shape, xo.shape)
        x[:, i] += xo
        y[:, i] += yo
        z[:, i] += zo

    sprite = ipv.scatter(x,
                         y,
                         z,
                         texture=radial_sprite((64, 64), color),
                         marker='square_2d',
                         size=size_star,
                         **scatter_kwargs)
    with sprite.material.hold_sync():
        sprite.material.blending = pythreejs.BlendingMode.CustomBlending
        sprite.material.blendSrc = pythreejs.BlendFactors.SrcColorFactor
        sprite.material.blendDst = pythreejs.BlendFactors.OneFactor
        sprite.material.blendEquation = 'AddEquation'
        sprite.material.transparent = True
        sprite.material.depthWrite = False
        sprite.material.alphaTest = 0.1
    return sprite, line
Ejemplo n.º 22
0
def ipv_animate(particles, velocities, particleColors, particleSizes,
                paramRanges):

    nTimesteps = particles.shape[0]
    nParticles = particles.shape[1]

    # determine quiver sizes and colors
    veloQuiverSizes = np.zeros((nTimesteps, nParticles, 1))
    for iTimestep in range(nTimesteps):
        veloQuiverSizes[iTimestep, :,
                        0] = np.linalg.norm(velocities[iTimestep, :, :],
                                            axis=1)
    veloQuiverSizes = np.clip(veloQuiverSizes, 0, 2)
    quiverColors = np.ones(
        (nTimesteps, nParticles, 4)) * .8  #veloQuiverSizes/3

    ipv.figure()
    #bPlots = ipv.scatter( best[:, :, 0],  best[:, :, 1],  best[:, :, 2], marker = 'sphere', size=2, color = 'red' )
    pPlots = ipv.scatter(particles[:, :, 0],
                         particles[:, :, 1],
                         particles[:, :, 2],
                         marker='sphere',
                         size=particleSizes,
                         color=particleColors)
    #qvPlots = ipv.quiver( particles[:, :, 0], particles[:, :, 1], particles[:, :, 2], velocities[:, :, 0], velocities[:, :, 1], velocities[:, :, 2], size=veloQuiverSizes[:,:,0]*3, color=quiverColors)

    ipv.animation_control([pPlots], interval=600)
    ipv.xlim(paramRanges[0][1], paramRanges[0][2])
    ipv.ylim(paramRanges[1][1], paramRanges[1][2])
    ipv.zlim(paramRanges[2][1], paramRanges[2][2])

    ipv.show()
Ejemplo n.º 23
0
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')
Ejemplo n.º 24
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))
Ejemplo n.º 25
0
def gaussian(N=1000, draw=True, show=True, seed=42, color=None, marker='sphere'):
    """Show N random gaussian distributed points using a scatter plot"""
    import ipyvolume as ipv
    rng = np.random.RandomState(seed)
    x, y, z = rng.normal(size=(3, N))

    if draw:
        if color:
            mesh = ipv.scatter(x, y, z, marker=marker, color=color)
        else:
            mesh = ipv.scatter(x, y, z, marker=marker)
        if show:
            #ipv.squarelim()
            ipv.show()
        return mesh
    else:
        return x, y, z
Ejemplo n.º 26
0
def stars(N=1000, radius=100000, thickness=3, seed=42, color=[255, 240, 240]):
    import ipyvolume as ipv
    rng = np.random.RandomState(seed)
    x, y, z = rng.normal(size=(3, N))
    r = np.sqrt(x**2 + y**2 + z**2)/(radius + thickness * radius * np.random.random(N))
    x /= r
    y /= r
    z /= r
    return ipv.scatter(x, y, z, texture=radial_sprite((64, 64), color), marker='square_2d', grow_limits=False, size=radius*0.7/100)
Ejemplo n.º 27
0
def test_ipyvolume():
    import ipyvolume as ipv

    s = 1 / 2**0.5
    # 4 vertices for the tetrahedron
    x = np.array([1., -1, 0, 0])
    y = np.array([0, 0, 1., -1])
    z = np.array([-s, -s, s, s])
    # and 4 surfaces (triangles), where the number refer to the vertex index
    triangles = [(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 3, 2)]

    ipv.figure()
    # draw the tetrahedron mesh
    ipv.plot_trisurf(x, y, z, triangles=triangles, color='orange')
    # mark the vertices
    ipv.scatter(x, y, z, marker='sphere', color='blue')
    # set limits and show
    ipv.xyzlim(-2, 2)
    ipv.show()
Ejemplo n.º 28
0
def ipv_plot_plydata(plydata, sample_frac=1, marker='circle_2d', **kwargs):
    """Plot vertices in a plydata object using ipyvolume."""
    if sample_frac < 1:
        xyz = random_sample(plydata['vertex'], plydata['vertex'].count,
                            sample_frac)
    else:
        xyz = dict(x=plydata['vertex']['x'],
                   y=plydata['vertex']['y'],
                   z=plydata['vertex']['z'])
    fig = ipv.scatter(**xyz, marker=marker, **kwargs)
    return fig
Ejemplo n.º 29
0
def show_patient_3d(src_dir, patient_name):
    filepath = 'data/' + patient_name + '-mask.npy'
    mask = np.load(filepath)
    fig = ipv.figure()
    colors = ['red', 'green', 'blue']
    n_organs = 3
    contours = {}
    for organ_num in range(n_organs):
        contours = mask2contours(mask[:,:,:,organ_num])
        coord = np.argwhere(contours)
        n_points = coord.shape[0]
        x, y, z = np.random.normal(0,100,(3,n_points))
        for i in range(n_points):
            x[i] = coord[i,0]
            y[i] = coord[i,1]
            z[i] = coord[i,2]
        if n_points>0:
            scatter = ipv.scatter(x, y, z, size=1, marker='sphere', color=colors[organ_num])
    ipv.show()
    
    if src_dir != None:
        prediction = np.load(src_dir + '/predictions/' + patient_name + '_prediction.npy')
        prediction_thr = np.argmax(prediction, axis=-1)
        
        fig = ipv.figure()
        colors = ['magenta', 'lime', 'cyan']
        n_organs = 3
        contours = {}
        for organ_num in range(n_organs):
            mask = (prediction_thr==organ_num)
            contours = mask2contours(mask)
            coord = np.argwhere(contours)
            n_points = coord.shape[0]
            x, y, z = np.random.normal(0,100,(3,n_points))
            for i in range(n_points):
                x[i] = coord[i,0]
                y[i] = coord[i,1]
                z[i] = coord[i,2]
            if n_points>0:
                scatter = ipv.scatter(x, y, z, size=1, marker='sphere', color=colors[organ_num])
        ipv.show()
def SC(L_x, L_y, L_z, Color='red'):
    Ax = []
    Ay = []
    Az = []
    for O in range(L_x):
        #for each layer in the y direction.
        for S in range(L_y):
            #for each layer in the z direction.
            for A in range(L_z):
                Ax.append(float(O))
                Ay.append(float(S))
                Az.append(float(A))
    #the x, y, z limits
    ipv.xyzlim(0, 10)  #define as a function highest of L_xyz
    ipv.scatter(np.array(Ax),
                np.array(Ay),
                np.array(Az),
                marker='sphere',
                size=6.5,
                color=Color)
    ipv.show()