コード例 #1
0
def visualize(gt_mat, meas_mat, graph, res):
    marginals = Marginals(graph, res)

    keys = res.keys()
    linecollection = np.zeros((0, 16, 3))
    linecollection2 = np.zeros((0, 16, 3))
    linecollectionobj = np.zeros((0, 3))
    linecollectionobj2 = np.zeros((0, 3))

    # Plot points and covariance matrices
    for pose in gt_mat[1:, :]:
        linecollection = plot_camera(pose, linecollection)
    linecollectionobj = plot_object(gt_mat[0], linecollectionobj)

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    lc = Line3DCollection(linecollection, color='r')
    ax.add_collection(lc)

    # Plot points and covariance matrices
    for pose in meas_mat[1:, :]:
        linecollection2 = plot_camera(pose, linecollection2)
    linecollectionobj2 = plot_object(meas_mat[0], linecollectionobj2)

    lc2 = Line3DCollection(linecollection2, color='g')
    ax.add_collection(lc2)

    lco = Line3DCollection(linecollectionobj[None, :], color='r')
    ax.add_collection(lco)
    lco2 = Line3DCollection(linecollectionobj2[None, :], color='g')
    ax.add_collection(lco2)
    plt.show()
コード例 #2
0
def connectome(s):
    vertex1, vertex2, vertex3 = s.ch.points[s.ch.simplices[:, 0]], s.ch.points[
        s.ch.simplices[:, 1]], s.ch.points[s.ch.simplices[:, 2]]
    phi_avg = (vertex1 + vertex2 + vertex3) / 3.

    linesv = [(tuple(phi_avg[i[0]]), tuple(phi_avg[i[1]])) for i in vconn]
    colv = [(1, 0, 0, 1) for i in range(len(linesv))]
    linesh = [(tuple(phi_avg[i[0]]), tuple(phi_avg[i[1]])) for i in hconn]
    colh = [(0, 0, 1, 1) for i in range(len(linesh))]
    colx = [(0, 1, 0, 1) for i in range(len(linesh))]
    coly = [(1, 1, 0, 1) for i in range(len(linesh))]

    lines = linesv + linesh
    c = np.array(colv + colh)

    lc1 = Line3DCollection(
        linesv[int(len(linesv) / 2):], colors=colv, linewidths=3
    )  #[:int(5*len(linesv)/7)] [:int(len(linesv)/2)] + linesv[int(3*len(linesv)/4):]
    lc2 = Line3DCollection(linesh[int(len(linesh) / 2):],
                           colors=colh,
                           linewidths=3)  #[:int(5*len(linesh)/7)]
    #lc3 = Line3DCollection(linesv[int(len(linesv)/2):], colors=colx, linewidths=3)
    #lc4 = Line3DCollection(linesh[int(len(linesh)/2):], colors=coly, linewidths=3)
    #fig, ax = pl.subplots()
    #ax.add_collection(lc)
    fig2 = plt.figure()
    ax2 = fig2.gca(projection='3d')
    #ax2.plot(phi_avg[:,0], phi_avg[:,1], phi_avg[:,2], 'r', markersize=1)
    ax2.add_collection(lc1)
    ax2.add_collection(lc2)
コード例 #3
0
 def draw_sphere(self, origin, radius, wireframe=False, **kwargs):
     longitude = np.radians(np.linspace(0, 360, 16,
                                        endpoint=False))[:, np.newaxis]
     latitude = np.radians(np.linspace(-90, 90, 8,
                                       endpoint=True))[np.newaxis, :]
     z = np.sin(latitude)
     r = np.cos(latitude)
     x = r * np.cos(longitude)
     y = r * np.sin(longitude)
     unit_sphere = np.stack((x, y, np.broadcast_to(z, x.shape)), axis=-1)
     sphere = unit_sphere * radius + origin
     if wireframe:
         parallels = np.reshape(
             np.stack(
                 (sphere[:, 1:-1], np.roll(sphere[:, 1:-1], 1, axis=0)),
                 axis=2), (-1, 2, 3))
         meridians = np.reshape(
             np.stack((sphere, np.roll(sphere, 1, axis=1)), axis=-2)[:, 1:],
             (-1, 2, 3))
         self.ax.add_collection(Line3DCollection(parallels, **kwargs))
         self.ax.add_collection(Line3DCollection(meridians, **kwargs))
     else:
         axis = ((), (0, ), (0, 1), (1, ))
         quads = np.reshape(
             np.stack([np.roll(sphere, 1, axis=ax) for ax in axis], axis=2),
             (-1, 4, 3))
         self.ax.add_collection(Poly3DCollection(quads, **kwargs))
コード例 #4
0
def multicolor(ax, x, y, z, t, c, threedim=True, etho=False, cg=1):
    """multicolor plot modified from francesco."""
    lw = 1
    x = x[::cg]
    y = y[::cg]
    if threedim:
        z = z[::cg]
    t = t[::cg]
    if threedim:
        points = np.array([x, y, z]).transpose().reshape(-1, 1, 3)
        segs = np.concatenate([points[:-1], points[1:]], axis=1)
        lc = Line3DCollection(segs, cmap=c, lw=lw)
        if etho:
            lc = Line3DCollection(segs, cmap=c, lw=lw, norm=ethonorm)
        lc.set_array(t)
        ax.add_collection3d(lc)
        ax.set_xlim(np.min(x), np.max(x))
        ax.set_ylim(np.min(y), np.max(y))
        ax.set_zlim(np.min(z), np.max(z))
    else:
        points = np.array([x, y]).transpose().reshape(-1, 1, 2)
        segs = np.concatenate([points[:-1], points[1:]], axis=1)
        lc = LineCollection(segs, cmap=c, lw=lw)
        if etho:
            lc = LineCollection(segs, cmap=c, lw=lw, norm=ethonorm)
        lc.set_array(t)
        ax.add_collection(lc)
        ax.set_xlim(np.min(x), np.max(x))
        ax.set_ylim(np.min(y), np.max(y))
    return lc
コード例 #5
0
	def drawWhirlybird(self,phi,theta,psi):
		verts = []
		for i in range(1,len(self.verts)):
			vertsTemp = rotate(self.verts[i].T,phi,theta,psi).T
			vertsTemp = transformXYZtoNED(vertsTemp)
			verts.append(vertsTemp)

		#print(verts)
		verts = np.asarray(verts)
		#print(verts)

		if self.flagInit == True:
			# Initialize Poly3DCollection class for each set of vertices, and
			# create an object handle to each one.
			self.PolyCollections.append(Line3DCollection([np.asarray(verts[0])],facecolor = 'black',edgecolor = 'black', lw = 2))
			self.PolyCollections.append(Line3DCollection([np.asarray(verts[1])],facecolor = 'black',edgecolor = 'black', lw = 2))
			self.PolyCollections.append(Poly3DCollection([np.asarray(verts[2])],facecolor = 'green',edgecolor = 'black', lw = 2))
			self.PolyCollections.append(Poly3DCollection([np.asarray(verts[3])],facecolor = 'red',edgecolor = 'black', lw = 2))
			# Add each Poly3DCollection object to the axes.
			for i in range(len(self.PolyCollections)):
				self.ax.add_collection3d(self.PolyCollections[i])
			self.flagInit = False
		else:
			# Update the verts
			self.PolyCollections[0].set_segments([np.asarray(verts[0])])
			self.PolyCollections[1].set_segments([np.asarray(verts[1])])
			self.PolyCollections[2].set_verts([np.asarray(verts[2])])
			self.PolyCollections[3].set_verts([np.asarray(verts[3])])
コード例 #6
0
    def update_scalarmappable(self):
        if self._c_data is None:
            self._gl_solid_edgecolor = self.get_color()[0]
        if self._gl_solid_edgecolor is not None:
            f = cc.to_rgba(self._gl_solid_edgecolor)
            self._gl_edgecolor = np.tile(f, (len(self._gl_3dpath[2]),1))        
        else:
            self._gl_edgecolor = self.to_rgba(self._c_data)
            idx = (np.sum(self._gl_edgecolor[:,:3],1) != 0.0)
            self._gl_edgecolor[idx,-1]=self._alpha

        Line3DCollection.update_scalarmappable(self)
コード例 #7
0
    def create_artists_graph(self):
        '''create and add to self.ax main artrist related to lattice graph'''

        # initialize vertices
        self.xyz = self.vertices.coords
        self.x, self.y, self.z = self.xyz.T
        self.update_XY_scr()

        # create vertices
        if self.sc is not None:  # remove previous vertices points
            self.ax.collections.remove(self.sc)

        self.sc = self.ax.scatter(self.x, self.y, self.z, marker='o')

        # create edges
        if self.USE_COLLECTIONS:
            if self.edges_lines is not None:  # remove previous edges lines
                for key, edge_col in self.edges_lines.items():
                    self.ax.collections.remove(edge_col)

            self.edges_lines = {}
            for key, edge in self.UC.edges.items():
                segments = [
                    self.xyz[self.edges.source_target[j], :]
                    for j in self.edges.array_ind[key]
                ]
                edge_col = Line3DCollection(segments)
                self.ax.add_collection3d(edge_col)
                self.edges_lines[key] = edge_col
        else:
            if self.edges_lines is not None:  # remove previous lines edges
                for line in self.edges_lines:
                    self.ax.artists.remove(line)

            self.edges_lines = []
            for j in range(len(self.edges.ids)):
                st = list(self.edges.source_target[j])
                line = Line3D(self.x[st], self.y[st], self.z[st])
                self.ax.add_artist(line)
                self.edges_lines.append(line)

        # create latticeNet
        if self.latticeNet is not None:  # remove previous lattice lines
            self.ax.collections.remove(self.latticeNet)
        self.latticeNet = Line3DCollection(self.cluster.latticeLines,
                                           linestyle='--',
                                           lw=0.2)
        self.ax.add_collection3d(self.latticeNet)

        self.v_source_ind, self.v_target_ind = None, None
        self.v_ind, self.v_active_ind = None, None
        self.e_ind, self.e_active_ind = None, None
        self.e_activeDist_ids = []
コード例 #8
0
def plot_bg_and_mc(pbg, pmc, id=0, step=1):
    df = pbg
    # mind the order!
    d0 = pd.DataFrame([
                df['Z'][::step],
                df['X'][::step],
                df['Y'][::step]],
                index=['z', 'x', 'y']).T
    numtracks = d0.shape[0]
    dd = pd.DataFrame([
            df['TX'][::step]*dZ,
            df['TY'][::step]*dZ],
            index=['x', 'y']).T
    dd.insert(loc=0, column='z', value=dZ)
    d1 = d0 + dd
    # print d0, d1
    C = plt.cm.Blues(0.5)
    lc_bg = Line3DCollection(list(zip(d0.values, d1.values)), colors=C, alpha=0.5, lw=2)

    df = pmc

    # mind the order!
    d0 = pd.DataFrame([
                df['Z'],
                df['X'],
                df['Y']],
                index=['z', 'x', 'y']).T
    numtracks = d0.shape[0]
    dd = pd.DataFrame([
            df['TX']*dZ,
            df['TY']*dZ],
            index=['x', 'y']).T
    dd.insert(loc=0, column='z', value=dZ)
    d1 = d0 + dd
    print(d1.shape)
    C = plt.cm.Reds(0.5)
    lc_mc = Line3DCollection(list(zip(d0.values, d1.values)), colors=C, alpha=0.9, lw=2)
    
    fig = plt.figure(figsize=(12,8))
    ax = fig.gca(projection='3d')
    ax.view_init(azim=-50, elev=10)
    ax.add_collection3d(lc_mc)
    ax.add_collection3d(lc_bg)
    
    # mind the order!
    ax.set_xlabel("z")
    ax.set_ylabel("x")
    ax.set_zlabel("y")  
    ax.set_xlim(0, BRICK_Z)
    ax.set_ylim(0, BRICK_X)
    ax.set_zlim(0, BRICK_Y)
コード例 #9
0
 def __init__(self, *args, **kargs):
     ArtGL.__init__(self)
     self.do_stencil_test = True
     self._gl_3dpath = kargs.pop('gl_3dpath', None)
     self._gl_offset = kargs.pop('gl_offset', (0, 0, 0.))
     self._gl_edgecolor = kargs.pop('gl_edgecolor', None)
     self._c_data = kargs.pop('c_data', None)
     self._gl_solid_edgecolor = kargs.pop('gl_solid_edgecolor', None)
     self._gl_lighting = kargs.pop('gl_lighting', True)
     self._gl_array_idx = kargs.pop('array_idx', None)
     self._gl_voffset = kargs.pop('view_offset', (0,0,0,0.))        
     self._update_ec = True
     self._update_v = True
     Line3DCollection.__init__(self, *args, **kargs)
コード例 #10
0
def plot_datamatrix3D_multicolor(amp_datamatrix, sampletime, FPS, area_start,
                                 area_end):

    bin_length = 8 * 1.5e8 / 23.328e9

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.set_title("Raw radar data", title_font)
    ax.set_xlabel("Range/m", axis_font)
    ax.set_ylabel("Time/s", axis_font)
    ax.set_zlabel("Amplitude", axis_font)
    ax.set_zlim(-0.005, 0.005)
    ax.set_xlim(0, 5)
    ax.set_ylim(0, 60)

    slowtime = np.arange(sampletime)
    fasttime = np.arange((area_start - 1e-5), (area_end - 1e-5) + bin_length,
                         bin_length)
    norm = plt.Normalize(amp_datamatrix.min(), amp_datamatrix.max())

    for i in slowtime:
        slowtime_array = np.full(len(fasttime), i)
        amp_array = amp_datamatrix[i * FPS]
        points = np.array([fasttime, slowtime_array,
                           amp_array]).T.reshape(-1, 1, 3)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)

        # ax.plot3D(fasttime ,slowtime_array,amp_datamatrix[i*FPS] ,'blue')
        lc = Line3DCollection(segments, cmap='rainbow', norm=norm)
        lc.set_array(amp_array)
        lc.set_linewidth(1)
        line = ax.add_collection(lc)
    fig.colorbar(line, ax=ax)
    plt.show()
    fig.savefig('test.png', dpi=600)
コード例 #11
0
ファイル: animation.py プロジェクト: nonrevlb/ControlSystems
 def __init__(self):
     self.flagInit = True  # Used to indicate initialization
     self.fig = plt.figure()
     self.ax = Axes3D(self.fig)  # Create a 3D axes in the figure
     # A list object that will contain the lists of vertices of the
     # space ships sides.
     self.verts = self.getWhirlybirdVertices()
     #Create stand that won't move
     stand = Line3DCollection([np.asarray(self.verts[0])],
                              facecolor='black',
                              edgecolor='black',
                              lw=2)
     self.ax.add_collection3d(stand)
     # A list that will contain handles to the Poly3DCollection
     # Objects so that they can be modified.
     self.PolyCollections = []
     # Set axis limits
     _axis_limit = 1.1
     self.ax.set_zlim3d([-.65, _axis_limit])
     self.ax.set_ylim3d([-_axis_limit, _axis_limit])
     self.ax.set_xlim3d([-_axis_limit, _axis_limit])
     # Set title and labels
     self.ax.set_title('Spacecraft')
     self.ax.set_xlabel('East')
     self.ax.set_ylabel('North')
     self.ax.set_zlabel('-Down')
     # Change viewing angle
     self.ax.view_init(self.ax.elev, self.ax.azim + 90)
コード例 #12
0
def plotChainWithEdge(chain, edges, dist):
    pts = chain

    plt.ion()
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    # for b in barcodes:
    xPoints = [point[0] for point in pts]
    yPoints = [point[1] for point in pts]
    zPoints = [point[2] for point in pts]

    #Chain
    # ax.plot(xPoints, yPoints, zPoints, 'b')

    #Balls
    # ax.scatter(xPoints, yPoints, zPoints, 'r', s=350, alpha=0.4)

    #Points
    ax.scatter(xPoints, yPoints, zPoints, 'r')

    radius = [dist] * len(pts)
    for (xi, yi, zi, ri) in zip(xPoints, yPoints, zPoints, radius):
        (xs, ys, zs) = drawSphere(xi, yi, zi, ri)
        # ax.plot_surface(xs, ys, zs, color="b", alpha=.1)

    points = np.array([p.tolist() for p in pts])
    lc = Line3DCollection(points[edges], colors='r')
    #Edges
    plt.gca().add_collection(lc)

    plt.draw()
    plt.show()
    plt.pause(1000000)
コード例 #13
0
ファイル: visualization.py プロジェクト: YaluLiu/mocap
def display_3D_skeleton(pos, skeleton, azim, camera_pos=None):
    line_3d_segs = []
    cols = []
    for j, j_parent in enumerate(skeleton.parents()):
        if j_parent == -1:
            continue

        col = 'red' if j in skeleton.joints_right() else 'black'
        cols.append(col)
        line_3d_segs.append([(pos[j, 0], pos[j, 1], pos[j, 2]),
                             (pos[j_parent, 0], pos[j_parent, 1], pos[j_parent,
                                                                      2])])

    lc = Line3DCollection(line_3d_segs, colors=cols, linewidths=2)
    fig = plt.figure(figsize=(10, 10))
    ax_3d = fig.add_subplot(1, 1, 1, projection='3d')
    ax_3d.add_collection3d(lc, zdir='z')
    ax_3d.view_init(elev=15., azim=azim)
    # ax_3d.set_aspect('equal')
    ax_3d.set_xlim3d([-4, 5])
    ax_3d.set_ylim3d([-4, 5])
    ax_3d.set_zlim3d([-4, 5])

    if camera_pos is not None:
        ax_3d.scatter(camera_pos["x"],
                      camera_pos["y"],
                      camera_pos["z"],
                      color="g",
                      s=50)

    plt.show()
コード例 #14
0
ファイル: mesh_tools.py プロジェクト: fanronghong/fealpy
def show_mesh_1d(axes,
                 mesh,
                 nodecolor='k',
                 cellcolor='k',
                 aspect='equal',
                 linewidths=1,
                 markersize=20,
                 showaxis=False):
    axes.set_aspect(aspect)
    if showaxis == False:
        axes.set_axis_off()
    else:
        axes.set_axis_on()

    node = mesh.node
    cell = mesh.ds.cell

    dim = mesh.geo_dimension()
    if dim == 1:
        node = np.r_['1', node.reshape(-1, 1), np.zeros((len(node), 1))]

    axes.scatter(node[:, 0], node[:, 1], color=nodecolor, s=markersize)
    vts = node[cell, :]

    if dim < 3:
        lines = LineCollection(vts, linewidths=linewidths, colors=cellcolor)
        return axes.add_collection(lines)
    else:
        lines = Line3DCollection(vts, linewidths=linewidths, colors=cellcolor)
        return axes.add_collection3d(vts)
コード例 #15
0
ファイル: mesh_tools.py プロジェクト: heyewangyueming/fealpy
def show_mesh_1d(axes,
                 mesh,
                 nodecolor='k',
                 cellcolor='k',
                 aspect='equal',
                 linewidths=1,
                 markersize=20,
                 showaxis=False):
    axes.set_aspect(aspect)
    if showaxis == False:
        axes.set_axis_off()
    else:
        axes.set_axis_on()

    node = mesh.entity('node')
    cell = mesh.entity('cell')

    if node.shape[1] == 1:
        node = np.r_['1', node, np.zeros_like(node)]

    axes.scatter(node[:, 0], node[:, 1], color=nodecolor, s=markersize)
    vts = node[cell, :]

    GD = mesh.geo_dimension()
    if GD < 3:
        lines = LineCollection(vts, linewidths=linewidths, colors=cellcolor)
        return axes.add_collection(lines)
    else:
        lines = Line3DCollection(vts, linewidths=linewidths, colors=cellcolor)
        return axes.add_collection3d(vts)
コード例 #16
0
def get_animManager():
    """Return axample of configured AnimationManager instance"""
                
    # data: coordinates of nodes and links
    xn = [1.1, 1.9, 0.1, 0.3, 1.6, 0.8, 2.3, 1.2, 1.7, 1.0, -0.7, 0.1, 0.1, -0.9, 0.1, -0.1, 2.1, 2.7, 2.6, 2.0]
    yn = [-1.2, -2.0, -1.2, -0.7, -0.4, -2.2, -1.0, -1.3, -1.5, -2.1, -0.7, -0.3, 0.7, -0.0, -0.3, 0.7, 0.7, 0.3, 0.8, 1.2]
    zn = [-1.6, -1.5, -1.3, -2.0, -2.4, -2.1, -1.8, -2.8, -0.5, -0.8, -0.4, -1.1, -1.8, -1.5, 0.1, -0.6, 0.2, -0.1, -0.8, -0.4]
    group = [1, 1, 4, 4, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3]
    edges = [(1, 0), (2, 0), (3, 0), (3, 2), (4, 0), (5, 0), (6, 0), (7, 0), (8, 0), (9, 0), (11, 10), (11, 3), (11, 2), (11, 0), (12, 11), (13, 11), (14, 11), (15, 11), (17, 16), (18, 16), (18, 17), (19, 16), (19, 17), (19, 18)]
    xyzn = list(zip(xn, yn, zn))
    segments = [(xyzn[s], xyzn[t]) for s, t in edges]                
                    
    # create figure        
    fig = plt.figure('3D graph example')
    ax = fig.gca(projection='3d')
    ax.set_axis_off()
    
    # plot vertices
    ax.scatter(xn,yn,zn, marker='o', c = group, s = 64)    
    # plot edges
    edge_col = Line3DCollection(segments, lw=0.2)
    ax.add_collection3d(edge_col)
    # add vertices annotation. CAUTION: might slow down animation
    for j, xyz_ in enumerate(xyzn): 
        annotate3D(ax, s=str(j+1), xyz=xyz_, fontsize=10, xytext=(-3,3),
                   textcoords='offset points', ha='right',va='bottom')
                    
    # pass figure to animation manager
    mng = AnimationManager(ax)
    # set some initial parameters
    mng.dlg.spinBox_period_rot.setValue(20)
    mng.dlg.spinBox_elev.setValue(20)
    
    return mng
コード例 #17
0
ファイル: runge.py プロジェクト: mathhat/unik4660
def update_line(num, r, line, ax):

    line[0].set_data(r[0:2, :num])
    line[0].set_3d_properties(r[2, :num])
    line[1].set_data([[x[num], x[num] + B[0, num]],
                      [y[num], y[num] + B[1, num]]])
    line[1].set_3d_properties([z[num], z[num] + B[2, num]])
    line[2].set_data([[x[num], x[num] + N[0, num]],
                      [y[num], y[num] + N[1, num]]])
    line[2].set_3d_properties([z[num], z[num] + N[2, num]])
    line[3].set_data([[x[num], x[num] + T[0, num]],
                      [y[num], y[num] + T[1, num]]])
    line[3].set_3d_properties([z[num], z[num] + T[2, num]])
    #line[2].set_data([r[0:2, num], r[0:2, num]+N[0:2, num]])
    #line[2].set_3d_properties([r[2, num],r[2, num]+N[2, num]])
    #line[3].set_data([r[0:2, num], r[0:2, num]+T[0:2, num]])
    #line[3].set_3d_properties([r[2, num],r[2, num]+T[2, num]])

    #fig2.clf(ax1)
    #if num%50 == 0:
    #ax.plot([x[num],x[num]+B[0,num]],[y[num],y[num]+ B[1,num]],[z[num], z[num]+B[2,num]],'r')
    #ax.plot([x[num],x[num]+N[0,num]],[y[num],y[num]+ N[1,num]],[z[num], z[num]+N[2,num]],'b')
    #ax.plot([x[num],x[num]+T[0,num]],[y[num],y[num]+ T[1,num]],[z[num], z[num]+T[2,num]],'g')
    lc = Line3DCollection(segments[0:(num)],
                          cmap=plt.get_cmap('coolwarm'),
                          norm=norm)
    lc.set_array(torsion[0:(num)])
    lc.set_linewidth(2)

    ax.add_collection3d(lc, zs=r[2, 0:num], zdir='z')

    return line
コード例 #18
0
ファイル: spatial-lif.py プロジェクト: jackd/ecn
def vis_graph(coords, time, out_coords, out_time, indices, splits, n=10):
    splits = splits[:n + 1]
    out_coords = out_coords[:n]
    out_time = out_time[:n]
    indices = indices[:splits[-1]]
    in_indices = list(set(indices))

    row_lengths = splits[1:] - splits[:-1]

    fig = plt.figure()
    ax = fig.gca(projection="3d")
    ax.scatter(coords[in_indices, 0],
               coords[in_indices, 1],
               time[in_indices],
               color="black")
    ax.scatter(out_coords[:, 0], out_coords[:, 1], out_time, color="blue")

    j = indices
    x = coords[j, 0]
    y = coords[j, 1]
    t = time[j]
    in_xyz = np.stack((x, y, t), axis=-1)

    out_x = np.repeat(out_coords[:, 0], row_lengths, axis=0)
    out_y = np.repeat(out_coords[:, 1], row_lengths, axis=0)
    out_t = np.repeat(out_time, row_lengths, axis=0)
    out_xyz = np.stack((out_x, out_y, out_t), axis=-1)
    # print(out_xyz[:, :2] - in_xyz[:, :2])

    segs = np.stack((in_xyz, out_xyz), axis=-2)
    assert segs.shape[1:] == (2, 3)

    ax.add_collection(Line3DCollection(segs))
コード例 #19
0
def plot_model(ax, model, color, initial, **options):
    lines = list()

    for element in model.elements:
        if type(element) == Truss:
            node_a = element.node_a
            node_b = element.node_b

            a = [node_a.reference_x, node_a.reference_y, node_a.reference_z
                 ] if initial else [node_a.x, node_a.y, node_a.z]
            b = [node_b.reference_x, node_b.reference_y, node_b.reference_z
                 ] if initial else [node_b.x, node_b.y, node_b.z]

            lines.append([a, b])
        elif type(element) == Spring:
            location = element.node.location
            if element.kx != 0:
                plot_spring(ax, location, 'x', **options)
            if element.ky != 0:
                plot_spring(ax, location, 'y', **options)
            if element.kz != 0:
                plot_spring(ax, location, 'z', **options)

    lc = Line3DCollection(lines, colors=color, linewidths=2)

    ax.add_collection(lc)

    plot_symbols(ax, model, color, initial, **options)
コード例 #20
0
def plot_3d_forest_rover(roverdomain, rectangles, ntraj_points=100):
    from matplotlib import pyplot as plt
    from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection

    # get the cost of the current trajectory
    traj_cost = roverdomain.estimate_cost()

    # get points on the current trajectory
    traj_points = roverdomain.traj.get_points(np.linspace(0., 1.0, ntraj_points, endpoint=True))

    # convert the rectangles into lists of vertices for matplotlib
    poly3d, verts, faces = generate_verts(rectangles)

    ax = plt.gcf().add_subplot(111, projection='3d')

    # plot start and goal
    ax.scatter((roverdomain.start[0], roverdomain.goal[0]),
               (roverdomain.start[1], roverdomain.goal[1]),
               (roverdomain.start[2], roverdomain.goal[2]), c='k')

    # plot traj
    seg = (zip(traj_points[:-1, :], traj_points[1:, :]))
    ax.add_collection3d(Line3DCollection(seg, colors=[(0, 1., 0, 1.)] * len(seg)))

    # plot rectangles
    ax.add_collection3d(Poly3DCollection(poly3d, facecolors=(0.7, 0.7, 0.7, 1.), linewidth=0.5))

    # set limits of axis to be the same as domain
    s_range = roverdomain.s_range
    ax.set_xlim(s_range[0][0], s_range[1][0])
    ax.set_ylim(s_range[0][1], s_range[1][1])
    ax.set_zlim(s_range[0][2], s_range[1][2])
コード例 #21
0
ファイル: plot_detector_tools.py プロジェクト: jxi24/TrackML
    def add_module_hit_outline_3D_plot(self,
                                       fig,
                                       track_id,
                                       hitlist=None,
                                       copy_fig=False,
                                       edgecolor='firebrick',
                                       linewidth=5):

        if copy_fig:
            new_fig = self.copy_fig(fig)
        else:
            new_fig = fig

        hit_modules = self.get_track_hits(track_id)[1]
        if hitlist is not None:
            hit_modules = hit_modules[hitlist]

        ax = new_fig.axes[0]
        for module in hit_modules:
            module_cell = Line3DCollection(
                self.module_verts_cycle[tuple(module)],
                linewidth=linewidth,
                edgecolor=edgecolor)
            ax.add_collection3d(module_cell)

        return new_fig
コード例 #22
0
def plot_tree3d(ax,
                tree,
                diameter_scale=_DIAMETER_SCALE,
                linewidth=_LINEWIDTH,
                color=None,
                alpha=_ALPHA):
    '''Generates a figure of the tree in 3d.

    If the tree contains one single point the plot will be empty \
    since no segments can be constructed.

    Args:
        ax(matplotlib axes): on what to plot
        tree(neurom.core.Tree or neurom.core.Neurite): plotted tree
        diameter_scale(float): Scale factor multiplied with segment diameters before plotting
        linewidth(float): all segments are plotted with this width, but only if diameter_scale=None
        color(str or None): Color of plotted values, None corresponds to default choice
        alpha(float): Transparency of plotted values
    '''
    segs = [(s[0][COLS.XYZ], s[1][COLS.XYZ]) for s in iter_segments(tree)]

    linewidth = _get_linewidth(tree,
                               diameter_scale=diameter_scale,
                               linewidth=linewidth)
    color = _get_color(color, tree.type),

    collection = Line3DCollection(segs,
                                  color=color,
                                  linewidth=linewidth,
                                  alpha=alpha)
    ax.add_collection3d(collection)

    _update_3d_datalim(ax, tree)
    def Draw_Mu4_Outline_Region(self, verts, ininc, adj):

        verts_z = (self.compounds_info[self.main_compound]["enthalpy"] - self.compounds_info[self.main_compound][self.dependent_element]*self.mu4 \
           - self.compounds_info[self.main_compound][self.element_x]*verts[:,0] \
           - self.compounds_info[self.main_compound][self.element_y]*verts[:,1] ) \
           / self.compounds_info[self.main_compound][self.element_z]

        verts_z = verts_z.reshape((len(verts), 1))
        plane_vertices = np.hstack((verts, verts_z))

        for i, ininc_i in enumerate(ininc):
            if len(ininc_i) < 3:
                continue
            ininc_i = self.Sort_Plane_Vertices(ininc_i, adj)
            x = []
            y = []
            z = []
            for v in ininc_i:
                x.append(plane_vertices[v][0])
                y.append(plane_vertices[v][1])
                z.append(plane_vertices[v][2])
            x.append(plane_vertices[ininc_i[0]][0])
            y.append(plane_vertices[ininc_i[0]][1])
            z.append(plane_vertices[ininc_i[0]][2])
            coord = [list(zip(x, y, z))]

            try:
                self.path.remove()
            except:
                pass

            self.path = Line3DCollection(coord, lw=4, color='k')
            self.quaternary_phasediagram_3d_plot_axes.add_collection3d(
                self.path)
コード例 #24
0
def draw_polygon_coll(ax,
                      mesh,
                      tris,
                      sf=1,
                      ln=1,
                      pg=1,
                      c=[0, 0, 1],
                      alpha=0.1,
                      linewidths=0.5,
                      linestyles=':'):
    Pcoll = []
    for triID in tris:
        P = []
        for verID in mesh.getTri(triID):
            triVertex = tuple(mesh.getVertex(verID))
            P.append(triVertex)
        Pcoll.append(P)
    if ln == 1:
        collection = Line3DCollection(Pcoll,
                                      colors=c,
                                      linewidths=linewidths,
                                      linestyles=linestyles)
        ax.add_collection3d(collection)
    if pg == 1:
        collection = Poly3DCollection(Pcoll)
        collection.set_facecolor((c[0], c[1], c[2], alpha))

    ax.add_collection3d(collection)
    ax.set_xlim(0, SCALING_FACTOR)
    ax.set_ylim(0, SCALING_FACTOR)
    ax.set_zlim(0, SCALING_FACTOR)
コード例 #25
0
def _colorline3d(x,
                 y,
                 z,
                 t=None,
                 cmap=plt.get_cmap('viridis'),
                 linewidth=1,
                 alpha=1.0,
                 ax=None):
    '''
    Plot a colored line with coordinates x and y
    Optionally specify colors in the array z
    Optionally specify a colormap, a norm function and a line width
    https://stackoverflow.com/questions/52884221/how-to-plot-a-matplotlib-line-plot-using-colormap
    '''
    # Default colors equally spaced on [0,1]:
    if t is None:
        t = np.linspace(0.25, 1.0, len(x))
    if ax is None:
        ax = plt.gca()

    points = np.array([x, y, z]).T.reshape(-1, 1, 3)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)

    colors = np.array([cmap(i) for i in t])
    lc = Line3DCollection(segments,
                          colors=colors,
                          linewidth=linewidth,
                          alpha=alpha)
    ax.add_collection(lc)
    ax.scatter(x, y, z, c=colors, marker='*',
               alpha=alpha)  #Adding line markers
コード例 #26
0
def plot_mesh_3D(P,
                 var,
                 bnd=None,
                 choice='T',
                 linewidth=0.5,
                 marker_size=3,
                 eps=1e-16):
    if choice == 'T':
        E = get_E(var)
    else:
        E = var
    lines = []
    for i in range(E.shape[0]):
        lines.append([tuple(P[E[i, 0], :]), tuple(P[E[i, 1], :])])
    lc = Line3DCollection(lines, colors='black', linewidth=linewidth)
    fig = plt.figure()

    ax = fig.gca(projection='3d')
    ax.add_collection3d(lc)

    if bnd is None:
        c_list = 'blue'
    else:
        bnd_P = poly_bnd_3D(bnd[0], bnd[1], P, eps=eps)
        c_list = np.where(bnd_P, 'red', 'blue')
    ax.scatter(P[:, 0], P[:, 1], P[:, 2], s=marker_size, c=c_list)

    xa, ya, za = np.min(P, axis=0)
    xb, yb, zb = np.max(P, axis=0)
    ax.set_xlim(xa, xb)
    ax.set_ylim(ya, yb)
    ax.set_zlim(za, zb)

    plt.show()
コード例 #27
0
def plot_SubTh1simp3D(q, me, u, **kwargs):
    lim = kwargs.pop('lim', True)
    vmin = kwargs.pop('vmin', np.min(u))
    vmax = kwargs.pop('vmax', np.max(u))
    fig = plt.gcf()
    if len(fig.axes) > 0:
        ax = fig.axes[0]
    else:
        ax = fig.gca(projection='3d')
    U = np.mean(u[me], axis=1).reshape((me.shape[0], ))
    coll = ax.add_collection(
        Line3DCollection(q[me],
                         array=U,
                         norm=matplotlib.colors.Normalize(vmin=vmin,
                                                          vmax=vmax),
                         **kwargs))
    if lim:
        box = np.array([
            np.min(q[:, 0]),
            np.max(q[:, 0]),
            np.min(q[:, 1]),
            np.max(q[:, 1]),
            np.min(q[:, 2]),
            np.max(q[:, 2])
        ])
        set_axes(ax, box)
    return coll
コード例 #28
0
def draw_lines_3d(lines,
                  axes,
                  linewidth=1.0,
                  linestyle='solid',
                  color='#000000'):
    """Creates an 3D line collection and adds it to the axis.

    Parameters:
        lines (list): List of ((X1, Y1, Z1), (X2, X2, Z2)) lines.
        axes (object): Matplotlib axes.
        linewidth (float, list): Width for the lines.
        linestyle (str, list): Matplotlib line style strings.
        color (str, list): Color for the lines in hex or rgb.

    """
    l = len(lines)
    if isinstance(linewidth, (int, float)):
        linewidth = float(linewidth)
        linewidth = [linewidth] * l
    if isinstance(color, basestring):
        color = [color] * l
    # --------------------------------------------------------------------------
    coll = Line3DCollection(lines,
                            linewidths=linewidth,
                            colors=color,
                            linestyle=linestyle,
                            zorder=ZORDER_LINES)
    axes.add_collection(coll)
コード例 #29
0
def annotate_cluster(cluster_name, cluster_civs, civ_data, X, ax):
    c = []
    for i in range(civ_data.shape[0]):
        if civ_data.iloc[i].name in cluster_civs:
            c.append(i)
    center = np.mean(X[c, 0:3], axis=0)
    ax.scatter(center[0],
               center[1],
               center[2],
               s=100,
               c='orange',
               marker='o',
               edgecolors='black')

    segments = [(center, X[C, 0:3]) for C in c]
    ax.add_collection3d(Line3DCollection(segments, lw=2))
    ax.text3D(center[0],
              center[1],
              center[2],
              cluster_name,
              color='orange',
              size=24,
              horizontalalignment='center',
              verticalalignment='top',
              bbox=dict(alpha=0, edgecolor='w', facecolor='w'))

    #    ax.text3D(np.max(X[:,0],axis=0),np.max(X[:,1],axis=0),np.max(X[:,2],axis=0),cluster_name, color ='orange', size = 24,
    #               horizontalalignment='center', verticalalignment='top',
    #               bbox=dict(alpha=0, edgecolor='w', facecolor='w'))

    plt.draw()
    plt.pause(0.1)
コード例 #30
0
def plotChainWithAllHom(chain, useNewMethod):
    distM = MAT.getDistM(chain)
    barcodes, info = TDA.genHom(distM, useNewMethod)
    edges = []

    for b in barcodes:
        edges += b[0]

    plt.ion()
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    # for b in barcodes:
    xPoints = [point[0] for point in chain]
    yPoints = [point[1] for point in chain]
    zPoints = [point[2] for point in chain]

    ax.scatter(xPoints, yPoints, zPoints, 'r')

    points = np.array([p.tolist() for p in chain])
    lc = Line3DCollection(points[edges], colors='r')
    # Edges
    plt.gca().add_collection(lc)

    plt.draw()
    plt.show()
    plt.pause(1000000)