Пример #1
0
def plot_graph_3d(G):
    from mayavi import mlab

    for (node0, node1) in G.edges():
        (x0, y0, z0) = G.node[node0]["xyz"]
        (x1, y1, z1) = G.node[node1]["xyz"]
        mlab.plot3d([x0, x1], [y0, y1], [z0, z1], color=(1, 0, 0), tube_radius=0.0025)
Пример #2
0
def show3d():
	# cube
	a = list(itertools.product(([0.5,1]),repeat=3))
	controls = [np.array(list(b)) for b in a]

	# random
	controls = np.random.uniform(0.0,1.0,(5,3))
	norms = np.apply_along_axis(np.linalg.norm, 1, controls)
	controls = np.transpose(controls.T/norms)

	cone = get_cone(controls,verbose=1)

	print "Controls:",controls
	print "Cone:",cone

	for c in controls:
		plan3d(c,np.array([0]*3))
	
	mlab.points3d(controls[:,0],controls[:,1],controls[:,2])

	for c in cone:
		l = np.array([c*0.0] + [c*1.0])
		x = l[:,0]
		y = l[:,1]
		z = l[:,2]
		mlab.plot3d(x,y,z,line_width=1.0)

	mlab.show()
Пример #3
0
    def test_stericValue_1(self):
        print("m0, m1, m2", self.cg1.steric_value(["m0", "m1", "m2"]))
        from_ = np.amin(self.cg1.coords._coordinates)
        to_ = np.amax(self.cg1.coords._coordinates)
        x, y, z = np.mgrid[from_:to_:4, from_:to_:4, from_:to_:4]
        from mayavi import mlab
        s = np.zeros_like(x)
        for i, j, k in np.ndindex(x.shape):
            s[i, j, k] = self.cg1.steric_value(
                np.array([x[i, j, k], y[i, j, k], z[i, j, k]]), "r**-3")
        #mlab.contour3d(x,y,z,s, contours= [0.5, 1, 2, 5], opacity=0.3)
        src = mlab.pipeline.scalar_field(x, y, z, s)
        mlab.pipeline.volume(src)
        #mlab.pipeline.iso_surface(src, contours=[0.1, ], opacity=0.3)
        #mlab.pipeline.iso_surface(src, contours=[0.5, ], opacity=0.7)
        #mlab.pipeline.iso_surface(src, contours=[1, ])

        colors = {"s": (0, 1, 0), "h": (0, 0, 1), "m": (1, 0, 0), "i": (
            1, 1, 0), "f": (0.5, 0.5, 0.5), "t": (0.5, 0.5, 0.5)}
        for d in self.cg1.defines:
            x = self.cg1.coords[d][0][0], self.cg1.coords[d][1][0]
            y = self.cg1.coords[d][0][1], self.cg1.coords[d][1][1]
            z = self.cg1.coords[d][0][2], self.cg1.coords[d][1][2]
            mlab.plot3d(x, y, z, tube_radius=2, color=colors[d[0]])
        mlab.show()
        assert False
Пример #4
0
def plot_matrix(connectmat_file, centers_file, threshold_pct=5, weight_edges=False,
                node_scale_factor=2, edge_radius=.5, resolution=8, name_scale_factor=1,
                names_file=None, node_indiv_colors=[], highlight_nodes=[], fliplr=False):
    """
    Given a connectivity matrix and a (x,y,z) centers file for each region, plot the 3D network
    """
    matrix = core.file_reader(connectmat_file)
    nodes = core.file_reader(centers_file)
    if names_file:
        names = core.file_reader(names_file,1)
    num_nodes = len(nodes)
    edge_thresh_pct = threshold_pct / 100.0
    matrix_flat = np.array(matrix).flatten()
    edge_thresh = np.sort(matrix_flat)[len(matrix_flat)-int(len(matrix_flat)*edge_thresh_pct)]
    
    matrix = core.file_reader(connectmat_file)
    ma = np.array(matrix)

    thresh = scipy.stats.scoreatpercentile(ma.ravel(),100-threshold_pct)
    ma_thresh = ma*(ma > thresh)
    
    if highlight_nodes:
        nr = ma.shape[0]
        subset_mat = np.zeros((nr, nr))
        for i in highlight_nodes:
            subset_mat[i,:] = 1
            subset_mat[:,i] = 1
        ma_thresh = ma_thresh * subset_mat
        
    if fliplr:
        new_nodes = []
        for node in nodes:
            new_nodes.append([45-node[0],node[1],node[2]]) # HACK
        nodes = new_nodes
    
    mlab.figure(bgcolor=(1, 1, 1), size=(400, 400))
    for count,(x,y,z) in enumerate(nodes):
        if node_indiv_colors:
            mlab.points3d(x,y,z, color=colors[node_indiv_colors[count]], scale_factor=node_scale_factor, resolution=resolution)
        else:
            mlab.points3d(x,y,z, color=(0,1,0), scale_factor=node_scale_factor, resolution=resolution)
        if names_file:
            width = .025*name_scale_factor*len(names[count])
            print width
            print names[count]
            mlab.text(x, y,names[count], z=z,width=.025*len(names[count]),color=(0,0,0))
    for i in range(num_nodes-1):    
        x0,y0,z0 = nodes[i]
        for j in range(i+1, num_nodes):
            #if matrix[i][j] > edge_thresh:
            if ma_thresh[i][j] > edge_thresh:
                x1,y1,z1 = nodes[j]
                if weight_edges:
                    mlab.plot3d([x0,x1], [y0,y1], [z0,z1],
                            tube_radius=matrix[i][j]/matrix_flat.max(),
                            color=(1,1,1))
                else:
                    mlab.plot3d([x0,x1], [y0,y1], [z0,z1],
                            tube_radius=edge_radius,
                            color=(1,1,1))
Пример #5
0
 def draw_pontoons(self, fig, truss, R, freeboard):
     from mayavi import mlab
     nE = truss.shape[0]
     c = (0.5,0,0)
     for k in xrange(nE):
         if np.any(truss[k,2,:] > freeboard): continue
         mlab.plot3d(truss[k,0,:], truss[k,1,:], truss[k,2,:], color=c, tube_radius=R, figure=fig)
Пример #6
0
def drawArrows(file1, file2, figure, bbox, index, descendant):
    """
    Draw an 'arrow' from the cell 'index' to 'descendant'
    'descendant' is assumed to be a 1D np.array with size 0, 1 or 2.
    """
    #load the center of mass position
    if descendant.size > 0 and descendant[0] != 0:
        com1 = file1["features"][str(index[0])]["com"][:]
        com2 = file2["features"][str(descendant[0])]["com"][:]
        
        #write the cell label as text
        mlab.text3d(com1[2]-bbox[2]+1,com1[1]-bbox[1]+1,com1[0]-bbox[0]+1, str(index), color=(1,1,1), figure=figure)
        
        #plot a point where the current cell is
        mlab.points3d([com1[2]-bbox[2]+1],[com1[1]-bbox[1]+1],[com1[0]-bbox[0]+1],color=(0,0,1), figure=figure)
                
        #plot a line to the descendant's center
        mlab.plot3d([com1[2]-bbox[2]+1,com2[2]-bbox[2]+1],
                    [com1[1]-bbox[1]+1,com2[1]-bbox[1]+1],
                    [com1[0]-bbox[0]+1,com2[0]-bbox[0]+1],
                    tube_radius=0.2, color=(1,0,0), figure=figure)
        
        #plot a second line, if there is a split
        if descendant.size == 2:
            com3 = file2["features"][str(descendant[1])]["com"][:]
            mlab.plot3d([com1[2]-bbox[2]+1,com3[2]-bbox[2]+1],
                        [com1[1]-bbox[1]+1,com3[1]-bbox[1]+1],
                        [com1[0]-bbox[0]+1,com3[0]-bbox[0]+1],
                        tube_radius=0.2, color=(1,0,0), figure=figure)
Пример #7
0
    def draw_column(self, fig, centerline, freeboard, h_section, r_nodes, spacingVec=None, ckIn=None):
        from mayavi import mlab
        npts = 20

        nsection = h_section.size
        z_nodes = np.flipud( freeboard - np.r_[0.0, np.cumsum(np.flipud(h_section))] )

        th = np.linspace(0, 2*np.pi, npts)
        for k in xrange(nsection):
            rk = np.linspace(r_nodes[k], r_nodes[k+1], npts)
            z  = np.linspace(z_nodes[k], z_nodes[k+1], npts)
            R, TH = np.meshgrid(rk, th)
            Z, _  = np.meshgrid(z, th)
            X = R*np.cos(TH) + centerline[0]
            Y = R*np.sin(TH) + centerline[1]

            # Draw parameters
            if ckIn is None:
                ck = (0.6,)*3 if np.mod(k,2) == 0 else (0.4,)*3
            else:
                ck = ckIn
            #ax.plot_surface(X, Y, Z, alpha=0.5, color=ck)
            mlab.mesh(X, Y, Z, opacity=0.7, color=ck, figure=fig)

            if spacingVec is None: continue
            
            z = z_nodes[k] + spacingVec[k]
            while z < z_nodes[k+1]:
                rk = np.interp(z, z_nodes[k:], r_nodes[k:])
                #ax.plot(rk*np.cos(th), rk*np.sin(th), z*np.ones(th.shape), 'r', lw=0.25)
                mlab.plot3d(rk*np.cos(th) + centerline[0], rk*np.sin(th) + centerline[1], z*np.ones(th.shape), color=(0.5,0,0), figure=fig)
                z += spacingVec[k]
                
                '''
Пример #8
0
def lorenz_plot(name, N=10, res=2000, step=2, t=10, seed_=120):
    # Select initial conditions
    seed(seed_)
    x0 = -15 + 30 * np.random.rand(N, 3)

    # Solve for the trajectories
    t = np.linspace(0, t, res)
    pts = np.empty((N, res, 3))
    for i, x in enumerate(x0):
        pts[i] = odeint(lorenz_ode, x, t)

    # Select the colors for the different curves.
    colors = np.zeros((N, 3))
    colors[:,1] = np.linspace(0, 1, N)
    colors = map(tuple, colors.tolist())

    # Plot the different trajectories.
    for x, color in zip(pts, colors):
        mlab.plot3d(x[:,0], x[:,1], x[:,2], tube_radius=.2, color=color)

    # Position the camera.
    mlab.gcf().scene.camera.position = np.array([165.40890060328016, -140.77357847515529, 8.2574865327247622]) / 1.55
    mlab.gcf().scene.camera.focal_point = [-1.7792501449584961, -3.6287221908569336, 23.397351264953613]
    mlab.gcf().scene.camera.view_up = [-0.078467260964232038, -0.20339450183237351, 0.97594752194015633]
    mlab.gcf().scene.camera.clipping_range = [128.64624663718814, 328.22549479639167]

    # Save the plot.
    mlab.savefig(name)
    mlab.clf()
Пример #9
0
def plotOrs(*ptss):

    mlab.figure(34); mlab.clf()

    r = 1
    phi, theta = mgrid[0:pi:101j, 0:2*pi:101j]
    
    x = r*sin(phi)*cos(theta)
    y = r*sin(phi)*sin(theta)
    z = r*cos(phi)

    
    mlab.mesh(x,y,z, colormap='gray',opacity=.2)
    
    
    
    colors = [(1,0,0),(0,1,0),(0,0,1)]
    print len(colors)
    print len(ptss)
    for (pts,col) in izip(ptss,colors):
        print col        
        ors = normr(pts)
        # Create a sphere
        
        x,y,z = ors.T
        
        mlab.points3d(x,y,z,color=col)
        mlab.plot3d(x,y,z,color=col,tube_radius=.025)
Пример #10
0
def save_spline(f, end_label, line_label, size, pnts, slabels):

  llist = [] # get list of line indicies
  for t in np.where(pnts['label']==end_label)[0]: # find the end points
    ijk = pnts['ijk'][t].tolist()  # get end point indices
    slabels['hit'][tuple(ijk)] = 0 # clear end point hits
  next_point(slabels, ijk, end_label, line_label, llist) # walk from the last end point
 
  points = np.zeros((len(llist[0]), len(llist))) # indicies -> point coordinates
  for i in range(len(llist)): 
    #points[:,i] = i2xyz(llist[i], size)
    points[0,i] = 8 * 0.069 * (llist[i][0] + 0.5)
    points[1,i] = 8 * 0.069 * (llist[i][1] + 0.5)
    points[2,i] = 0.798 * (llist[i][2] + 0.5)

  s = 15.0 # smoothness parameter
  k = 3 # b-spline order
  nest = -1 # estimate of number of knots needed (-1 = maximal)
  tckp,u = splprep(points, s=s, k=k, nest=-1) # find b-spline knot points
  xnew,ynew,znew = splev(np.linspace(0, 1, 30), tckp) # interpolate smooth points

  f.write(str(len(xnew))+" ")
  for i in range(len(xnew)):
    f.write("%2.4f %2.4f %2.4f "% (xnew[i], ynew[i], znew[i]))
  f.write('\n')

  import mayavi.mlab as mylab
  mylab.plot3d(points[0], points[1], points[2], color=(1,0,0))
  mylab.plot3d(xnew, ynew, znew, color=(0,1,0))
  mylab.show()
  return
Пример #11
0
def show_lidar_with_boxes(pc_velo, objects, calib,
                          img_fov=False, img_width=None, img_height=None): 
    ''' Show all LiDAR points.
        Draw 3d box in LiDAR point cloud (in velo coord system) '''
    if 'mlab' not in sys.modules: import mayavi.mlab as mlab
    from viz_util import draw_lidar_simple, draw_lidar, draw_gt_boxes3d

    print(('All point num: ', pc_velo.shape[0]))
    fig = mlab.figure(figure=None, bgcolor=(0,0,0),
        fgcolor=None, engine=None, size=(1000, 500))
    if img_fov:
        pc_velo = get_lidar_in_image_fov(pc_velo, calib, 0, 0,
            img_width, img_height)
        print(('FOV point num: ', pc_velo.shape[0]))
    draw_lidar(pc_velo, fig=fig)

    for obj in objects:
        if obj.type=='DontCare':continue
        # Draw 3d bounding box
        box3d_pts_2d, box3d_pts_3d = utils.compute_box_3d(obj, calib.P) 
        box3d_pts_3d_velo = calib.project_rect_to_velo(box3d_pts_3d)
        # Draw heading arrow
        ori3d_pts_2d, ori3d_pts_3d = utils.compute_orientation_3d(obj, calib.P)
        ori3d_pts_3d_velo = calib.project_rect_to_velo(ori3d_pts_3d)
        x1,y1,z1 = ori3d_pts_3d_velo[0,:]
        x2,y2,z2 = ori3d_pts_3d_velo[1,:]
        draw_gt_boxes3d([box3d_pts_3d_velo], fig=fig)
        mlab.plot3d([x1, x2], [y1, y2], [z1,z2], color=(0.5,0.5,0.5),
            tube_radius=None, line_width=1, figure=fig)
    mlab.show(1)
Пример #12
0
def plot_tree(rrt):
    from mayavi import mlab
    tree = rrt.tree
    leafs = [i for i in tree.nodes() if len(tree.successors(i)) == 0]
    accounted = set()
    paths = []

    for leaf in leafs:
        this_node = leaf
        this_path = []
        paths.append(this_path)
        while True:
            this_path.append(this_node)
            accounted.add(this_node)
            p = tree.predecessors(this_node)
            if len(p) == 0:
                break
            assert len(p) == 1
            this_node = p[0]
            if this_node in accounted:
                this_path.append(this_node) #repeat branching node
                break

    for p in paths:
        s = np.array([rrt.tree.node[i]['state'] for i in p])
        c = np.array([rrt.tree.node[i]['cost'] for i in p])
        mlab.plot3d(s[:,0],s[:,1],s[:,2]/50,c,tube_radius=0.002,colormap='Spectral')
Пример #13
0
def plotDensity(mToB,coeffs,n=100,plotVals="real",plotBnd=True):
    """Plot boundary density with Mayavi
    
       INPUT:
       mToB     - Mesh-to-Basis map
       coeffs   - Coefficients of boundary density
       n        - Discretisation points per element (default 100)
       plotVals - "real", "imag" or "abs" for real/imaginary part or absolute values
                  (default "real")
       plotBnd  - Also plot boundary of shape (default True)
    """

    from mayavi import mlab

    transforms={"real":numpy.real,"imag":numpy.imag,"abs":numpy.abs}
    
    x,f=evalDensity(mToB,coeffs,n)    
    f=transforms[plotVals](f)
                    
    xmin=min(x[0])
    xmax=max(x[0])
    ymin=min(x[1])
    ymax=max(x[1])
    zmin=max([-1,min(f)])
    zmax=min([1,max(f)])
    extent=[xmin,xmax,ymin,ymax,zmin,zmax]
    ranges=[xmin,xmax,ymin,ymax,min(f),max(f)]
    
    fig=mlab.figure(bgcolor=(1,1,1))
    mlab.plot3d(x[0],x[1],f,extent=extent,color=(0,0,0),tube_radius=None,figure=fig)
    if plotBnd:
        mlab.plot3d(x[0],x[1],numpy.zeros(x[0].shape),extent=[xmin,xmax,ymin,ymax,0,0],tube_radius=None,figure=fig)
    mlab.axes(extent=extent,ranges=ranges,line_width=3.0,figure=fig)
    mlab.show()
Пример #14
0
def show_matches(pc1, pc2, samples1, samples2, matches, tube_radius=0.0003, N=50):
    axis = 0
    diff = 1
    bbx = utils.compute_bounding_box_std(pc1)
    pc1[:, axis] -= (bbx[axis][1] - bbx[axis][0])*1.5
    samples1[:, axis] -= (bbx[axis][1] - bbx[axis][0])*1.5
    pc2[:, axis] += (bbx[axis][1] - bbx[axis][0])*1.5
    samples2[:, axis] += (bbx[axis][1] - bbx[axis][0])*1.5
    show_pc(pc1, pc2)
    assert(samples1.shape[0] == samples2.shape[0] == matches.shape[0])
    if matches.shape[0] > N:
        samples11 = samples1[matches[0:N,0].astype(dtype=np.int16)]
        samples22 = samples2[matches[0:N,1].astype(dtype=np.int16)]
    else:
        samples11 = samples1[matches[:,0].astype(dtype=np.int16)]
        samples22 = samples2[matches[:,1].astype(dtype=np.int16)]
    assert (samples11.shape == samples22.shape)
    line = np.zeros((2, 3))
    i = 0
    correct = 0
    wrong = 0
    for sample1, sample2 in zip(samples11, samples22):
        line[0] = sample1
        line[1] = sample2
        if matches[i,0] == matches[i, 1]:
            mlab.plot3d(line[:, 0], line[:, 1], line[:, 2], color=(0, 1, 0), tube_radius=tube_radius)
            correct += 1
        else:
            mlab.plot3d(line[:, 0], line[:, 1], line[:, 2], color=(1, 0, 0), tube_radius=tube_radius)
            wrong += 1
        i += 1
    print 'correct: ', float(correct) / (correct + wrong), '    worng: ', float(wrong) / (correct + wrong)
    mlab.show()
    return -1
Пример #15
0
 def plotLines(self, X, color=None, size=None, scalars=None):
     
     if self.autoRemove: self.removeLines()
     
     if isinstance(X, list):
         Ndim = 3
     else:
         Ndim = len(X.shape)
     
     if color==None: color=(1,0,0)
     
     #~ data.scene.disable_render = True
     #~ view = data.scene.mlab.view()
     #~ roll = data.scene.mlab.roll()
     #~ move = data.scene.mlab.move()
     
     if Ndim==2:
         if scalars==None:
             self.lines.append(mlab.plot3d(X[:,0], X[:,1], X[:,2], color=color, tube_radius=size))
         else:
             self.lines.append(mlab.plot3d(X[:,0], X[:,1], X[:,2], scalars, tube_radius=size))
     elif Ndim==3:
         for x in X:
             if scalars==None:
                 self.lines.append(mlab.plot3d(x[:,0], x[:,1], x[:,2], color=color, tube_radius=size))
             else:
                 self.lines.append(mlab.plot3d(x[:,0], x[:,1], x[:,2], scalars, tube_radius=size))
Пример #16
0
def save_poly(fname, lines):
  fname += "_poly.txt"
  f = open(fname, 'w')
  print ' ', fname
  for line in lines:
    points = calc_points(line)
    #spoints = bspline(points, n=points.shape[0], degree=20)
    ##m = len(points)
    m = len(points)/2
    if m<4: continue
    kx = 3
    ##if(m>3): kx = 3
    ##else: kx = m-1
    wx = np.ones(len(points))
    wx[0] = wx[-1] = 100
    tck,u=si.splprep(np.transpose(points),w=wx,k=kx,s=10)
    ##m /= 2
    ##if(m<4) : m=4
    spoints = np.transpose([si.splev(np.linspace(0,1,m),tck)])
    f.write("%2d " % m) 
    for spoint in spoints:
      for vert in spoint:
        f.write("%0.2f " % vert)
    f.write('\n')
    mylab.plot3d(points[:,0], points[:,1], points[:,2], color=(1,0,0))   
    mylab.plot3d(spoints[:,0], spoints[:,1], spoints[:,2], color=(0,1,0))
  f.close()
  mylab.show()
  return
Пример #17
0
def plot_eclipse(a,b,c,color=(1,1,1)):
    zs=np.linspace(-c*0.95,c*0.95,10)
    for z0 in zs:
        theta=np.linspace(0,pi*2,num=30)
        r=(1-z0**2/c**2)/(np.cos(theta)**2/a**2+np.sin(theta)**2/b**2)
        r=r**0.5
        mlab.plot3d(r*np.cos(theta),r*np.sin(theta),np.ones_like(r)*z0,color=color,tube_radius=None)
Пример #18
0
def plot_matrix_metric(connectmat_file,centers_file,threshold_pct,grp_metrics=None,node_metric='bc',
                       weight_edges=0,node_scale_factor=2,edge_radius=.5,resolution=8,name_scale_factor=1,names_file=0,
                       red_nodes=None):
    """
    Given a connectivity matrix and a (x,y,z) centers file for each region, plot the 3D network
    """
    matrix=core.file_reader(connectmat_file)
    nodes=core.file_reader(centers_file)
    if names_file:
        names = core.file_reader(names_file,1)
    num_nodes = len(nodes)
    edge_thresh_pct = threshold_pct / 100.0
    matrix_flat=np.array(matrix).flatten()
    edge_thresh=np.sort(matrix_flat)[len(matrix_flat)-int(len(matrix_flat)*edge_thresh_pct)]
    
    if grp_metrics: # regional metrics caclulated elsewhere, loaded in
        node_colors = {}     # define colors for each metric
        node_colors['s'] = (1,  0.733,  0)
        node_colors['cc'] = (0.53, 0.81, 0.98)
        node_colors['bc'] = (0.5,  1,  0)
        node_colors['eloc'] = (1,  0 ,  1)
        node_colors['ereg'] = (1,  1,  0)
        
        node_metrics={}
        metrics = np.array(core.file_reader(grp_metrics))
        cols = np.shape(metrics)[1]
        for i in range(cols):
            colmean = np.mean(metrics[:,i])
            colscale = 2 / colmean
            metrics[:,i] = metrics[:,i] * colscale # make node mean size 2
        node_metrics['s'] = metrics[:,0] # strength
        node_metrics['cc'] = metrics[:,1] # clustering coefficient
        node_metrics['bc'] = metrics[:,2] # betweenness centrality
        node_metrics['eloc'] = metrics[:,3] # local efficiency
        node_metrics['ereg'] = metrics[:,4] # regional efficiency
    
    mlab.figure(bgcolor=(1, 1, 1), size=(800, 800))
    for count,(x,y,z) in enumerate(nodes):
        if grp_metrics:
            mlab.points3d(x,y,z, color=node_colors[node_metric],
                          scale_factor=node_metrics[node_metric][count], resolution=resolution)
        else:
            mlab.points3d(x,y,z, color=(0,1,0), scale_factor=node_scale_factor, resolution=resolution)
        if names_file:
            mlab.text(x, y,names[count], z=z,width=.02*name_scale_factor*len(names[count]),color=(0,0,0))
    
    for i in range(num_nodes-1):    
        x0,y0,z0=nodes[i]
        for j in range(i+1, num_nodes):
            if matrix[i][j] > edge_thresh:
                x1,y1,z1=nodes[j]
                if weight_edges:
                    mlab.plot3d([x0,x1], [y0,y1], [z0,z1],
                            tube_radius=matrix[i][j]/matrix_flat.max(),
                            color=(1,1,1))
                else:
                    mlab.plot3d([x0,x1], [y0,y1], [z0,z1],
                            tube_radius=edge_radius,
                            color=(1,1,1))
Пример #19
0
    def plot_3D_spectrum(self, xmin=None, xmax=None, xN=None, ymin=None,
                         ymax=None, yN=None, trajectory=False, tube_radius=1e-2,
                         part='imag'):
        """Plot the Riemann sheet structure around the EP.

            Parameters:
            -----------
                xmin, xmax: float
                    Dimensions in x-direction.
                ymin, ymax: float
                    Dimensions in y-direction.
                xN, yN: int
                    Number of sampling points in x and y direction.
                trajectory: bool
                    Whether to include a projected trajectory of the eigenbasis
                    coefficients.
                part: str
                    Which function to apply to the eigenvalues before plotting.
                tube_radius: float
                    Trajectory tube thickness.
        """
        from mayavi import mlab

        X, Y, Z = self.sample_H(xmin, xmax, xN, ymin, ymax, yN)
        Z0, Z1 = [Z[..., n] for n in (0, 1)]

        def get_min_and_max(*args):
            data = np.concatenate(*args)
            return data.min(), data.max()

        surf_kwargs = dict(colormap='Spectral', mask=np.diff(Z0.real) > 0.015)

        mlab.figure(0)
        Z_min, Z_max = get_min_and_max([Z0.real, Z1.real])
        mlab.surf(X.real, Y.real, Z0.real, vmin=Z_min, vmax=Z_max, **surf_kwargs)
        mlab.surf(X.real, Y.real, Z1.real, vmin=Z_min, vmax=Z_max, **surf_kwargs)
        mlab.axes(zlabel="Re(E)")

        mlab.figure(1)
        Z_min, Z_max = get_min_and_max([Z0.imag, Z1.imag])
        mlab.mesh(X.real, Y.real, Z0.imag, vmin=Z_min, vmax=Z_max, **surf_kwargs)
        mlab.mesh(X.real, Y.real, Z1.imag, vmin=Z_min, vmax=Z_max, **surf_kwargs)
        mlab.axes(zlabel="Im(E)")

        if trajectory:
            x, y = self.get_cycle_parameters(self.t)
            _, c1, c2 = self.solve_ODE()

            for i, part in enumerate([np.real, np.imag]):
                e1, e2 = [part(self.eVals[:, n]) for n in (0, 1)]
                z = map_trajectory(c1, c2, e1, e2)
                mlab.figure(i)
                mlab.plot3d(x, y, z, tube_radius=tube_radius)
                mlab.points3d(x[0], y[0], z[0],
                              # color=line_color,
                              scale_factor=1e-1,
                              mode='sphere')

        mlab.show()
Пример #20
0
def draw_line(pt_1, pt_2, color=(1.0, 0.0, 0.0)):
    """Draw a line between two points"""
    mlab.plot3d(
        np.hstack([pt_1[0], pt_2[0]]),
        np.hstack([pt_1[1], pt_2[1]]),
        np.hstack([pt_1[2], pt_2[2]]),
        color=color
    )
Пример #21
0
    def line(self,n,p,c=None,l=1,o=1,w=0.1): 
        s = np.linspace(0,l)
        l = [p+e*n for e in s]

        xs = [e[0] for e in l]
        ys = [e[1] for e in l]
        zs = [e[2] for e in l]
        mlab.plot3d(xs,ys,zs,figure=self.fig,color=c,opacity=o)
Пример #22
0
def find_path_through_point_cloud(xyzs, plotting=False):
    xyzs = np.asarray(xyzs).reshape(-1, 3)
    S = skeletonize_point_cloud(xyzs)
    segs = get_segments(S)

    if plotting:
        from mayavi import mlab

        mlab.figure(1)
        mlab.clf()
        plot_graph_3d(S)

    S, segs = prune_skeleton(S, segs)

    if plotting:
        from mayavi import mlab

        mlab.figure(3)
        mlab.clf()
        plot_graph_3d(S)

    segs3d = [np.array([S.node[i]["xyz"] for i in seg]) for seg in segs]

    if plotting:
        plot_paths_2d(segs3d)

    C = make_cost_matrix(segs3d)
    PG = make_path_graph(C, [len(path) for path in segs3d])

    (score, nodes) = longest_path_through_segment_graph(PG)
    print nodes

    total_path = []
    for node in nodes[::2]:
        if node % 2 == 0:
            total_path.extend(segs[node // 2])
        else:
            total_path.extend(segs[node // 2][::-1])

    total_path_3d = remove_duplicate_rows(np.array([S.node[i]["xyz"] for i in total_path]))
    total_path_3d = unif_resample(total_path_3d, seg_len=0.02, tol=0.003)  # tolerance of 1mm
    total_path_3d = unif_resample(total_path_3d, seg_len=0.02, tol=0.003)  # tolerance of 1mm
    #    total_path_3d = unif_resample(total_path_3d, seg_len=.02, tol=.003) # tolerance of 1mm

    if plotting:
        mlab.figure(2)
        mlab.clf()
        for seg in segs3d:
            x, y, z = np.array(seg).T
            mlab.plot3d(x, y, z, color=(0, 1, 0), tube_radius=0.001)
        x, y, z = np.array(total_path_3d).T
        mlab.plot3d(x, y, z, color=(1, 0, 0), tube_radius=0.01, opacity=0.2)

        x, y, z = np.array(xyzs).reshape(-1, 3).T
        mlab.points3d(x, y, z, scale_factor=0.01, opacity=0.1, color=(0, 0, 1))

    return total_path_3d
Пример #23
0
    def _show3(self, color_range=True):

        X = self[["x", "y", "z"]].values

        if color_range:
            t = np.linspace(0, 100, len(X))
            mlab.plot3d(X[:, 0], X[:, 1], X[:, 2], -t, colormap="gist_gray")
        else:
            mlab.plot3d(X[:, 0], X[:, 1], X[:, 2], color=(0, 0, 0))
Пример #24
0
    def _show3(self,color_range=True,linewidth=0.01):

        X=self[['x','y','z']].values

        if color_range:
            t = np.linspace(0, 100, len(X))
            mlab.plot3d(X[:,0],X[:,1],X[:,2],-t,colormap='gist_gray',tube_radius=linewidth)
        else:
            mlab.plot3d(X[:,0],X[:,1],X[:,2],color=(0,0,0),tube_radius=linewidth)
Пример #25
0
    def _show3(self,color_range=True):

        X=self[['x','y','z']].values

        if color_range:
            t = np.linspace(0, 100, len(X))
            mlab.plot3d(X[:,0],X[:,1],X[:,2],-t,colormap='gist_gray')
        else:
            mlab.plot3d(X[:,0],X[:,1],X[:,2],color=(0,0,0))
Пример #26
0
def plot3d():
    num = np.pi / 1000
    pts = np.arange(0, 2 * np.pi + num, num)
    x = np.cos(pts) * (1 + np.cos(pts * 6))
    y = np.sin(pts) * (1 + np.cos(pts * 6))
    z = np.sin(pts * 6 / 11)
    mlab.plot3d(x, y, z)
    mlab.savefig("plot3d.png", size=png_size)
    mlab.clf()
Пример #27
0
def plot_tracks(trk_file):
    """
    Plot streamlines from a DSI Studio .txt tracks file
    """
    trks = core.file_reader(trk_file)
    ta = np.array(trks)
    for t in ta:
        tl = len(t)
        trs = np.reshape(t, (tl/3,3))
        mlab.plot3d(trs[:,0], trs[:,1], trs[:,2])
Пример #28
0
def plotvMF(mu,tau,pi,figm,color=(1.,0.0,0.0)):
  X,Y,Z = S2.mesh(1.)
  q = np.c_[X.ravel(),Y.ravel(),Z.ravel()].T
  pdf = pi*np.exp(mu.T.dot(q)*tau)*tau/(4*np.pi*np.sinh(tau)) +1.
  X*=np.reshape(pdf,X.shape)
  Y*=np.reshape(pdf,X.shape)
  Z*=np.reshape(pdf,X.shape)

  mlab.mesh(X,Y,Z,color=color,opacity=0.3,figure=figm,mode='2dtriangle')
  mlab.plot3d([0,mu[0]],[0,mu[1]],[0,mu[2]],color=color,opacity=0.9,figure=figm)
Пример #29
0
def view_bonds(mol,doshow=True):
    from mayavi import mlab
    for i,j in mol.bonds():
        mlab.plot3d([mol.atoms[i].r[0], mol.atoms[j].r[0]],
                    [mol.atoms[i].r[1], mol.atoms[j].r[1]],
                    [mol.atoms[i].r[2], mol.atoms[j].r[2]],
                    tube_radius=0.2,
                    tube_sides=20)
    if doshow: mlab.show()
    return
Пример #30
0
def plot_trajectory(td, trial_index, state_indices):
    prob = integrator_chains.Problem.loadJSONdict(td['trials'][trial_index]['problem_instance'])
    state_dim = prob.output_dim*prob.number_integrators

    try:
        traj = np.array(td['trials'][trial_index]['trajectory'])
    except KeyError:
        print('Trial '+str(trial_index)+' does not have an associated trajectory.')
        sys.exit(-1)

    if state_indices.strip() == '':
        state_indices = []
    else:
        state_index_bounds = (2+prob.output_dim, 2+prob.output_dim+state_dim-1)
        state_indices = _get_index_list(state_indices, state_index_bounds)
        if state_indices is None:
            print('One of the requested state indices is out of bounds, '
                  '[0, '+str(state_index_bounds[1]-state_index_bounds[0])+']')
            sys.exit(-1)

    if len(state_indices) == 0:
        print('Try `--state` option to select indices for plotting.')
        sys.exit(0)

    x = traj[:,state_indices]
    if len(state_indices) == 2:
        import matplotlib.pyplot as plt
        plt.plot(x.T[0], x.T[1], 'r.-')
        plt.plot(x.T[0][0], x.T[1][0], 'r*')
        plt.show()

    elif len(state_indices) == 3:
        from mayavi import mlab

        # mlab.plot3d() of Mayavi fails if there are repetitions of rows,
        # so we first manually delete any.
        y = np.zeros((x.shape[0], 3))
        y[0] = x[0]
        i = 1
        for j in range(1, x.shape[0]):
            if (x[j] != x[j-1]).any():
                y[i] = x[j]
                i += 1
        y = y[:(i+1),:]

        mlab.plot3d(y.T[0], y.T[1], y.T[2],
                    color=(1.0, 0.0, 0.0))
        mlab.points3d(y.T[0][0], y.T[1][0], y.T[2][0],
                      color=(1.0, 0.0, 0.0), mode='sphere', opacity=0.5, scale_factor=0.2)
        mlab.show()

    else:
        print('Plotting of trajectories requires selection of 2 or 3 indices.'
              '\nTry `--state` option to select indices for plotting.')
        sys.exit(0)
Пример #31
0
    def show_mpl_heatmap(self, **kwargs):  # pylint: disable=invalid-name,too-many-arguments,too-many-locals,too-many-statements,too-many-branches
        """
        Show a heatmap of the trajectory with matplotlib.
        """
        import numpy as np
        from scipy import stats
        try:
            from mayavi import mlab
        except ImportError:
            raise ImportError(
                'Unable to import the mayavi package, that is required to'
                'use the plotting feature you requested. '
                'Please install it first and then call this command again '
                '(note that the installation of mayavi is quite complicated '
                'and requires that you already installed the python numpy '
                'package, as well as the vtk package'
            )
        from ase.data.colors import jmol_colors
        from ase.data import atomic_numbers

        # pylint: disable=invalid-name

        def collapse_into_unit_cell(point, cell):
            """
            Applies linear transformation to coordinate system based on crystal
            lattice, vectors. The inverse of that inverse transformation matrix with the
            point given results in the point being given as a multiples of lattice vectors
            Than take the integer of the rows to find how many times you have to shift
            the point back"""
            invcell = np.matrix(cell).T.I
            # point in crystal coordinates
            points_in_crystal = np.dot(invcell, point).tolist()[0]
            #point collapsed into unit cell
            points_in_unit_cell = [i % 1 for i in points_in_crystal]
            return np.dot(cell.T, points_in_unit_cell).tolist()

        elements = kwargs.pop('elements', None)
        mintime = kwargs.pop('mintime', None)
        maxtime = kwargs.pop('maxtime', None)
        stepsize = kwargs.pop('stepsize', None) or 1
        contours = np.array(kwargs.pop('contours', None) or (0.1, 0.5))
        sampling_stepsize = int(kwargs.pop('sampling_stepsize', None) or 0)

        times = self.get_times()
        if mintime is None:
            minindex = 0
        else:
            minindex = np.argmax(times > mintime)
        if maxtime is None:
            maxindex = len(times)
        else:
            maxindex = np.argmin(times < maxtime)
        positions = self.get_positions()[minindex:maxindex:stepsize]

        try:
            if self.get_attribute('units|positions') in ('bohr', 'atomic'):
                bohr_to_ang = 0.52917720859
                positions *= bohr_to_ang
        except KeyError:
            pass

        symbols = self.symbols
        if elements is None:
            elements = set(symbols)

        cells = self.get_cells()
        if cells is None:
            raise ValueError('No cell parameters have been supplied for TrajectoryData')
        else:
            cell = np.array(cells[0])
        storage_dict = {s: {} for s in elements}
        for ele in elements:
            storage_dict[ele] = [np.array([]), np.array([]), np.array([])]
        for iat, ele in enumerate(symbols):
            if ele in elements:
                for idim in range(3):
                    storage_dict[ele][idim] = np.concatenate(
                        (storage_dict[ele][idim], positions[:, iat, idim].flatten())
                    )

        for ele in elements:
            storage_dict[ele] = np.array(storage_dict[ele]).T
            storage_dict[ele] = np.array([collapse_into_unit_cell(pos, cell) for pos in storage_dict[ele]]).T

        white = (1, 1, 1)
        mlab.figure(bgcolor=white, size=(1080, 720))

        for i1, a in enumerate(cell):
            i2 = (i1 + 1) % 3
            i3 = (i1 + 2) % 3
            for b in [np.zeros(3), cell[i2]]:
                for c in [np.zeros(3), cell[i3]]:
                    p1 = b + c
                    p2 = p1 + a
                    mlab.plot3d([p1[0], p2[0]], [p1[1], p2[1]], [p1[2], p2[2]], tube_radius=0.1)

        for ele, data in storage_dict.items():
            kde = stats.gaussian_kde(data, bw_method=0.15)

            _x = data[0, :]
            _y = data[1, :]
            _z = data[2, :]
            xmin, ymin, zmin = _x.min(), _y.min(), _z.min()
            xmax, ymax, zmax = _x.max(), _y.max(), _z.max()

            _xi, _yi, _zi = np.mgrid[xmin:xmax:60j, ymin:ymax:30j, zmin:zmax:30j]  # pylint: disable=invalid-slice-index
            coords = np.vstack([item.ravel() for item in [_xi, _yi, _zi]])
            density = kde(coords).reshape(_xi.shape)

            # Plot scatter with mayavi
            #~ figure = mlab.figure('DensityPlot')
            grid = mlab.pipeline.scalar_field(_xi, _yi, _zi, density)
            #~ min = density.min()
            maxdens = density.max()
            #~ mlab.pipeline.volume(grid, vmin=min, vmax=min + .5*(max-min))
            surf = mlab.pipeline.iso_surface(grid, opacity=0.5, colormap='cool', contours=(maxdens * contours).tolist())
            lut = surf.module_manager.scalar_lut_manager.lut.table.to_array()

            # The lut is a 255x4 array, with the columns representing RGBA
            # (red, green, blue, alpha) coded with integers going from 0 to 255.

            # We modify the alpha channel to add a transparency gradient
            lut[:, -1] = np.linspace(100, 255, 256)
            lut[:, 0:3] = 255 * jmol_colors[atomic_numbers[ele]]
            # and finally we put this LUT back in the surface object. We could have
            # added any 255*4 array rather than modifying an existing LUT.
            surf.module_manager.scalar_lut_manager.lut.table = lut

            if sampling_stepsize > 0:
                mlab.points3d(
                    _x[::sampling_stepsize],
                    _y[::sampling_stepsize],
                    _z[::sampling_stepsize],
                    color=tuple(jmol_colors[atomic_numbers[ele]].tolist()),
                    scale_mode='none',
                    scale_factor=0.3,
                    opacity=0.3
                )

        mlab.view(azimuth=155, elevation=70, distance='auto')
        mlab.show()
def draw_gt_boxes3d(gt_boxes3d,
                    fig,
                    color=(1, 1, 1),
                    line_width=1,
                    draw_text=True,
                    text_scale=(1, 1, 1),
                    color_list=None):
    # gt_boxes3d=np.array([[4.8119, -1.9323, 39.7667],
    #  [3.0897, -1.9323, 39.6927],
    #  [3.0897, -0.1503, 39.6927],
    #  [4.8119, -0.1503, 39.7667],
    #  [4.6423, -1.9323, 43.7183],
    #  [2.9200, -1.9323, 43.6443],
    #  [2.9200, -0.1503, 43.6443],
    #  [4.6423, -0.1503, 43.7183]])
    ''' Draw 3D bounding boxes
    Args:
        gt_boxes3d: numpy array (n,8,3) for XYZs of the box corners
        fig: mayavi figure handler
        color: RGB value tuple in range (0,1), box line color
        line_width: box line width
        draw_text: boolean, if true, write box indices beside boxes
        text_scale: three number tuple
        color_list: a list of RGB tuple, if not None, overwrite color.
    Returns:
        fig: updated fig
    '''
    # gt_boxes3d=np.expand_dims(gt_boxes3d, 0)
    num = len(gt_boxes3d)
    #####33
    # gt_boxes3d=np.swapaxes(gt_boxes3d, 0, 1)
    # temp = np.copy(gt_boxes3d[:, 0])
    # gt_boxes3d[:, 0] = gt_boxes3d[:, 1]
    # gt_boxes3d[:, 1] = temp
    #################################333
    for ar in gt_boxes3d:
        oldar = ar
        temp = np.copy(ar[:, 0])
        ar[:, 0] = ar[:, 2]
        ar[:, 2] = temp
        # ar[:, 1] = temp
        # temp = np.copy(ar[:, 2])
        # ar[:, 2] = ar[:, 1]
        # ar[:, 1] = temp
    ############3
    for n in range(num):
        b = gt_boxes3d[n]
        if color_list is not None:
            color = color_list[n]
        if draw_text:
            mlab.text3d(b[4, 0],
                        b[4, 1],
                        b[4, 2],
                        '%d' % n,
                        scale=text_scale,
                        color=color,
                        figure=fig)
        for k in range(0, 4):
            # http://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html
            i, j = k, (k + 1) % 4
            mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]],
                        [b[i, 2], b[j, 2]],
                        color=color,
                        tube_radius=None,
                        line_width=line_width,
                        figure=fig)

            i, j = k + 4, (k + 1) % 4 + 4
            mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]],
                        [b[i, 2], b[j, 2]],
                        color=color,
                        tube_radius=None,
                        line_width=line_width,
                        figure=fig)

            i, j = k, k + 4
            mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]],
                        [b[i, 2], b[j, 2]],
                        color=color,
                        tube_radius=None,
                        line_width=line_width,
                        figure=fig)
    # mlab.show()
    # mlab.view(azimuth=180, elevation=70, focalpoint=[ 12.0909996 , -1.04700089, -2.03249991], distance=62.0, figure=fig)
    return fig
               color=None,
               mode='point',
               colormap='gnuplot',
               scale_factor=1,
               figure=fig)
 # draw origin
 mlab.points3d(0, 0, 0, color=(1, 1, 1), mode='sphere', scale_factor=0.2)
 # draw axis
 axes = np.array([
     [2., 0., 0., 0.],
     [0., 2., 0., 0.],
     [0., 0., 2., 0.],
 ],
                 dtype=np.float64)
 mlab.plot3d([0, axes[0, 0]], [0, axes[0, 1]], [0, axes[0, 2]],
             color=(1, 0, 0),
             tube_radius=None,
             figure=fig)
 mlab.plot3d([0, axes[1, 0]], [0, axes[1, 1]], [0, axes[1, 2]],
             color=(0, 1, 0),
             tube_radius=None,
             figure=fig)
 mlab.plot3d([0, axes[2, 0]], [0, axes[2, 1]], [0, axes[2, 2]],
             color=(0, 0, 1),
             tube_radius=None,
             figure=fig)
 mlab.view(azimuth=180,
           elevation=70,
           focalpoint=[12.0909996, -1.04700089, -2.03249991],
           distance=62.0,
           figure=fig)
 ##########################################################################################################
Пример #34
0
def show_lidar_with_depth(
    pc_velo,
    objects,
    calib,
    fig,
    img_fov=False,
    img_width=None,
    img_height=None,
    objects_pred=None,
    depth=None,
    cam_img=None,
    constraint_box=False,
    pc_label=False,
    save=False,
):
    """ Show all LiDAR points.
        Draw 3d box in LiDAR point cloud (in velo coord system) """
    if "mlab" not in sys.modules:
        import mayavi.mlab as mlab
    from viz_util import draw_lidar_simple, draw_lidar, draw_gt_boxes3d

    print(("All point num: ", pc_velo.shape[0]))
    if img_fov:
        pc_velo_index = get_lidar_index_in_image_fov(pc_velo[:, :3], calib, 0,
                                                     0, img_width, img_height)
        pc_velo = pc_velo[pc_velo_index, :]
        print(("FOV point num: ", pc_velo.shape))
    print("pc_velo", pc_velo.shape)
    draw_lidar(pc_velo, fig=fig, pc_label=pc_label)

    # Draw depth
    if depth is not None:
        depth_pc_velo = calib.project_depth_to_velo(depth, constraint_box)

        indensity = np.ones((depth_pc_velo.shape[0], 1)) * 0.5
        depth_pc_velo = np.hstack((depth_pc_velo, indensity))
        print("depth_pc_velo:", depth_pc_velo.shape)
        print("depth_pc_velo:", type(depth_pc_velo))
        print(depth_pc_velo[:5])
        draw_lidar(depth_pc_velo, fig=fig, pts_color=(1, 1, 1))

        if save:
            data_idx = 0
            vely_dir = "data/object/training/depth_pc"
            save_filename = os.path.join(vely_dir, "%06d.bin" % (data_idx))
            print(save_filename)
            # np.save(save_filename+".npy", np.array(depth_pc_velo))
            depth_pc_velo = depth_pc_velo.astype(np.float32)
            depth_pc_velo.tofile(save_filename)

    color = (0, 1, 0)
    for obj in objects:
        if obj.type == "DontCare":
            continue
        # Draw 3d bounding box
        _, box3d_pts_3d = utils.compute_box_3d(obj, calib.P)
        box3d_pts_3d_velo = calib.project_rect_to_velo(box3d_pts_3d)
        print("box3d_pts_3d_velo:")
        print(box3d_pts_3d_velo)

        draw_gt_boxes3d([box3d_pts_3d_velo],
                        fig=fig,
                        color=color,
                        label=obj.type)

    if objects_pred is not None:
        color = (1, 0, 0)
        for obj in objects_pred:
            if obj.type == "DontCare":
                continue
            # Draw 3d bounding box
            _, box3d_pts_3d = utils.compute_box_3d(obj, calib.P)
            box3d_pts_3d_velo = calib.project_rect_to_velo(box3d_pts_3d)
            print("box3d_pts_3d_velo:")
            print(box3d_pts_3d_velo)
            draw_gt_boxes3d([box3d_pts_3d_velo], fig=fig, color=color)
            # Draw heading arrow
            _, ori3d_pts_3d = utils.compute_orientation_3d(obj, calib.P)
            ori3d_pts_3d_velo = calib.project_rect_to_velo(ori3d_pts_3d)
            x1, y1, z1 = ori3d_pts_3d_velo[0, :]
            x2, y2, z2 = ori3d_pts_3d_velo[1, :]
            mlab.plot3d(
                [x1, x2],
                [y1, y2],
                [z1, z2],
                color=color,
                tube_radius=None,
                line_width=1,
                figure=fig,
            )
    mlab.show(1)
Пример #35
0
def plot3d(data,
           xvar,
           yvar,
           zvar,
           fvar,
           ival='Dive',
           day=None,
           filament=None,
           cmap='RdYlBu',
           rev_cmap=True,
           alpha=1,
           cmin=None,
           cmax=None,
           title='',
           temp=None,
           chl=None,
           intdat=None):
    """
    Create 3D curtain plot

    Parameters
    ----------
    data : dataframe
        Pandas dataframe containing the needed data.
    xvar : character
        Name of the x axis variable, in the data dataframe (normally lon - or however longitude is name in the dataframe) .
    yvar : character
        Name of the y axis variable, in the data dataframe  (normally lat - or however latitude is name in the dataframe) .
    zvar : character
        Name of the z axis variable, in the data dataframe (normally a rounded Depth or Pressure value).
    fvar : character
        Name of the variable used for the filling (for example temperature, salinity, Sv1000 or whtaever you want it to be).
    ival : character, optional
        This is a grouping value, if not using 'Dive', make sure to define it. The default is 'Dive'.
    day : dataframe, optional
        Reference to a dataframe containing day/night information, if defined, this will put a bar on top of the plot. The default is None.
    filament : dataframe, optional
        This will put a bar below the plot, for example to delimit certain regions. The default is None.
    cmap : colormap, optional
        Character describing a valid colormap. The default is 'RdYlBu'.
    rev_cmap : boolean, optional
        Define if the colormap should be reversed. The default is True.
    alpha : float, optional
        Sets the transparenct. The default is 1.
    cmin : float, optional
        Define the color scale minimum. The default is None.
    cmax : float, optional
        Define the color scale maximum. The default is None.
    title : character, optional
        Add a title to the plot. The default is ''.
    temp : TYPE, optional
        Add temperature background map. The default is None.
    chl : TYPE, optional
        Add chlorophyll background map. The default is None.
    intdat : TYPE, optional
        DESCRIPTION. The default is None.

    Returns
    -------
    None.

    """
    ne = 0
    #bring x,y,z data into shape, create 3 pivot tables
    x = pd.pivot(data=data.reset_index(),
                 index=ival,
                 columns=zvar,
                 values=xvar)
    y = pd.pivot(data=data.reset_index(),
                 index=ival,
                 columns=zvar,
                 values=yvar)
    z = -pd.pivot(
        data=data.reset_index(), index=ival, columns=zvar, values=zvar)

    #create pivot table with fill value, where ival become the index
    fill = pd.pivot(data=data.reset_index(),
                    index=ival,
                    columns=zvar,
                    values=fvar)

    #define cmax and cmin if they are not given
    if cmax is None:
        cmax = np.ceil(np.nanmax(fill))
    if cmin is None:
        cmin = np.floor(np.nanmin(fill))

    #create a mayavi figure
    fig = mlab.figure(size = (2048,1526),\
                bgcolor = (1,1,1), fgcolor = (0.5, 0.5, 0.5), figure=title)

    #create a mesh from the x,y,z and fill info
    svp = mlab.mesh(x,
                    y,
                    z,
                    scalars=fill,
                    colormap=cmap,
                    opacity=alpha,
                    extent=[0.2, 1, 0.1, 1, 0.22, .69],
                    figure=fig,
                    representation='surface')

    #reverse color map if needed
    if rev_cmap == True:
        svp.module_manager.scalar_lut_manager.reverse_lut = True
    #set color range
    svp.module_manager.scalar_lut_manager.data_range = (cmin, cmax)
    #svp.module_manager.scalar_lut_manager.use_below_range_color = True
    #svp.module_manager.scalar_lut_manager.below_range_color = (0,0,0,0)
    #svp.module_manager.scalar_lut_manager.lut.number_of_colors = 64

    #add colorbar
    cb = mlab.colorbar(object=svp, title=title, orientation='vertical')
    cb.scalar_bar.unconstrained_font_size = True
    cb.label_text_property.font_size = 20
    cb.title_text_property.font_size = 46

    #make plot window
    mlab.gcf()

    #set plot limits
    xmin = x.values[np.isfinite(x.values)].min()
    xmax = x.values[np.isfinite(x.values)].max()
    ymin = y.values[np.isfinite(y.values)].min()
    ymax = y.values[np.isfinite(y.values)].max()
    zmin = z.values[np.isfinite(z.values)].min()
    zmax = z.values[np.isfinite(z.values)].max()

    #change the aesthetics
    ax = mlab.axes(nb_labels=5,
                   xlabel='Longitude',
                   ylabel='Latitude',
                   zlabel='Depth [m]',
                   ranges=[xmin, xmax, ymin, ymax, zmin, zmax])
    ax.axes.font_factor = 0.5
    ax.axes.label_format = '    %6.2f'

    #add day night at top
    if day is not None:
        lut = np.zeros((2, 4))
        lut[1, :] = [0, 0, 0, 100]
        lut[0, :] = [100, 100, 0, 100]
        p3d = mlab.plot3d(day.lon.values,
                          day.lat.values,
                          day['depth'].values,
                          day['numSun'].values,
                          tube_radius=0.001,
                          figure=fig,
                          opacity=1,
                          extent=[0.2, 1, 0.1, 1, 0.695, 0.71])
        p3d.module_manager.scalar_lut_manager.lut.number_of_colors = 2
        p3d.module_manager.scalar_lut_manager.lut.table = lut

    #add line at bottom of plot
    if filament is not None:
        mlab.plot3d(filament.lon.values,
                    filament.lat.values,
                    filament['fildep'].values,
                    filament['numfil'].values,
                    tube_radius=0.01,
                    figure=fig,
                    opacity=1,
                    extent=[0.2, 1, 0.1, 1, 0.19, 0.21],
                    colormap='Set1')

    #add chl background map
    if chl is not None:
        if ne == 0:
            zl = 0.2
        else:
            zl = 0.72
        ne += 1
        x1 = chl.longitude.values.min()
        x2 = chl.longitude.values.max()
        y1 = chl.latitude.values.min()
        y2 = chl.latitude.values.max()
        dx = xmax - xmin
        dy = ymax - ymin
        xl1 = -(xmin - x1) / dx
        xl2 = -(xmax - x2) / dx
        yl1 = -(ymin - y1) / dy
        yl2 = -(ymax - y2) / dy

        zs = pd.pivot_table(data=chl,
                            index='latitude',
                            columns='longitude',
                            values='chlorophyll').transpose()
        #cmap2 =  matplotlib.cm.get_cmap()
        #cmap2.set_bad('white',1.)
        sat1 = mlab.imshow(
            zs,
            figure=fig,
            extent=[0.2 + xl1, 1 + xl2, 0.1 + yl1, 1 + yl2, zl, zl],
            opacity=0.8,
            colormap=cmap,
            interpolate=False)
        sat1.module_manager.scalar_lut_manager.reverse_lut = True
        sat1.module_manager.scalar_lut_manager.data_range = (0, 10)
        sat1.module_manager.scalar_lut_manager.lut.nan_color = (0, 0, 0, 0)
        cb2 = mlab.colorbar(object=sat1,
                            title='CHla',
                            orientation='horizontal')
        cb2.scalar_bar.unconstrained_font_size = True
        cb2.label_text_property.font_size = 20
        cb2.title_text_property.font_size = 46

    #add temp backgorund map
    if temp is not None:
        if ne == 0:
            zl = 0.2
        else:
            zl = 0.72
        ne += 1

        x1 = temp.longitude.values.min()
        x2 = temp.longitude.values.max()
        y1 = temp.latitude.values.min()
        y2 = temp.latitude.values.max()
        dx = xmax - xmin
        dy = ymax - ymin
        xl1 = -(xmin - x1) / dx
        xl2 = -(xmax - x2) / dx
        yl1 = -(ymin - y1) / dy
        yl2 = -(ymax - y2) / dy

        zs2 = pd.pivot_table(data=temp,
                             index='latitude',
                             columns='longitude',
                             values='sst').transpose()
        sat2 = mlab.imshow(
            zs2,
            figure=fig,
            extent=[0.2 + xl1, 1 + xl2, 0.1 + yl1, 1 + yl2, zl, zl],
            colormap=cmap,
            opacity=0.8,
            interpolate=False)
        sat2.module_manager.scalar_lut_manager.reverse_lut = True
        sat2.module_manager.scalar_lut_manager.lut.nan_color = (0, 0, 0, 0)
        #sat2.module_manager.scalar_lut_manager.data_range = (10, 25)

    #ignore this, as this was specific for the 38 kHz map for calibration
    if intdat is not None:
        x1 = intdat.Lon_S.values.min()
        x2 = intdat.Lon_S.values.max()
        y1 = intdat.Lat_S.values.min()
        y2 = intdat.Lat_S.values.max()
        dx = xmax - xmin
        dy = ymax - ymin
        xi1 = -(xmin - x1) / dx
        xi2 = -(xmin - x2) / dx
        yi1 = -(ymin - y1) / dy
        yi2 = -(ymin - y2) / dy

        xi = pd.pivot(data=intdat,
                      index='Ping_S',
                      columns='Depth_mean',
                      values='Lon_S')
        yi = pd.pivot(data=intdat,
                      index='Ping_S',
                      columns='Depth_mean',
                      values='Lat_S')
        zi = pd.pivot(data=intdat,
                      index='Ping_S',
                      columns='Depth_mean',
                      values='Depth_mean')

        filli = pd.pivot(data=intdat,
                         index='Ping_S',
                         columns='Depth_mean',
                         values='Sv38')

        ivp = mlab.mesh(xi,
                        yi,
                        zi,
                        scalars=filli,
                        colormap=cmap,
                        opacity=alpha,
                        extent=[xi1, xi2, yi1, yi2, 0.2, .7],
                        figure=fig,
                        representation='surface')
        if rev_cmap == True:
            ivp.module_manager.scalar_lut_manager.reverse_lut = True
        ivp.module_manager.scalar_lut_manager.data_range = (cmin, cmax)

    #set initial view
    mlab.view(90, 110, -2)
Пример #36
0
BEND = pi/6
TWIST = 2*pi



thread = Thread()
xyz0 = thread.getXYZ()
#mlab.plot3d(x,y,z,tube_radius=.4,color=(1,1,1))
mlab.figure(1); mlab.clf()
T = 16

for (t,cons) in enumerate(twists.jumprope2(thread,pi)):
    #twists.twist_ctrl(thread,2*np.pi/T,0)
    thread.setConstraints(cons)
    x,y,z = thread.getXYZ()
    mlab.plot3d(x,y,z,tube_radius=.1,color=(1-t/T,0,t/T))

xyz = np.array([x,y,z])

print twists.opt_rot(xyz,xyz0)
#x,y,z = tips
#mlab.points3d(x,y,z,color=(1,1,1))

for (t,cons) in enumerate(twists.jumprope2(thread,pi)):
    #twists.twist_ctrl(thread,2*np.pi/T,0)
    thread.setConstraints(cons)
    x,y,z = thread.getXYZ()
    mlab.plot3d(x,y,z,tube_radius=.1,color=(0,t/T,1-t/T))

Пример #37
0
import numpy as np
from mayavi import mlab


def lorenz_ode(state, t):
    x, y, z = state
    return np.array(lorenz(x, y, z))


t = np.linspace(0., 50., 2000)
r = odeint(lorenz_ode, (10., 50., 50.), t)

#x, y, z = r[:,0], r[:,1], r[:,2]
x, y, z = r.T
mlab.plot3d(x, y, z, t, tube_radius=None)
Пример #38
0
 def draw(p1, p2, front=1):
     mlab.plot3d([p1[0], p2[0]], [p1[1], p2[1]], [p1[2], p2[2]],
                 color=in_color[names.index(lab) * 2 + front],
                 tube_radius=None,
                 line_width=2,
                 figure=fig)
Пример #39
0
    def add_arrow(self,
                  coords,
                  map_surface=None,
                  tube_radius=3.0,
                  color="white",
                  alpha=1,
                  name=None,
                  hemi=None):
        """
        Add an arrow across the brain between two co-ordinates

        :param coords: list of co-ordinates or (n, 3) numpy array.  Co-ordinate
            space must match that of the underlying MRI image
        :param tube_radius: float
            controls the size of the arrow
        :param color: matplotlib color code
            HTML name, RGB tuple or hex code
        :param alpha: float in [0, 1]
            opacity of coordinate spheres
        :param name: str
            internal name to use
        :param hemi: str | None
            If None, assumed to belong to the hemisphere being shown.
            If two hemispheresa are being shown, an error will be thrown
        """

        hemi = self._check_hemi(hemi)

        if map_surface is None:
            foci_vtxs = surfer.utils.find_closest_vertices(
                self.geo[hemi].coords, coords)
            foci_coords = self.geo[hemi].coords[foci_vtxs]
        else:
            foci_surf = surfer.utils.Surface(self.subject_id,
                                             hemi,
                                             map_surface,
                                             subjects_dir=self.subjects_dir)
            foci_surf.load_geometry()
            foci_vtxs = surfer.utils.find_closest_vertices(
                foci_surf.coords, coords)
            foci_coords = self.geo[hemi].coords[foci_vtxs]

        # foci_vtxs = surfer.utils.find_closest_vertices(self.geo[hemi].coords, coords)
        # foci_coords = self.geo[hemi].coords[foci_vtxs]

        # Convert the color code
        if not isinstance(color, tuple):
            color = colorConverter.to_rgb(color)

        if name is None:
            name = "arrow_%s" % (len(self.arrows_dict) + 1)

        nsegs = 100

        x = np.linspace(foci_coords[0, 0], foci_coords[1, 0], nsegs)
        y = np.linspace(foci_coords[0, 1], foci_coords[1, 1], nsegs)
        z = np.linspace(foci_coords[0, 2], foci_coords[1, 2], nsegs)

        line_coords = np.vstack((x, y, z)).transpose()
        step = 5
        idx_a = range(0, nsegs + 1, step)
        idx_b = range(10, nsegs + 1, step)

        views = self._toggle_render(False)

        al = []

        for brain in self._brain_list:
            if brain['hemi'] == hemi:
                for start, end in zip(idx_a, idx_b):

                    seg_width = tube_radius - (start *
                                               (tube_radius - .5) / 100.)

                    al.append(
                        mlab.plot3d(line_coords[start:end, 0],
                                    line_coords[start:end, 1],
                                    line_coords[start:end, 2],
                                    np.ones_like(line_coords[start:end, 0]),
                                    color=color,
                                    opacity=alpha,
                                    tube_radius=seg_width,
                                    name=name,
                                    figure=brain['brain']._f))

        self.arrows_dict[name] = al

        self._toggle_render(True, views)
Пример #40
0
def draw_lidar(pc,
               color=None,
               fig=None,
               bgcolor=(0, 0, 0),
               pts_scale=1,
               pts_mode='point',
               pts_color=None):
    """
     Draw lidar points
    :param pc: numpy array (n,3) of XYZ
    :param color: numpy array (n) of intensity or whatever
    :param fig: mayavi figure handler, if None create new one otherwise will use it
    :param bgcolor:
    :param pts_scale:
    :param pts_mode:
    :param pts_color:
    :return: created or used fig
    """

    if "mlab" not in sys.modules:
        try:
            import mayavi.mlab as mlab
        except BaseException:
            print("mlab module should be installed")
            return

    if fig is None:
        fig = mlab.figure(figure=None,
                          bgcolor=bgcolor,
                          fgcolor=None,
                          engine=None,
                          size=(1600, 1000))
    if color is None:
        color = pc[:, 2]
    mlab.points3d(pc[:, 0],
                  pc[:, 1],
                  pc[:, 2],
                  color,
                  color=pts_color,
                  mode=pts_mode,
                  colormap='gnuplot',
                  scale_factor=pts_scale,
                  figure=fig)

    # draw origin
    mlab.points3d(0, 0, 0, color=(1, 1, 1), mode='sphere', scale_factor=0.2)

    # draw axis
    axes = np.array([
        [2., 0., 0., 0.],
        [0., 2., 0., 0.],
        [0., 0., 2., 0.],
    ],
                    dtype=np.float64)
    mlab.plot3d([0, axes[0, 0]], [0, axes[0, 1]], [0, axes[0, 2]],
                color=(1, 0, 0),
                tube_radius=None,
                figure=fig)
    mlab.plot3d([0, axes[1, 0]], [0, axes[1, 1]], [0, axes[1, 2]],
                color=(0, 1, 0),
                tube_radius=None,
                figure=fig)
    mlab.plot3d([0, axes[2, 0]], [0, axes[2, 1]], [0, axes[2, 2]],
                color=(0, 0, 1),
                tube_radius=None,
                figure=fig)

    # draw fov Todo: update to real sensor spec.
    fov = np.array(
        [  # 45 degree
            [20., 20., 0., 0.],
            [20., -20., 0., 0.],
        ],
        dtype=np.float64)

    mlab.plot3d([0, fov[0, 0]], [0, fov[0, 1]], [0, fov[0, 2]],
                color=(1, 1, 1),
                tube_radius=None,
                line_width=1,
                figure=fig)
    mlab.plot3d([0, fov[1, 0]], [0, fov[1, 1]], [0, fov[1, 2]],
                color=(1, 1, 1),
                tube_radius=None,
                line_width=1,
                figure=fig)

    # draw square region
    TOP_Y_MIN = -20
    TOP_Y_MAX = 20
    TOP_X_MIN = 0
    TOP_X_MAX = 40
    TOP_Z_MIN = -2.0
    TOP_Z_MAX = 0.4

    x1 = TOP_X_MIN
    x2 = TOP_X_MAX
    y1 = TOP_Y_MIN
    y2 = TOP_Y_MAX
    mlab.plot3d([x1, x1], [y1, y2], [0, 0],
                color=(0.5, 0.5, 0.5),
                tube_radius=0.1,
                line_width=1,
                figure=fig)
    mlab.plot3d([x2, x2], [y1, y2], [0, 0],
                color=(0.5, 0.5, 0.5),
                tube_radius=0.1,
                line_width=1,
                figure=fig)
    mlab.plot3d([x1, x2], [y1, y1], [0, 0],
                color=(0.5, 0.5, 0.5),
                tube_radius=0.1,
                line_width=1,
                figure=fig)
    mlab.plot3d([x1, x2], [y2, y2], [0, 0],
                color=(0.5, 0.5, 0.5),
                tube_radius=0.1,
                line_width=1,
                figure=fig)

    # mlab.orientation_axes()
    mlab.view(azimuth=180,
              elevation=70,
              focalpoint=[12.0909996, -1.04700089, -2.03249991],
              distance=62.0,
              figure=fig)

    return fig
Пример #41
0
    df = np.loadtxt(f)

    r = np.ones(len(df)) * 0.03

    color = (0.2, 0.4, 0.5)
    mlab.points3d(df[:, 0],
                  df[:, 2],
                  df[:, 1],
                  r,
                  color=color,
                  colormap='gnuplot',
                  scale_factor=1,
                  figure=fig)

    mlab.plot3d([0.0, 0.0], [0.0, 0.0], [0.0, CUBE_MAX],
                color=(0, 0, 0),
                tube_radius=None,
                figure=fig)
    mlab.plot3d([0.0, CUBE_MAX], [0.0, 0.0], [0.0, 0.0],
                color=(1, 0, 0),
                tube_radius=None,
                figure=fig)
    mlab.plot3d([0.0, 0.0], [0.0, CUBE_MAX / 2], [0.0, 0.0],
                color=(0, 1, 0),
                tube_radius=None,
                figure=fig)
    mlab.plot3d([0.0, 0.0], [0.0, CUBE_MAX / 2], [CUBE_MAX, CUBE_MAX],
                color=(0, 0, 0),
                tube_radius=None,
                figure=fig)
    mlab.plot3d([0.0, CUBE_MAX], [0.0, 0.0], [CUBE_MAX, CUBE_MAX],
                color=(0, 0, 0),
Пример #42
0
            NR.extend(     np.flatnonzero(particles[:,:,:,i] == 27).tolist() )
            NCX.extend(   np.flatnonzero(particles[:,:,:,i] == 25).tolist() )

Ca   = np.unravel_index(Ca, particles[:,:,:,0].shape )
NR   = np.unravel_index(NR, particles[:,:,:,0].shape )
PMCA = np.unravel_index(PMCA, particles[:,:,:,0].shape )
NCX  = np.unravel_index(NCX, particles[:,:,:,0].shape )


print('Num Ca    : ', Ca[0].shape[0])
print('Num PMCA  : ', PMCA[0].shape[0])
print('Num NMDAR : ', NR[0].shape[0])
# plot_points1 = mlab.points3d(Ca[0], Ca[1], Ca[2], color=(0,0,1), scale_factor=2.0,line_width=0.1)
plot_points2 = mlab.points3d(NR[0], NR[1], NR[2], color=(1,0,0), scale_factor=2.0,line_width=0.1)
# plot_points3 = mlab.points3d(PMCA[0], PMCA[1], PMCA[2], color=(0,1,0), scale_factor=2.0,line_width=0.1)

#
xvnum,yvnum,zvnum = particles[:,:,:,0].shape
Zoff = 0
xvnum = xvnum / 2
voxel_length = 50
length = voxel_length*pitch
text = "{0:.1f} um".format(length)
mlab.plot3d( [xvnum,xvnum],[0,voxel_length],[Zoff,Zoff],color=(0.7,0.7,0.7),tube_radius=2.5)
mlab.text3d( xvnum, voxel_length, Zoff-30, text, scale=10,color=(0.2,0.2,0.2))
# 0.02 um x 100

mlab.savefig(output_file)
mlab.show()

Пример #43
0
 def lineplot(x, y, z, colormap='Spectral', r=0.1, color=(0, 0, 0)):
     mlab.plot3d(x, y, z, tube_radius=r, color=color, colormap=colormap)
Пример #44
0
def plotMF(fig, R, col=None):
    mfColor = []
    mfColor.append((232 / 255.0, 65 / 255.0, 32 / 255.0))  # red
    mfColor.append((32 / 255.0, 232 / 255.0, 59 / 255.0))  # green
    mfColor.append((32 / 255.0, 182 / 255.0, 232 / 255.0))  # tuerkis
    pts = np.zeros((3, 6))
    for i in range(0, 3):
        pts[:, i * 2] = -R[:, i]
        pts[:, i * 2 + 1] = R[:, i]
    if col is None:
        mlab.plot3d(pts[0, 0:2],
                    pts[1, 0:2],
                    pts[2, 0:2],
                    figure=fig,
                    color=mfColor[0])
        mlab.plot3d(pts[0, 2:4],
                    pts[1, 2:4],
                    pts[2, 2:4],
                    figure=fig,
                    color=mfColor[1])
        mlab.plot3d(pts[0, 4:6],
                    pts[1, 4:6],
                    pts[2, 4:6],
                    figure=fig,
                    color=mfColor[2])
    else:
        mlab.plot3d(pts[0, 0:2],
                    pts[1, 0:2],
                    pts[2, 0:2],
                    figure=fig,
                    color=col)
        mlab.plot3d(pts[0, 2:4],
                    pts[1, 2:4],
                    pts[2, 2:4],
                    figure=fig,
                    color=col)
        mlab.plot3d(pts[0, 4:6],
                    pts[1, 4:6],
                    pts[2, 4:6],
                    figure=fig,
                    color=col)
Пример #45
0
        dataPrev = dataCurr
    else:
        print dataPrev, dataCurr
        count = count + 1
        print "-------", i

dataNew = np.array(dataNew)
print type(dataTraj), type(dataNew), count
#print dataNew
x = dataNew[:, 1]
y = dataNew[:, 2]
z = dataNew[:, 3]

#print dataNew
#mlab.points3d(x, y, z) # s, colormap="copper", scale_factor=.25, mode='cube')
mlab.plot3d(x, y, z, tube_radius=0.25,
            color=(1, 0, 0))  #, representation='points')

dataGeom = np.loadtxt("rw3D_Geometry__Hrad_" + strHrad + "__Brad_" + strBrad +
                      "__HARDWALL.csv",
                      dtype=int)

XX = dataGeom[:, 0]
YY = dataGeom[:, 1]
ZZ = dataGeom[:, 2]

mlab.points3d(XX,
              YY,
              ZZ,
              mode='cube',
              color=(210. / 256., 180. / 256., 140. / 256.),
              scale_factor=1.0)
Пример #46
0
    def make_sphere(self):
        """
        Plots Bloch sphere and data sets.
        """
        # setup plot
        # Figure instance for Bloch sphere plot
        from mayavi import mlab
        import matplotlib.colors as colors
        if self.user_fig:
            self.fig = self.user_fig
        else:
            self.fig = mlab.figure(
                1,
                size=self.size,
                bgcolor=colors.colorConverter.to_rgb(self.bgcolor),
                fgcolor=colors.colorConverter.to_rgb(self.fgcolor))

        sphere = mlab.points3d(0,
                               0,
                               0,
                               figure=self.fig,
                               scale_mode='none',
                               scale_factor=2,
                               color=colors.colorConverter.to_rgb(
                                   self.sphere_color),
                               resolution=100,
                               opacity=self.sphere_alpha,
                               name='bloch_sphere')

        # Thse commands make the sphere look better
        sphere.actor.property.specular = 0.45
        sphere.actor.property.specular_power = 5
        sphere.actor.property.backface_culling = True

        # make frame for sphere surface
        if self.frame:
            theta = np.linspace(0, 2 * np.pi, 100)
            for angle in np.linspace(-np.pi, np.pi, self.frame_num):
                xlat = np.cos(theta) * np.cos(angle)
                ylat = np.sin(theta) * np.cos(angle)
                zlat = np.ones_like(theta) * np.sin(angle)
                xlon = np.sin(angle) * np.sin(theta)
                ylon = np.cos(angle) * np.sin(theta)
                zlon = np.cos(theta)
                mlab.plot3d(xlat,
                            ylat,
                            zlat,
                            color=colors.colorConverter.to_rgb(
                                self.frame_color),
                            opacity=self.frame_alpha,
                            tube_radius=self.frame_radius)
                mlab.plot3d(xlon,
                            ylon,
                            zlon,
                            color=colors.colorConverter.to_rgb(
                                self.frame_color),
                            opacity=self.frame_alpha,
                            tube_radius=self.frame_radius)

        # add axes
        axis = np.linspace(-1.0, 1.0, 10)
        other = np.zeros_like(axis)
        mlab.plot3d(axis,
                    other,
                    other,
                    color=colors.colorConverter.to_rgb(self.axes_color),
                    tube_radius=self.axes_radius,
                    opacity=self.axes_alpha)
        mlab.plot3d(other,
                    axis,
                    other,
                    color=colors.colorConverter.to_rgb(self.axes_color),
                    tube_radius=self.axes_radius,
                    opacity=self.axes_alpha)
        mlab.plot3d(other,
                    other,
                    axis,
                    color=colors.colorConverter.to_rgb(self.axes_color),
                    tube_radius=self.axes_radius,
                    opacity=self.axes_alpha)

        # add data to sphere
        self.plot_points()
        self.plot_vectors()

        # #add labels
        mlab.text3d(0,
                    0,
                    self.zlpos[0],
                    self.zlabel[0],
                    color=colors.colorConverter.to_rgb(self.font_color),
                    scale=self.font_scale)
        mlab.text3d(0,
                    0,
                    self.zlpos[1],
                    self.zlabel[1],
                    color=colors.colorConverter.to_rgb(self.font_color),
                    scale=self.font_scale)
        mlab.text3d(self.xlpos[0],
                    0,
                    0,
                    self.xlabel[0],
                    color=colors.colorConverter.to_rgb(self.font_color),
                    scale=self.font_scale)
        mlab.text3d(self.xlpos[1],
                    0,
                    0,
                    self.xlabel[1],
                    color=colors.colorConverter.to_rgb(self.font_color),
                    scale=self.font_scale)
        mlab.text3d(0,
                    self.ylpos[0],
                    0,
                    self.ylabel[0],
                    color=colors.colorConverter.to_rgb(self.font_color),
                    scale=self.font_scale)
        mlab.text3d(0,
                    self.ylpos[1],
                    0,
                    self.ylabel[1],
                    color=colors.colorConverter.to_rgb(self.font_color),
                    scale=self.font_scale)
Пример #47
0
                   color=(1, 1, 1),
                   scale_mode='none')

H2 = mlab.points3d(atoms_x[-1:],
                   atoms_y[-1:],
                   atoms_z[-1:],
                   scale_factor=2,
                   resolution=20,
                   color=(1, 1, 1),
                   scale_mode='none')

# The bounds between the atoms, we use the scalar information to give
# color
mlab.plot3d(atoms_x,
            atoms_y,
            atoms_z, [1, 2, 1],
            tube_radius=0.4,
            colormap='Reds')

# Display the electron localization function ###################################

# Load the data, we need to remove the first 8 lines and the '\n'
str = ' '.join(file('h2o-elf.cube').readlines()[9:])
data = np.fromstring(str, sep=' ')
data.shape = (40, 40, 40)

source = mlab.pipeline.scalar_field(data)
min = data.min()
max = data.max()
vol = mlab.pipeline.volume(source,
                           vmin=min + 0.65 * (max - min),
Пример #48
0
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D

    fig = plt.figure(figsize=(6, 6), dpi=300)
    ax = plt.subplot(111, projection='3d')

    for xx in e:
        ax.plot(xx[:, 0], xx[:, 1], xx[:, 2], color='k', lw=1.0)

    ax.set_xlim(-b1, b1)
    ax.set_ylim(-b2, b2)
    ax.set_zlim(-b3, b3)

    plt.show()

    from mayavi import mlab
    fig = mlab.figure(bgcolor=(1, 1, 1), size=(800, 800))

    bz_line_width = b1 / 200

    for xx in e:
        mlab.plot3d(xx[:, 0],
                    xx[:, 1],
                    xx[:, 2],
                    tube_radius=bz_line_width,
                    color=(0, 0, 0))

    mlab.orientation_axes()
    mlab.show()
def dataset_viz(show_frustum=False):  
    sunrgbd = sunrgbd_object(data_dir)
    idxs = np.array(range(1,len(sunrgbd)+1))
    np.random.shuffle(idxs)
    for idx in range(len(sunrgbd)):
        data_idx = idxs[idx]
        print('--------------------', data_idx)
        pc = sunrgbd.get_depth(data_idx)
        print(pc.shape)
        
        # Project points to image
        calib = sunrgbd.get_calibration(data_idx)
        uv,d = calib.project_upright_depth_to_image(pc[:,0:3])
        print(uv)
        print(d)
        raw_input()
        
        import matplotlib.pyplot as plt
        cmap = plt.cm.get_cmap('hsv', 256)
        cmap = np.array([cmap(i) for i in range(256)])[:,:3]*255
        
        img = sunrgbd.get_image(data_idx)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 
        for i in range(uv.shape[0]):
            depth = d[i]
            color = cmap[int(120.0/depth),:]
            cv2.circle(img, (int(np.round(uv[i,0])), int(np.round(uv[i,1]))), 2, color=tuple(color), thickness=-1)
        Image.fromarray(img).show() 
        raw_input()
        
        # Load box labels
        objects = sunrgbd.get_label_objects(data_idx)
        print(objects)
        raw_input()
        
        # Draw 2D boxes on image
        img = sunrgbd.get_image(data_idx)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 
        for i,obj in enumerate(objects):
            cv2.rectangle(img, (int(obj.xmin),int(obj.ymin)), (int(obj.xmax),int(obj.ymax)), (0,255,0), 2)
            cv2.putText(img, '%d %s'%(i,obj.classname), (max(int(obj.xmin),15), max(int(obj.ymin),15)), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255,0,0), 2)
        Image.fromarray(img).show()
        raw_input()
        
        # Draw 3D boxes on depth points
        box3d = []
        ori3d = []
        for obj in objects:
            corners_3d_image, corners_3d = utils.compute_box_3d(obj, calib)
            ori_3d_image, ori_3d = utils.compute_orientation_3d(obj, calib)
            print('Corners 3D: ', corners_3d)
            box3d.append(corners_3d)
            ori3d.append(ori_3d)
        raw_input()
        
        bgcolor=(0,0,0)
        fig = mlab.figure(figure=None, bgcolor=bgcolor, fgcolor=None, engine=None, size=(1600, 1000))
        mlab.points3d(pc[:,0], pc[:,1], pc[:,2], pc[:,2], mode='point', colormap='gnuplot', figure=fig)
        mlab.points3d(0, 0, 0, color=(1,1,1), mode='sphere', scale_factor=0.2)
        draw_gt_boxes3d(box3d, fig=fig)
        for i in range(len(ori3d)):
            ori_3d = ori3d[i]
            x1,y1,z1 = ori_3d[0,:]
            x2,y2,z2 = ori_3d[1,:]
            mlab.plot3d([x1, x2], [y1, y2], [z1,z2], color=(0.5,0.5,0.5), tube_radius=None, line_width=1, figure=fig)
        mlab.orientation_axes()
        for i,obj in enumerate(objects):
            print('Orientation: ', i, np.arctan2(obj.orientation[1], obj.orientation[0]))
            print('Dimension: ', i, obj.l, obj.w, obj.h)
        raw_input()
       
        if show_frustum: 
            img = sunrgbd.get_image(data_idx)
            img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 
            for i,obj in enumerate(objects):
                box2d_fov_inds = (uv[:,0]<obj.xmax) & (uv[:,0]>=obj.xmin) & (uv[:,1]<obj.ymax) & (uv[:,1]>=obj.ymin)
                box2d_fov_pc = pc[box2d_fov_inds, :]
                img2 = np.copy(img)
                cv2.rectangle(img2, (int(obj.xmin),int(obj.ymin)), (int(obj.xmax),int(obj.ymax)), (0,255,0), 2)
                cv2.putText(img2, '%d %s'%(i,obj.classname), (max(int(obj.xmin),15), max(int(obj.ymin),15)), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255,0,0), 2)
                Image.fromarray(img2).show()
                
                fig = mlab.figure(figure=None, bgcolor=bgcolor, fgcolor=None, engine=None, size=(1000, 1000))
                mlab.points3d(box2d_fov_pc[:,0], box2d_fov_pc[:,1], box2d_fov_pc[:,2], box2d_fov_pc[:,2], mode='point', colormap='gnuplot', figure=fig)
                raw_input()
Пример #50
0
    coil_R * sin(theta) + ypos,
]).T
#right coil
right_coil = array([
    -z_pitch * theta / (2. * pi) - .1049,
    coil_R * cos(theta) + dx,
    -coil_R * sin(theta) + ypos,
]).T

if __name__ == "__main__":
    ##lower electrode +
    b1 = electrode2(phi0)
    path = get_stuff_coil(dx=b1[0], dy=b1[1], r=.02, d=.08, nturns=12)
    mlab.plot3d(path[:, 0],
                path[:, 1],
                path[:, 2],
                tube_radius=.002,
                color=copper)
    radius = 1.4 * .0254
    d = .04
    dz, dtheta = (d) / 5.0, pi / 50.0
    [z, theta] = mgrid[-d:0 + dz:dz, 0:2 * pi + dtheta * .5:dtheta]
    x = radius * cos(theta) + b1[0]
    y = radius * sin(theta) + b1[1]
    mlab.mesh(x, y, z, color=copper)

    radius = .003
    d = 4.15 * .0254
    dz, dtheta = (d) / 5.0, pi / 50.0
    [z, theta] = mgrid[-d:0 + dz:dz, 0:2 * pi + dtheta * .5:dtheta]
    x = radius * cos(theta) + b1[0]
Пример #51
0
def show_lidar_with_boxes(
    pc_velo,
    objects,
    calib,
    img_fov=False,
    img_width=None,
    img_height=None,
    objects_pred=None,
    depth=None,
    cam_img=None,
):
    """ Show all LiDAR points.
        Draw 3d box in LiDAR point cloud (in velo coord system) """
    if "mlab" not in sys.modules:
        import mayavi.mlab as mlab
    from viz_util import draw_lidar_simple, draw_lidar, draw_gt_boxes3d

    print(("All point num: ", pc_velo.shape[0]))
    fig = mlab.figure(figure=None,
                      bgcolor=(0, 0, 0),
                      fgcolor=None,
                      engine=None,
                      size=(1000, 500))
    if img_fov:
        pc_velo = get_lidar_in_image_fov(pc_velo[:, 0:3], calib, 0, 0,
                                         img_width, img_height)
        print(("FOV point num: ", pc_velo.shape[0]))
    print("pc_velo", pc_velo.shape)
    draw_lidar(pc_velo, fig=fig)
    # pc_velo=pc_velo[:,0:3]

    color = (0, 1, 0)
    for obj in objects:
        if obj.type == "DontCare":
            continue
        # Draw 3d bounding box
        _, box3d_pts_3d = utils.compute_box_3d(obj, calib.P)
        box3d_pts_3d_velo = calib.project_rect_to_velo(box3d_pts_3d)
        print("box3d_pts_3d_velo:")
        print(box3d_pts_3d_velo)

        draw_gt_boxes3d([box3d_pts_3d_velo], fig=fig, color=color)

        # Draw depth
        if depth is not None:
            # import pdb; pdb.set_trace()
            depth_pt3d = depth_region_pt3d(depth, obj)
            depth_UVDepth = np.zeros_like(depth_pt3d)
            depth_UVDepth[:, 0] = depth_pt3d[:, 1]
            depth_UVDepth[:, 1] = depth_pt3d[:, 0]
            depth_UVDepth[:, 2] = depth_pt3d[:, 2]
            print("depth_pt3d:", depth_UVDepth)
            dep_pc_velo = calib.project_image_to_velo(depth_UVDepth)
            print("dep_pc_velo:", dep_pc_velo)

            draw_lidar(dep_pc_velo, fig=fig, pts_color=(1, 1, 1))

        # Draw heading arrow
        _, ori3d_pts_3d = utils.compute_orientation_3d(obj, calib.P)
        ori3d_pts_3d_velo = calib.project_rect_to_velo(ori3d_pts_3d)
        x1, y1, z1 = ori3d_pts_3d_velo[0, :]
        x2, y2, z2 = ori3d_pts_3d_velo[1, :]
        mlab.plot3d(
            [x1, x2],
            [y1, y2],
            [z1, z2],
            color=color,
            tube_radius=None,
            line_width=1,
            figure=fig,
        )
    if objects_pred is not None:
        color = (1, 0, 0)
        for obj in objects_pred:
            if obj.type == "DontCare":
                continue
            # Draw 3d bounding box
            _, box3d_pts_3d = utils.compute_box_3d(obj, calib.P)
            box3d_pts_3d_velo = calib.project_rect_to_velo(box3d_pts_3d)
            print("box3d_pts_3d_velo:")
            print(box3d_pts_3d_velo)
            draw_gt_boxes3d([box3d_pts_3d_velo], fig=fig, color=color)
            # Draw heading arrow
            _, ori3d_pts_3d = utils.compute_orientation_3d(obj, calib.P)
            ori3d_pts_3d_velo = calib.project_rect_to_velo(ori3d_pts_3d)
            x1, y1, z1 = ori3d_pts_3d_velo[0, :]
            x2, y2, z2 = ori3d_pts_3d_velo[1, :]
            mlab.plot3d(
                [x1, x2],
                [y1, y2],
                [z1, z2],
                color=color,
                tube_radius=None,
                line_width=1,
                figure=fig,
            )
    mlab.show(1)
    import mayavi.mlab as mlab
    mlab.figure(1)
    mlab.clf()
    print "nodes"
    for node in xrange(0, tracker_arr.shape[1],
                       max(1, tracker_arr.shape[1] // 30)):
        xyz = tracker_arr[:, node, :]
        good_inds = np.flatnonzero(~np.isnan(xyz[:, 0]))
        if len(good_inds) > 0:
            xyz_good = xyz[good_inds]
            x, y, z = xyz_good.T
            print xyz_good.min(axis=0), xyz_good.max(axis=0)
            mlab.plot3d(x,
                        y,
                        z,
                        np.float32(good_inds) / good_inds.max(),
                        tube_radius=.001,
                        opacity=.3,
                        colormap='Spectral')

    print "markers"
    for node in used_leds:
        xyz = owl_arr[:, node, :]
        good_inds = np.flatnonzero(np.isfinite(xyz[:, 0]))
        good_inds = good_inds[::100]
        if len(good_inds) > 0:
            xyz_good = xyz[good_inds]
            print xyz_good.min(axis=0), xyz_good.max(axis=0)
            x, y, z = xyz_good.T
            mlab.points3d(x,
                          y,
def draw_lidar_simple(pc, location, color=None):
    ''' Draw lidar points. simplest set up. '''
    ##############################################33
    # location=[13,-1,0]

    # mlab.points3d(xmid, ymid, zmid, scale_factor=1.0)
    ################################################

    fig = mlab.figure(figure=None,
                      bgcolor=(0, 0, 0),
                      fgcolor=None,
                      engine=None,
                      size=(1600, 1000))
    # fig=draw_gt_boxes3d(1,fig)
    if color is None: color = pc[:, 2]
    # draw points
    mlab.points3d(pc[:, 0],
                  pc[:, 1],
                  pc[:, 2],
                  color,
                  color=None,
                  mode='point',
                  colormap='gnuplot',
                  scale_factor=1,
                  figure=fig)
    # draw origin
    mlab.points3d(0, 0, 0, color=(1, 1, 1), mode='sphere', scale_factor=0.2)
    # draw axis
    axes = np.array([
        [2., 0., 0., 0.],
        [0., 2., 0., 0.],
        [0., 0., 2., 0.],
    ],
                    dtype=np.float64)
    mlab.plot3d([0, axes[0, 0]], [0, axes[0, 1]], [0, axes[0, 2]],
                color=(1, 0, 0),
                tube_radius=None,
                figure=fig)
    mlab.plot3d([0, axes[1, 0]], [0, axes[1, 1]], [0, axes[1, 2]],
                color=(0, 1, 0),
                tube_radius=None,
                figure=fig)
    mlab.plot3d([0, axes[2, 0]], [0, axes[2, 1]], [0, axes[2, 2]],
                color=(0, 0, 1),
                tube_radius=None,
                figure=fig)
    mlab.view(azimuth=180,
              elevation=70,
              focalpoint=[12.0909996, -1.04700089, -2.03249991],
              distance=62.0,
              figure=fig)
    ###################################################3
    location = [24, 0, 1]
    x_loc = location[0]
    y_loc = location[1]
    z_loc = location[2]
    mlab.points3d(x_loc, y_loc, z_loc, scale_factor=1.0)
    ################################################
    ####################################################3
    mlab.show()

    return fig
Пример #54
0
    #ki = Ry(np.deg2rad(mu)).dot(Rz(np.deg2rad(theta)).dot([k0, 0, 0]))
    ki = np.dot(Rz(np.deg2rad(theta)), np.dot(Ry(np.deg2rad(mu)), [k0, 0, 0]))
    #kf = np.dot(Rz(np.deg2rad(theta)), np.dot(Ry(np.deg2rad(mu)), np.dot(Rz(np.deg2rad(delta)), np.dot(Ry(np.deg2rad(gamma)),[k0, 0, 0]))))
    kf = np.dot(
        Rz(np.deg2rad(delta)),
        np.dot(
            Ry(np.deg2rad(gamma)),
            np.dot(Rz(np.deg2rad(theta)), np.dot(Ry(np.deg2rad(mu)),
                                                 [k0, 0, 0]))))

    #kf = Rz(np.deg2rad(theta-delta)).dot(Ry(np.deg2rad(mu-gamma)).dot([k0, 0, 0]))

    #ki = rsp.RotationMatrix(0, np.deg2rad(mu), np.deg2rad(theta)).dot([k0,0,0])
    #kf = rsp.RotationMatrix(0, np.deg2rad(-gamma), np.deg2rad(delta)).dot([k0,0,0])
    mlab.plot3d([-ki[0], 0], [-ki[1], 0], [-ki[2], 0], color=(0, 0, 1))
    mlab.plot3d([-ki[0], -ki[0] + kf[0]], [-ki[1], -ki[1] + kf[1]],
                [-ki[2], -ki[2] + kf[2]],
                color=(0, 0, 1))

    sphere = mlab.points3d(-ki[0],
                           -ki[1],
                           -ki[2],
                           scale_mode='none',
                           scale_factor=2 * k0,
                           color=(0.67, 0.77, 0.93),
                           resolution=50,
                           opacity=0.7)
    sphere.actor.property.specular = 0.45
    sphere.actor.property.specular_power = 5
    sphere.actor.property.backface_culling = True
Пример #55
0
def draw_grid(x1, y1, x2, y2, fig, tube_radius=None, color=(0.5, 0.5, 0.5)):
    mlab.plot3d([x1, x1], [y1, y2], [0, 0], color=color, tube_radius=tube_radius, line_width=1, figure=fig)
    mlab.plot3d([x2, x2], [y1, y2], [0, 0], color=color, tube_radius=tube_radius, line_width=1, figure=fig)
    mlab.plot3d([x1, x2], [y1, y1], [0, 0], color=color, tube_radius=tube_radius, line_width=1, figure=fig)
    mlab.plot3d([x1, x2], [y2, y2], [0, 0], color=color, tube_radius=tube_radius, line_width=1, figure=fig)
    return fig
Пример #56
0
    def render_platform(self, platform: _robot.Platform, *args, **kwargs):
        # platform position and orientation
        position = platform.pose.linear.position
        dcm = platform.pose.angular.dcm

        # temporary platform loop index
        pidx = kwargs.pop('loop_index', -1)

        # if the platform has a geometry assigned, we will plot the geometry
        # and only add the anchor points to it
        if platform.geometry is not None:
            self.render(platform.geometry,
                        transformation=platform.pose.transformation,
                        name=f'platform {pidx}')
        # otherwise, without a platform geometry, we will triangulate the
        # anchor points and plot the platform shape via that
        else:
            # render bounding box of platform
            if platform.is_cuboid:
                # get original anchors as (K,M) matrix
                anchors = self._extract_coordinates(platform.bi.swapaxes(0, 1))

                # in 3D, we perform delaunay triangulation of the corners and
                # retrieve the convex hull from there
                try:
                    delau = _Delaunay(anchors.T)
                except QhullError as e:
                    warnings.warn(RuntimeWarning(e))
                    return

                edges = delau.convex_hull
                vertices = delau.points

                # ensure vertices are (N,3) arrays
                vertices = _np.pad(vertices,
                                   ((0, 0), (0, 3 - vertices.shape[1])))

                # also rotate and translate the platform anchors
                vertices = (position[:, _np.newaxis] + dcm.dot(vertices.T)).T

                # 3D plot
                # first, plot the mesh of the platform i.e., its volume
                _mlab.triangular_mesh(
                    *self._prepare_plot_coordinates(
                        self._extract_coordinates(vertices.T)), edges,
                    **update_recursive(
                        dict(
                            color=(0, 0, 0),
                            line_width=0.10,
                        ), kwargs))
                # close all edges by appending the first column
                edges = _np.hstack((edges, edges[:, 0, _np.newaxis]))
                # and loop over each edge to plot
                for edge in edges:
                    _mlab.plot3d(
                        *self._prepare_plot_coordinates(vertices[edge, :].T),
                        **update_recursive(
                            dict(
                                color=self._RGB2rgb((13, 13, 13)),
                                line_width=0.10,
                            ), kwargs))

        # render all anchors
        self._render_component_list(
            platform,
            'anchors',
            transformation=platform.pose.transformation,
            platform_index=pidx,
            **kwargs)

        # render reference coordinate system of platform
        self.render_coordinate_system(position,
                                      name=f'platform {pidx}: center')

        # render rotated coordinate system of platform
        if platform.can_rotate:
            self.render_coordinate_system(position,
                                          dcm,
                                          name=f'platform {pidx}')
Пример #57
0
# -*- coding: utf-8 -*-
"""
Created on Wed Jul  5 09:43:18 2017

@author: Administrator
"""

import numpy as np
from mayavi import mlab

#建立数据
n_mer, n_long = 6, 11
dphi = np.pi / 1000.0
phi = np.arange(0.0, 2 * np.pi + 0.5 * dphi, dphi)
mu = phi * n_mer
x = np.cos(mu) * (1 + np.cos(n_long * mu / n_mer) * 0.5)
y = np.sin(mu) * (1 + np.cos(n_long * mu / n_mer) * 0.5)
z = np.sin(n_long * mu / n_mer) * 0.5

#对数据进行可视化
l = mlab.plot3d(x, y, z, np.sin(mu), tube_radius=0.025, colormap='Spectral')
mlab.show()
Пример #58
0

# Integrate the Lorenz equations on the time grid t
#Implements a detailed use of memory space for optimised accuracy, not
#so much speed.
#@nb.jit('float64(float64,float64,float64,float64,float64,float64,float64,float64)',nopython=False)
def int_f(u0=u0, v0=v0, w0=w0, sigma=sigma, beta=beta, rho=rho, tma=tmax, n=n):
    t = np.linspace(0, tmax, n)
    f = odeint(deriv_lorenz, (u0, v0, w0), t, args=(sigma, beta, rho))
    return f


x, y, z = int_f().T
Time = np.linspace(0, tmax, n)

mlab.plot3d(x, y, z, Time, colormap='Spectral', tube_radius=0.3)
mlab.outline(opacity=.4)
mlab.points3d(0, 0, 0, opacity=.5)
mlab.text3d(0, 0, 0, 'Origin')
mlab.points3d(u0, v0, w0, opacity=.5)
mlab.text3d(u0, v0, w0, 't_0')
mlab.points3d(np.sqrt(beta * (rho - 1)),
              np.sqrt(beta * (rho - 1)),
              rho - 1,
              opacity=.5)
mlab.text3d(
    np.sqrt(beta * (rho - 1)) * 1.2, np.sqrt(beta * (rho - 1)), rho - 1, 'C+')
mlab.points3d(-np.sqrt(beta * (rho - 1)),
              -np.sqrt(beta * (rho - 1)),
              rho - 1,
              opacity=.5)
Пример #59
0
    def do_landing_burn(self, goal_position, do_plot=True):
        flight = self.vessel.flight()
        orbit = self.vessel.orbit
        # create a transform for the goal position as an x-up frame
        # TODO: This is lazy and will fail if we are landing at the poles
        x_ax = goal_position / np.linalg.norm(goal_position)
        y_ax = np.cross(x_ax, np.array([0, 0, 1]))
        z_ax = np.cross(x_ax, y_ax)
        y_ax /= np.linalg.norm(y_ax)
        z_ax /= np.linalg.norm(z_ax)
        rot = np.column_stack([x_ax, y_ax, z_ax])
        q = R.from_matrix(rot).as_quat()
        ref_frame = self.conn.space_center.ReferenceFrame.create_relative(
            self.body.reference_frame, position=goal_position, rotation=q)

        # Solve the gfold problem based on current position and velocity
        pos, vel = self.get_position_and_velocity(ref_frame)
        start_time = self.conn.space_center.ut
        config = self.create_gfold_config()
        x, u, gam, z, dt = gfold_test.solve_gfold(config, pos, vel)

        # plot the results
        if do_plot:
            f = mlab.figure(bgcolor=(0, 0, 0))
            points3d([0], [0], [0],
                     scale_factor=200.0,
                     resolution=128,
                     color=(0, 0.5, 0.5))
            s = plot3d(x[0, :],
                       x[1, :],
                       x[2, :],
                       tube_radius=5.0,
                       colormap='Spectral')
            v = quiver3d(x[0, :], x[1, :], x[2, :], u[0, :], u[1, :], u[2, :])
            mlab.axes()
            mlab.show()

        timesteps = np.linspace(0, x.shape[1] * dt, num=x.shape[1])
        f = interp1d(timesteps, x[:], kind='cubic')
        u = interp1d(timesteps, u, kind='cubic')
        gam = interp1d(timesteps, gam, kind='cubic')

        self.autopilot.reference_frame = ref_frame
        self.autopilot.engage()

        context = clive_log.Context("vpstream")
        context.add_text_field("error")
        context.add_text_field("distance")

        while self.vessel.situation != self.conn.space_center.VesselSituation.landed:
            cur_time = self.conn.space_center.ut - start_time
            index_time = cur_time
            try:
                goal_position = f(index_time)
            except ValueError:
                goal_position = f(x.shape[1] * dt)
            pos, vel = self.get_position_and_velocity(ref_frame)
            err = goal_position - np.array([*pos, *vel])

            thrust_vector = np.array([2., 0, 0])
            thrust_vector[1:3] = err[1:3] * 0.015
            thrust_vector[1:3] += err[4:6] * 0.36
            self.autopilot.target_direction = tuple(thrust_vector)
            thrust_vector[0] = 0.0
            thrust_vector *= 0.05
            thrust_vector[0] = err[0] * 2.0
            thrust_vector[0] += err[3] * 4.3
            thrust_vector[0] = np.max((thrust_vector[0], 0))
            throttle = np.linalg.norm(thrust_vector) * 0.01  #0.25
            self.vessel.control.throttle = throttle
            distance = np.linalg.norm(pos)

            context.write_text_field("error", f"Error: {err}")
            context.write_text_field("distance", f"Distance: {distance}")
            context.display()

        self.vessel.control.throttle = 0
Пример #60
0
        for (u, v) in G.edges_iter():
            if edgeskip == 0 or i == edgeskip:
                i = 0
                if not show_between_states:
                    local_traj = np.array(
                        [G.node[u]['state'], G.node[v]['state']])
                else:
                    rrg_data['V'][u]['successors'][v].insert(
                        0, G.node[u]['state'])
                    rrg_data['V'][u]['successors'][v].append(
                        G.node[v]['state'])
                    local_traj = np.array(rrg_data['V'][u]['successors'][v])
                if is3D:
                    mlab.plot3d(local_traj.T[0],
                                local_traj.T[1],
                                local_traj.T[2],
                                color=(0.0, 0.0, 1.0),
                                line_width=0.5)
                    mlab.plot3d([G.node[u]['state'][0], G.node[v]['state'][0]],
                                [G.node[u]['state'][1], G.node[v]['state'][1]],
                                [G.node[u]['state'][2], G.node[v]['state'][2]],
                                color=(0.0, 0.0, 1.0),
                                line_width=0.5)
                else:
                    plt.plot(local_traj.T[0], local_traj.T[1], 'b-')
                    plt.plot([G.node[u]['state'][0], G.node[v]['state'][0]],
                             [G.node[u]['state'][1], G.node[v]['state'][1]],
                             'b.')
            if edgeskip > 0:
                i += 1