Exemple #1
0
def sphere_scatter3d(writer, data, output, meta, tag='sphere'):
    data = norm_range(data)
    out = output[0].cpu().detach().clone()
    out0 = out[0][0:3]
    out1 = out[1][0:3]

    stride = data.shape[2] // out.shape[2]

    im0 = data[0][:, ::stride, ::stride]
    x0 = out0[0].reshape(-1)
    y0 = out0[1].reshape(-1)
    z0 = out0[2].reshape(-1)
    c0 = im0.permute(1, 2, 0).reshape(-1, 3)

    im1 = data[1][:, ::stride, ::stride]
    x1 = out1[0].reshape(-1)
    y1 = out1[1].reshape(-1)
    z1 = out1[2].reshape(-1)
    c1 = im1.permute(1, 2, 0).reshape(-1, 3)

    axmin = np.round(out.min())
    axmax = np.round(out.max())

    fig = plt.figure()
    ax = mplot3d.Axes3D(fig)
    ax.set_xlim(axmin, axmax)
    ax.set_ylim(axmin, axmax)
    ax.set_zlim(axmin, axmax)
    ax.scatter3D(x0,
                 y0,
                 z0,
                 c=c0.numpy(),
                 s=40,
                 linewidths=0,
                 depthshade=False)
    writer.add_figure(tag + '/0', fig)

    fig = plt.figure()
    ax = mplot3d.Axes3D(fig)
    ax.set_xlim(axmin, axmax)
    ax.set_ylim(axmin, axmax)
    ax.set_zlim(axmin, axmax)
    ax.scatter3D(x1,
                 y1,
                 z1,
                 c=c1.numpy(),
                 s=40,
                 linewidths=0,
                 depthshade=False)
    writer.add_figure(tag + '/1', fig)
Exemple #2
0
def plot_mesh(points, tris, centroids, normals, quivers=False):
    fig = plt.figure(figsize=(8, 8))
    ax = mplot3d.Axes3D(fig)

    if quivers:
        x, y, z = centroids
        u, v, w = normals.T
        ax.quiver(x, y, z, u, v, w, length=0.2, normalize=True)

    meshvectors = mesh_vectors(points, tris)
    ax.add_collection3d(
        mplot3d.art3d.Poly3DCollection(meshvectors,
                                       facecolor=[0.5, 0.5, 0.5],
                                       lw=0.5,
                                       edgecolor=[0, 0, 0],
                                       alpha=.8,
                                       antialiaseds=True))
    scale = points.flatten('F')
    ax.auto_scale_xyz(scale, scale, scale)

    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    plt.show()
    return fig
Exemple #3
0
def visualize(pymesh_mesh=None, save_path=None):
    # Create a new plot
    figure = plt.figure()
    axes = mplot3d.Axes3D(figure)

    from stl import mesh as npmesh

    def convert_pymesh_to_npmesh(pymesh_mesh):
        vertices = pymesh_mesh.vertices
        faces = pymesh_mesh.faces

        mesh_np = npmesh.Mesh(np.zeros(faces.shape[0],
                                       dtype=npmesh.Mesh.dtype))
        for count, face in enumerate(faces):
            for axis in range(3):
                mesh_np.vectors[count][axis] = vertices[face[axis], :]
        return mesh_np

    # Load the STL files and add the vectors to the plot
    your_mesh = convert_pymesh_to_npmesh(pymesh_mesh)
    axes.add_collection3d(mplot3d.art3d.Poly3DCollection(your_mesh.vectors))

    # Auto scale to the mesh size
    scale = your_mesh.points.flatten(-1)
    axes.auto_scale_xyz(scale, scale, scale)

    axes.view_init(0, -180)

    # Save plot as name 'path'
    plt.savefig(save_path)
    return
 def generateAxes(self):
     '''
     Produces axes for plotting surfaces and paths
     '''
     self.fig = pyplot.figure()
     axes = mplot3d.Axes3D(self.fig)
     return axes
Exemple #5
0
def plot_meshes(mesh_list=[], point_list=[], points_new_list=[]):
    # Optionally render the rotated cube faces
    import matplotlib.pyplot as plt
    from mpl_toolkits import mplot3d
    # Create a new plot
    figure = plt.figure()
    axes = mplot3d.Axes3D(figure)
    # Render the cube
    color_list = ['r', 'b', 'g']
    for counter, mesh in enumerate(mesh_list):
        poly_3d = mplot3d.art3d.Poly3DCollection(mesh.vectors)
        axes.add_collection3d(poly_3d)
        poly_3d.set_facecolor(color_list[counter])

    for point in point_list:
        axes.scatter([point[0]], [point[1]], [point[2]],
                     c=[1, 0, 0],
                     alpha=0.5)

    for point in points_new_list:
        axes.scatter([point[0]], [point[1]], [point[2]], c=[0, 1, 0], alpha=1)

    # Auto scale to the mesh size
    if len(mesh_list) > 0:
        scale = mesh.points.flatten(-1)
        axes.auto_scale_xyz(scale, scale, scale)
    plt.xlabel('x')
    plt.ylabel('y')
    # Show the plot to the screen
    plt.show()
Exemple #6
0
def draw_mesh(meshname, mesh, refinement):
    fig = plt.figure(figsize=(6, 6), frameon=False)
    ax = mplot3d.Axes3D(fig)

    # Collect face data as vectors for plotting
    F = boundary_faces(tetramesh.elements)

    facevectors = np.zeros((F.shape[0], 3, 3))
    for i, face in enumerate(F):
        for j in range(3):
            facevectors[i][j] = tetramesh.vertices[face[j], :]
    ax.add_collection3d(
        mplot3d.art3d.Poly3DCollection(facevectors,
                                       facecolor=[0.5, 0.5, 0.5],
                                       lw=0.5,
                                       edgecolor=[0, 0, 0],
                                       alpha=0.66))

    scale = tetramesh.vertices.flatten()
    ax.auto_scale_xyz(scale, scale, scale)

    plt.setp(ax.get_xticklabels(), visible=False)
    plt.setp(ax.get_yticklabels(), visible=False)
    plt.setp(ax.get_zticklabels(), visible=False)

    plt.savefig(meshname)
    return
Exemple #7
0
    def createWorkspaceConvexHull(self):

        # Load the numpy array of sampled workspace end effector points
        print("Loading numpy array {}{}".format(self.directory,
                                                self.workspaceFilename))
        points = np.load(self.directory + self.workspaceFilename)

        print(points.shape)

        # Calculate the complex hull!
        hull = ConvexHull(points)

        # create the figure

        #         fig_workspace = plt.figure()

        #         #add an axis
        #         ax = fig_workspace.add_subplot(111, projection='3d')
        rows, cols = hull.simplices.shape

        # Plot surface traingulation
        simplical_facet_corners = []

        for counter, simplex in enumerate(hull.simplices):
            simplical_facet_corners.append([
                points[simplex[0], :], points[simplex[1], :],
                points[simplex[2], :]
            ])

        # Define directory to save convex hull
        self.directory = '/data'
        self.convexHullFilename = '/EEZYbotARM_workspace/workspace_convexHull.p'

        with open(self.directory + self.convexHullFilename, 'wb') as fp:
            pickle.dump(simplical_facet_corners, fp)

        # Plotting preperation
        ax = a3.Axes3D(pl.figure())
        # facetCol = sp.rand(3) #[0.0, 1.0, 0.0]
        facetCol = [0.5, 0.8, 0.4]
        lineCol = [0.8, 0.8, 0.8, 0.5]

        # Plot surface traingulation
        for simplex in hull.simplices:
            vtx = [
                points[simplex[0], :], points[simplex[1], :],
                points[simplex[2], :]
            ]
            tri = a3.art3d.Poly3DCollection([vtx], linewidths=1, alpha=0.4)
            tri.set_color(facetCol)
            tri.set_edgecolor(lineCol)
            ax.add_collection3d(tri)

        # Set limits for plot
        ax.set_xlim([-350, 350])
        ax.set_ylim([-350, 350])
        ax.set_zlim([-350, 350])

        # plt.axis('off')
        plt.show()
Exemple #8
0
def draw_3D_vertices(vertices, surfaces=None, surf_color=None, ax=None):

    if ax is None:
        fig = plt.figure()
        ax = plt3.Axes3D(fig)

    if surfaces is None:
        surfaces = [range(len(vertices))]

    for i, surf in enumerate(surfaces):
        tri = plt3.art3d.Poly3DCollection(vertices[surf])

        if surf_color is None:
            face_color = np.random.rand(3)
        else:
            face_color = surf_color[i]

        tri.set_facecolor(face_color)
        tri.set_edgecolor('k')
        ax.add_collection3d(tri)

    x = np.concatenate(vertices[:, :, 0])
    y = np.concatenate(vertices[:, :, 1])
    z = np.concatenate(vertices[:, :, 2])

    set_limits_3D(ax, x, y, z)

    plt.show()
    return ax
Exemple #9
0
def show_stl_file():
    """
    STL is a file format native to the stereolithography CAD software created by 3D Systems.
    """
    from stl import mesh
    from mpl_toolkits import mplot3d
    from matplotlib import pyplot

    # Create a new plot
    figure = pyplot.figure()
    axes = mplot3d.Axes3D(figure)

    # Load the STL files and add the vectors to the plot
    your_mesh = mesh.Mesh.from_file('coke.stl')
    axes.add_collection3d(mplot3d.art3d.Poly3DCollection(your_mesh.vectors))

    # Auto scale to the mesh size
    scale = your_mesh.points.flatten(-1)
    axes.auto_scale_xyz(scale, scale, scale)

    # volume, cog, inertia = your_mesh.get_mass_properties()
    # print("Volume                                  = {0}".format(volume))
    # print("Position of the center of gravity (COG) = {0}".format(cog))
    # print("Inertia matrix at expressed at the COG  = {0}".format(inertia[0,:]))
    # print("                                          {0}".format(inertia[1,:]))
    # print("                                          {0}".format(inertia[2,:]))

    # Show the plot to the screen
    pyplot.show()
def plot_bad_edges(mesh, bad_indices):
    # Create a new plot
    figure = pyplot.figure()
    axes = mplot3d.Axes3D(figure)

    good_ones = np.delete(mesh.vectors, bad_indices, 0)
    bad_ones = []
    for i in bad_indices:
        bad_ones.append(mesh.vectors[i])
    bad_ones = np.asarray(bad_ones)

    mesh_collection_good = mplot3d.art3d.Poly3DCollection(good_ones)
    mesh_collection_good.set_facecolor((0, 1, 1))
    mesh_collection_good.set_edgecolor((0, 0, 1))
    axes.add_collection3d(mesh_collection_good)

    mesh_collection_bad = mplot3d.art3d.Poly3DCollection(bad_ones)
    mesh_collection_bad.set_facecolor((1, 1, 0))
    mesh_collection_bad.set_edgecolor((1, 0, 0))
    axes.add_collection3d(mesh_collection_bad)

    # Auto scale to the mesh size
    scale = mesh.points.flatten(-1)
    axes.auto_scale_xyz(scale, scale, scale)

    # Show the plot to the screen
    pyplot.show()
Exemple #11
0
def main():
    make_blobs(n_samples=10, centers=3, n_features=3, random_state=0)

    P = 10 * PSD()
    a = np.random.multivariate_normal([0, 0, 0], P, 100)
    np.save('aP', P)
    np.save('a', a)
    print(P)

    P = 10 * PSD()
    b = np.random.multivariate_normal([10, 10, 10], P, 100)
    np.save('bP', P)
    np.save('b', b)
    print(P)

    P = 10 * PSD()
    c = np.random.multivariate_normal([-10, -10, 10], P, 100)
    np.save('cP', P)
    np.save('c', c)
    print(P)

    figure = plt.figure()
    axis = mplot3d.Axes3D(figure)
    axis.scatter(a[:, 0], a[:, 1], a[:, 2], marker='+')
    axis.scatter(b[:, 0], b[:, 1], b[:, 2], marker='o')
    axis.scatter(c[:, 0], c[:, 1], c[:, 2], marker='*')

    plt.show()
Exemple #12
0
    def plot2(self, img, index=2, fourierlines=False, title="none"):
        """For testing purposes"""
        import matplotlib.pyplot as plt

        fig = plt.figure(index)
        if 0:
            import mpl_toolkits.mplot3d as p3

            ax = p3.Axes3D(fig)
            yy, xx = np.indices(img.shape)
            ax.plot_surface(yy, xx, img)
        else:
            ax = fig.add_subplot(111)

            if img.size in img.shape:
                x = ft.fftfreq(len(img), 1, centered=True)
                ax.plot(x, img)
            else:
                ax.imshow(img, origin="lower", interpolation="nearest")
                if fourierlines:
                    s = np.asarray(img.shape)
                    fmin, fmax = ft.fft_freqind(s)
                    cen = -fmin
                    ax.plot([cen[1], cen[1]], [0, s[0] - 1])
                    ax.plot([0, s[1] - 1], [cen[0], cen[0]])

        plt.title(title)
        plt.pause(0.1)
        raw_input("press enter...")
Exemple #13
0
def surface():
    "show a nice 3d plot just for demo purposes"
    prob = FesProblem()
    steps = (15, 15)
    lower = (0.0, 0.0)
    upper = (1.0, 1.0)
    domain = [np.linspace(l, u, s) for s, l, u in zip(steps, lower, upper)]

    X = domain[0]
    Y = domain[1]

    L = [len(d) for d in domain]
    s = []
    e = 1
    for d in domain:
        L = L[1:]
        LS = np.prod(L)
        s.append(np.repeat(d.tolist() * LS, e))
        if len(L) > 0:
            e = e * L[0]

    z = np.array([prob.objfun(x) for x in np.array(s).T]).T[1]
    z = np.reshape(z, steps)

    fig = plt.figure()
    ax = mpl.Axes3D(fig)  # fig.add_subplot(111,projection='3d')
    ax.plot_surface(X, Y, z, rstride=1, cstride=1, cmap=cm.jet, linewidth=0)
    plt.show()
Exemple #14
0
def plot_3d(x, y, p, label='$z$', elev=30.0, azim=45.0):
    """
    Creates a Matplotlib figure with a 3D surface plot of the scalar field p.

    Parameters
    ----------
    x : numpy.ndarray
        Gridline locations in the x direction as a 1D array of floats.
    y : numpy.ndarray
        Gridline locations in the y direction as a 1D array of floats.
    p : numpy.ndarray
        Scalar field to plot as a 2D array of floats.
    label : string, optional
        Axis label to use in the third direction;
        default: 'z'.
    elev : float, optional
        Elevation angle in the z plane;
        default: 30.0.
    azim : float, optional
        Azimuth angle in the x,y plane;
        default: 45.0.
    """
    fig = pyplot.figure(figsize=(8.0, 6.0))
    ax = mplot3d.Axes3D(fig)
    ax.set_xlabel('$x$')
    ax.set_ylabel('$y$')
    ax.set_zlabel(label)
    X, Y = numpy.meshgrid(x, y)
    ax.plot_surface(X, Y, p, cmap=cm.viridis)
    ax.set_xlim(x[0], x[-1])
    ax.set_ylim(y[0], y[-1])
    ax.view_init(elev=elev, azim=azim)
Exemple #15
0
def draw_mesh(mesh):
    fig = plt.figure(figsize=(6, 6), frameon=False)
    ax = mplot3d.Axes3D(fig)

    # Collect face data as vectors for plotting
    F = mesh.elements
    P = mesh.nodes
    T = mesh.elements
    facevectors = np.zeros((F.shape[0], 3, 3))
    for i, face in enumerate(F):
        for j in range(3):
            facevectors[i][j] = mesh.vertices[face[j], :]
    ax.add_collection3d(
        mplot3d.art3d.Poly3DCollection(facevectors,
                                       facecolor=[0.5, 0.5, 0.5],
                                       lw=0.5,
                                       edgecolor=[0, 0, 0],
                                       alpha=0.66))

    scale = mesh.vertices.flatten()

    I = trimesh.Trimesh(vertices=P, faces=T, process=False).moment_inertia

    Ip, Q = trimesh.inertia.principal_axis(I)

    ax.quiver(0, 0, 0, Q[2, 0], Q[2, 1], Q[2, 2], length=20, normalize=False)
    ax.quiver(15, 10, -10, 0, 0, 20, length=1, normalize=False, color='k')
    ax.auto_scale_xyz(scale, scale, scale)

    plt.show()
    return fig
Exemple #16
0
    def __init__(self, **kwargs):
        self.file_name = kwargs.pop('file_name', None)
        multi_body = np.array(kwargs.pop('multi_body', False))
        self.debug = kwargs.pop('debug', False)

        if (multi_body and self.file_name is not None):
            self.read_geometry_file()
            sec_time = timer.time()
            print('Processing Geometries...')
            sys.stdout.flush()
            self.isol_geom()
            print('Done ', timer.time() - sec_time, 'sec')
            print(np.size(self.objects, 0), 'solids identified')

            if (self.debug):
                # debugging plot
                figure = plt.figure()
                axes = mplot3d.Axes3D(figure)

                for object_mesh in self.objects:
                    axes.add_collection3d(
                        mplot3d.art3d.Poly3DCollection(object_mesh))

                scale = self.object_mesh.points.flatten(-1)
                axes.set_aspect('equal')
                axes.set_xlabel('x')
                axes.set_ylabel('y')
                axes.set_zlabel('z')
                axes.auto_scale_xyz(scale, scale, scale)
                plt.show()
    def line3Dregress(self, x, y, z, show=False):
        data = np.concatenate(
            (x[:, np.newaxis], y[:, np.newaxis], z[:, np.newaxis]), axis=1)
        datamean = data.mean(axis=0)
        uu, dd, vv = np.linalg.svd(data - datamean)

        x0, y0, z0 = vv[0]
        v = np.array((z0, z0 * y0 / x0, -x0 - y0 * y0 / x0))
        v /= np.linalg.norm(v)

        if show:
            linepts = vv[0] * np.mgrid[-7:7:2j][:, np.newaxis]
            linepts += datamean

            linepts1 = v * np.mgrid[-7:7:2j][:, np.newaxis]
            linepts1 += datamean

            import matplotlib.pyplot as plt
            import mpl_toolkits.mplot3d as m3d
            ax = m3d.Axes3D(plt.figure())
            ax.scatter3D(*data.T)
            ax.plot3D(*linepts.T)
            ax.plot3D(*linepts1.T)
            plt.show()
        return v
Exemple #18
0
    def plot(self, plot_file=None, save_fig=False):
        """
		Method to plot an stl file. If `plot_file` is not given it plots `self.infile`.

		:param string plot_file: the stl filename you want to plot.
		:param bool save_fig: a flag to save the figure in png or not. If True the
			plot is not shown.
		"""
        if plot_file is None:
            plot_file = self.infile
        else:
            self._check_filename_type(plot_file)

        # Create a new plot
        figure = pyplot.figure()
        axes = mplot3d.Axes3D(figure)

        # Load the STL files and add the vectors to the plot
        stl_mesh = mesh.Mesh.from_file(plot_file)
        axes.add_collection3d(mplot3d.art3d.Poly3DCollection(stl_mesh.vectors))

        # Auto scale to the mesh size
        scale = stl_mesh.points.flatten(-1)
        axes.auto_scale_xyz(scale, scale, scale)

        # Show the plot to the screen
        if not save_fig:
            pyplot.show()
        else:
            figure.savefig(plot_file.split('.')[0] + '.png')
def plotSurf(surf, points):
    ax = a3.Axes3D(pl.figure())

    for t in surf:
        vtx = t.getTri()
        print vtx
        tri = a3.art3d.Poly3DCollection([vtx])
        tri.set_color(colors.rgb2hex(np.random.rand(3)))
        tri.set_edgecolor('k')
        ax.add_collection3d(tri)

    x = []
    y = []
    z = []
    for p in points:
        x.append(p[0])
        y.append(p[1])
        z.append(p[2])

    ax.scatter(x, y, z)
    ax.set_xlim(0, 1)
    ax.set_ylim(0, 1)
    ax.set_zlim(0, 1)

    pl.show()

    del (x)
    del (y)
    del (z)
Exemple #20
0
def findlongaxis(r):
    a = r.mean(axis=0)
    uu, dd, vv = np.linalg.svd(r - a)
    # Now vv[0] contains the first principal component, i.e. the direction
    # vector of the 'best fit' line in the least squares sense.

    # Now generate some points along this best fit line, for plotting.

    # I use -7, 7 since the spread of the data is roughly 14
    # and we want it to have mean 0 (like the points we did
    # the svd on). Also, it's a straight line, so we only need 2 points.
    linepts = vv[0] * np.mgrid[-7:7:2j][:, np.newaxis]

    # shift by the mean to get the line in the right place
    linepts += a

    # Verify that everything looks right.

    longaxis = np.vstack((a, a + vv[0, :] * 10))
    import matplotlib.pyplot as plt
    import mpl_toolkits.mplot3d as m3d
    if 0:
        ax = m3d.Axes3D(plt.figure())
        ax.scatter3D(*r.T)
        ax.plot3D(*linepts.T)
        plt.show()

    return longaxis
Exemple #21
0
    def plot(self, plot_file=None, save_fig=False):
        """
		Method to plot a file. If `plot_file` is not given it plots `self.shape`.

		:param string plot_file: the filename you want to plot.
		:param bool save_fig: a flag to save the figure in png or not. If True the
			plot is not shown.

		:return: figure: matlplotlib structure for the figure of the chosen geometry
		:rtype: matplotlib.pyplot.figure
		"""
        if plot_file is None:
            shape = self.shape
            plot_file = self.infile
        else:
            shape = self.load_shape_from_file(plot_file)

        stl_writer = StlAPI_Writer()
        # Do not switch SetASCIIMode() from False to True.
        stl_writer.SetASCIIMode(False)
        stl_writer.Write(shape, 'aux_figure.stl')

        # Create a new plot
        figure = pyplot.figure()
        axes = mplot3d.Axes3D(figure)

        # Load the STL files and add the vectors to the plot
        stl_mesh = mesh.Mesh.from_file('aux_figure.stl')
        os.remove('aux_figure.stl')
        axes.add_collection3d(
            mplot3d.art3d.Poly3DCollection(stl_mesh.vectors / 1000))

        # Get the limits of the axis and center the geometry
        max_dim = np.array([\
         np.max(stl_mesh.vectors[:, :, 0]) / 1000,\
         np.max(stl_mesh.vectors[:, :, 1]) / 1000,\
         np.max(stl_mesh.vectors[:, :, 2]) / 1000])
        min_dim = np.array([\
         np.min(stl_mesh.vectors[:, :, 0]) / 1000,\
         np.min(stl_mesh.vectors[:, :, 1]) / 1000,\
         np.min(stl_mesh.vectors[:, :, 2]) / 1000])

        max_lenght = np.max(max_dim - min_dim)
        axes.set_xlim(\
         -.6 * max_lenght + (max_dim[0] + min_dim[0]) / 2,\
         .6 * max_lenght + (max_dim[0] + min_dim[0]) / 2)
        axes.set_ylim(\
         -.6 * max_lenght + (max_dim[1] + min_dim[1]) / 2,\
         .6 * max_lenght + (max_dim[1] + min_dim[1]) / 2)
        axes.set_zlim(\
         -.6 * max_lenght + (max_dim[2] + min_dim[2]) / 2,\
         .6 * max_lenght + (max_dim[2] + min_dim[2]) / 2)

        # Show the plot to the screen
        if not save_fig:
            pyplot.show()
        else:
            figure.savefig(plot_file.split('.')[0] + '.png')

        return figure
def plotMesh(mesh, points=None):
    # Create a new plot
    figure = pyplot.figure()
    axes = mplot3d.Axes3D(figure)

    toPlot = stlmesh.Mesh(
        np.zeros(mesh.faces.shape[0], dtype=stlmesh.Mesh.dtype))
    for i, f in enumerate(mesh.faces):
        for j in range(3):
            toPlot.vectors[i][j] = mesh.vertices[f[j], :]

    axes.add_collection3d(mplot3d.art3d.Poly3DCollection(toPlot.vectors))

    if not (points is None) and points.any():
        axes.scatter3D(points[:, 0],
                       points[:, 1],
                       zs=points[:, 2],
                       c='r',
                       s=20)
    # Auto scale to the mesh size
    scale = toPlot.points.flatten(-1)
    axes.auto_scale_xyz(scale, scale, scale)

    # Show the plot to the screen
    pyplot.show()
Exemple #23
0
def chull_plot_3d(chull, faces, ax=None, **kwargs):
    """
    Plot the given faces that define a convex hull in 3-D. 
    
    Parameters
    ----------
    chull : scipy.spatial.ConvexHull instance
        Original convex hull that we want to plot in 3-D.
    faces : pycoverage3d.visutils.Geom.PlanarFace instance
        Faces that define a convex hull in 3-D.
    ax : matplotlib.axes.Axes instance, optional
        Axes to plot on, by default None.

    Returns
    -------
    fig : matplotlib.figure.Figure instance
        Figure corresponding to the plot.
    
    See Also
    --------
    pycoverge3d.visutils.Geom.PlanarFace : PlanarFace class used to compute the faces.

    Notes
    -----
    Requires matplotlib and mpl_toolkits.
   
    """
    ax = mplt.Axes3D(plt.figure())

    pc = mplt.art3d.Poly3DCollection(faces, **kwargs)
    ax.add_collection3d(pc)

    adjust_bounds(ax, chull.points)

    return ax.figure
def affichage_fichier_stl(lien) :


    figure= pyplot.figure()
    axes=mplot3d.Axes3D(figure)

    fichier=mesh.Mesh.from_file(lien)
    a=(fichier.vectors)
    normale=(fichier.normals)

    normale[7][0]=1  #Vecteur normal du fichié V dans le mauvais sens des x


    #print(a[1])
    # print(len(a))
    # print(CalculForce(a,normale,0))   #Dans l'outil fichier
    # print(CalculForce(a,normale,-2))
    # print(CalculForce(a,normale,-0.5))


    """baisser la présicion"""

    #print('milieu ',Dichotomie(0,-4,0.0000001))
    #print(CalculForce(a,normale,Dichotomie(0,-4,0.0000001)))

    """Problème pour le fichier Mini_650 te V avec les vecteurs normaux"""
    outil.translation(2,a,(outil.Dichotomie(400,-400,0.00001,a,normale,Rho=1000,masse=346618700000,potentiometre=0))[0])
    axes.add_collection3d(mplot3d.art3d.Poly3DCollection(fichier.vectors))
    scale = fichier.points.flatten()
    axes.auto_scale_xyz(scale, scale, scale)

    pyplot.show()
    def start_simulation(self):
        self.setFixedSize(1000, 500)

        self.button_1.hide()

        self.button_2 = QPushButton("Exit")
        self.layout.addWidget(self.button_2, 8, 8, 1, 1)
        self.button_2.clicked.connect(self.exit)

        #Graphique
        self.fig2 = plt.figure()
        self.graph = FigureCanvas(self.fig2)
        plt.plot([1, 2, 3, 4])
        plt.xlabel('Calcul de la position du tirant d\'eau')
        self.graph.draw()
        self.layout.addWidget(self.graph, 2, 5, 4, 4)

        #Figure 3D
        self.fig = plt.figure()
        self.canvas = FigureCanvas(self.fig)
        axes = mplot3d.Axes3D(self.fig)
        your_mesh = mesh.Mesh.from_file(self.coque)
        axes.add_collection3d(mplot3d.art3d.Poly3DCollection(
            your_mesh.vectors))
        scale = your_mesh.points.flatten("C")
        axes.auto_scale_xyz(scale, scale, scale)
        self.canvas.draw()
        self.layout.addWidget(self.canvas, 2, 0, 4, 4)
Exemple #26
0
 def plot_panels(self,
                 X_str,
                 elev=25,
                 azim=-160,
                 edge_color='k',
                 fill_color=1,
                 transp=0.2,
                 ax=None):
     m, n, bp = self.m, self.n, self.bp
     X_coord = self.X if X_str == 'X' else self.XV
     X = X_coord[:, :, :, 0]
     Y = X_coord[:, :, :, 1]
     Z = X_coord[:, :, :, 2]
     new_ax = not ax
     if new_ax:
         ax = a3.Axes3D(plt.figure())
     for i in range(m):
         for j in range(n):
             vtx = np.array([X[i, j], Y[i, j], Z[i, j]]).T
             panel = a3.art3d.Poly3DCollection([vtx])
             panel.set_facecolor((0, 0, fill_color, transp))
             panel.set_edgecolor(edge_color)
             ax.add_collection3d(panel)
     if new_ax:
         limits = (-bp / 1.8, bp / 1.8)
         ax.set_xlim(limits)
         ax.set_ylim(limits)
         ax.set_zlim(limits)
         ax.set_xlabel('x')
         ax.set_ylabel('y')
         ax.set_zlabel('z')
         ax.view_init(elev=elev, azim=azim)
     return ax
Exemple #27
0
def plot_model(face_collection):
    # Create new empty plot
    fig = plt.figure()
    axes = mplot3d.Axes3D(fig)
    axes.set_xlabel("X axis")
    axes.set_ylabel("Y axis")
    axes.set_zlabel("Z axis")

    # Add vectors from models to plot
    good_collection = mplot3d.art3d.Poly3DCollection(
        face_collection.get_vertices(vtype="good"))
    good_collection.set_edgecolor('black')  # Wireframe
    good_collection.set_facecolor('green')

    bad_collection = mplot3d.art3d.Poly3DCollection(
        face_collection.get_vertices(vtype="bad"))
    bad_collection.set_edgecolor('black')  # Wireframe
    bad_collection.set_facecolor('red')
    axes.add_collection3d(good_collection)
    axes.add_collection3d(bad_collection)

    # Plot points
    #axes.scatter3D(model.x,model.y,model.z,color='yellow', s=1) # plot vertices

    # Display plot
    plt.show()
Exemple #28
0
    def plotMesh(self,
                 use_displacement: bool = True,
                 edge_color: str = None,
                 alpha: float = 0.2):
        import mpl_toolkits.mplot3d as a3
        import matplotlib.pyplot as plt
        from matplotlib import _pylab_helpers

        if _pylab_helpers.Gcf.get_active() is None:
            axes = a3.Axes3D(plt.figure())
        else:
            axes = plt.gca()

        if use_displacement:
            points = self.R + self.U
            if edge_color is None:
                edge_color = "red"
        else:
            points = self.R
            if edge_color is None:
                edge_color = "blue"

        vts = points[self.T, :]
        helper = np.array([[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]])
        tri = a3.art3d.Line3DCollection(vts[:, helper].reshape(-1, 2, 3))
        tri.set_alpha(alpha)
        tri.set_edgecolor(edge_color)
        axes.add_collection3d(tri)
        axes.plot(points[:, 0], points[:, 1], points[:, 2], 'ko')
        axes.set_aspect('equal')
def plot_polytope_3d(A, b, ax=None, color='red', trans=0.2):
    verts = np.array(ppm.compute_polytope_vertices(A, b))
    # compute the triangles that make up the convex hull of the data points
    hull = ConvexHull(verts)
    triangles = [verts[s] for s in hull.simplices]
    # combine co-planar triangles into a single face
    faces = Faces(triangles, sig_dig=1).simplify()
    # plot
    if ax == None:
        ax = a3.Axes3D(plt.figure())

    pc = a3.art3d.Poly3DCollection(faces,
                                   facecolor=color,
                                   edgecolor="k",
                                   alpha=trans)
    ax.add_collection3d(pc)
    # define view
    yllim, ytlim = ax.get_ylim()
    xllim, xtlim = ax.get_xlim()
    zllim, ztlim = ax.get_zlim()
    x = verts[:, 0]
    x = np.append(x, [xllim, xtlim])
    y = verts[:, 1]
    y = np.append(y, [yllim, ytlim])
    z = verts[:, 2]
    z = np.append(z, [zllim, ztlim])
    ax.set_xlim(np.min(x) - 1, np.max(x) + 1)
    ax.set_ylim(np.min(y) - 1, np.max(y) + 1)
    ax.set_zlim(np.min(z) - 1, np.max(z) + 1)
Exemple #30
0
def plot_mesh(mesh):
    """ Load and plot initial """
    figure = plt.figure()
    axes = mplot3d.Axes3D(figure)
    if mesh[0].shape[0] == 9:
        axes.add_collection3d(
            mplot3d.art3d.Poly3DCollection(mesh.vectors,
                                           linewidths=1,
                                           alpha=0.01))
        axes.add_collection3d(
            mplot3d.art3d.Line3DCollection(mesh.vectors,
                                           colors='k',
                                           linewidths=0.2,
                                           linestyles=':'))
        scale = mesh.points.flatten('C')
    if mesh[0].shape[0] == 3:
        axes.add_collection3d(
            mplot3d.art3d.Poly3DCollection(mesh, linewidths=1, alpha=0.5))
        axes.add_collection3d(
            mplot3d.art3d.Line3DCollection(mesh,
                                           colors='k',
                                           linewidths=0.2,
                                           linestyles=':'))
        scale = mesh.flatten('C')

    axes.auto_scale_xyz(scale, scale, scale)
    plt.show()