def new_figure(self): # Create the figure and the axis self.figure = plt.figure() self.axis = self.figure.add_subplot(1, 1, 1, projection="3d") self.axis.set_title("Trajectory") self.axis.set_xlabel('x') self.axis.set_ylabel('y') self.axis.set_zlabel('z') self.line_ideal = Line3D([], [], [], color="blue", linestyle=':') self.line_real = Line3D([], [], [], color="red", linestyle='-') self.axis.add_line(self.line_ideal) self.axis.add_line(self.line_real) self.axis.set_xlim(self.min_x - 0.2, self.max_x + 0.2) self.axis.set_ylim(self.min_y - 0.2, self.max_y + 0.2) self.axis.set_zlim(self.min_z - 0.2, self.max_z + 0.2) self.line_ideal.set_data(self.desired_x, self.desired_y) self.line_ideal.set_3d_properties(self.desired_z) # Creating the Animation object animation.TimedAnimation.__init__(self, self.figure, interval=self.refreshRate, blit=True)
def __init__(self): fig = plt.figure() ax1 = fig.add_subplot(1, 2, 1, projection="3d") ax2 = fig.add_subplot( 2, 2, 2, ) ax3 = fig.add_subplot(2, 2, 2) self.t = np.linspace(0, 80, 300) self.x = np.cos(2 * np.pi * self.t / 10) self.y = np.sin(2 * np.pi * self.t / 10) self.z = 10 * self.t ax1.set_xlabel('x') ax1.set_ylabel('y') ax1.set_zlabel('z') self.line1 = Line3D([], [], [], color='black') self.line1a = Line3D([], [], [], color='red', linewidth=2) self.line1e = Line3D([], [], [], color='red', marker='o', markeredgecolor='r') ax1.add_line(self.line1) ax1.add_line(self.line1a) ax1.add_line(self.line1e) ax1.set_xlim(-1, 1) ax1.set_ylim(-1, 1) ax1.set_zlim(0, 800) ax2.set_xlabel('y') ax2.set_ylabel('z') self.line2 = Line2D([], [], color='black') self.line2a = Line2D([], [], color='red', linewidth=2) self.line2e = Line2D([], [], color='red', marker='o', markeredgecolor='r') ax2.add_line(self.line2) ax2.add_line(self.line2a) ax2.add_line(self.line2e) ax2.set_xlim(-1, 1) ax2.set_ylim(0, 800) ax3.set_xlabel('x') ax3.set_ylabel('z') self.line3 = Line2D([], [], color='black') self.line3a = Line2D([], [], color='red', linewidth=2) self.line3e = Line2D([], [], color='red', marker='o', markeredgecolor='r') ax3.add_line(self.line3) ax3.add_line(self.line3a) ax3.add_line(self.line3e) ax3.set_xlim(-1, 1) ax3.set_ylim(0, 800) plt.tight_layout() animation.TimedAnimation.__init__(self, fig, interval=50, blit=True)
def __init__(self, xdata, ydata, zdata, **kargs): self._invalidz = False self._zorig = None self._update_path = False self._facecolor = None self._gl_array_idx = kargs.pop('array_idx', None) Line3D.__init__(self, xdata, ydata, zdata, **kargs) ArtGL.__init__(self)
def add_lines_to_objects(self, objects): for i in range(len(objects)): objects[i]['lines'] = { 'position': Line3D([], [], [], color='black'), 'trail': Line3D([], [], [], color='m', linewidth=2), 'body_x': Line3D([], [], [], color='red', linewidth=2), 'body_y': Line3D([], [], [], color='green', linewidth=2), 'body_z': Line3D([], [], [], color='blue', linewidth=2) } return objects
def zoom_orbit(self, ax): """orbit without mars, so we can see earth and spaceship trajectory as they move through space together.""" earth_zoomline = Line3D( list(self.xs_earth), list(self.ys_earth), list(self.zs_earth), color="deepskyblue", ) traj_zoomline = Line3D(self.xs, self.ys, self.zs, color="black") ax.set_title("zoomed in to spaceship") ax.scatter(0, 0, 0, c="gold", marker="o") # Sun ax.add_line(earth_zoomline) ax.add_line(traj_zoomline) ax.set_xlim(min(self.xs), max(self.xs)) ax.set_ylim(min(self.ys), max(self.ys)) ax.set_zlim(min(self.zs), max(self.zs))
def add_gates_to_axis(self, ax, gates): for gate in gates: ax.add_line( Line3D(gate.corners[0, :], gate.corners[1, :], gate.corners[2, :], color='blue', linewidth=3)) return ax
def animate(i): a = Arrow3D([0, M[i, 0]], [0, M[i, 1]], [0, M[i, 2]], mutation_scale=20, lw=4, arrowstyle="-|>", color="b") b = Line3D(M[:i+1, 0], M[:i+1, 1], M[:i+1, 2], linestyle='--', color="red") ax.add_artist(a) ax.add_artist(b) return [a, b]
def create_artists_highlight(self): ''' creates artists used to higlight active elements''' self.background = self.canvas.copy_from_bbox(self.ax.bbox) self.sc_active = self.ax.plot([], [], [], animated=True, marker='o')[0] self.new_edge = Line3D([], [], [], color=self.color_active, lw=self.lw, animated=True) self.ax.add_artist(self.new_edge)
def create_artists_graph(self): '''create and add to self.ax main artrist related to lattice graph''' # initialize vertices self.xyz = self.vertices.coords self.x, self.y, self.z = self.xyz.T self.update_XY_scr() # create vertices if self.sc is not None: # remove previous vertices points self.ax.collections.remove(self.sc) self.sc = self.ax.scatter(self.x, self.y, self.z, marker='o') # create edges if self.USE_COLLECTIONS: if self.edges_lines is not None: # remove previous edges lines for key, edge_col in self.edges_lines.items(): self.ax.collections.remove(edge_col) self.edges_lines = {} for key, edge in self.UC.edges.items(): segments = [ self.xyz[self.edges.source_target[j], :] for j in self.edges.array_ind[key] ] edge_col = Line3DCollection(segments) self.ax.add_collection3d(edge_col) self.edges_lines[key] = edge_col else: if self.edges_lines is not None: # remove previous lines edges for line in self.edges_lines: self.ax.artists.remove(line) self.edges_lines = [] for j in range(len(self.edges.ids)): st = list(self.edges.source_target[j]) line = Line3D(self.x[st], self.y[st], self.z[st]) self.ax.add_artist(line) self.edges_lines.append(line) # create latticeNet if self.latticeNet is not None: # remove previous lattice lines self.ax.collections.remove(self.latticeNet) self.latticeNet = Line3DCollection(self.cluster.latticeLines, linestyle='--', lw=0.2) self.ax.add_collection3d(self.latticeNet) self.v_source_ind, self.v_target_ind = None, None self.v_ind, self.v_active_ind = None, None self.e_ind, self.e_active_ind = None, None self.e_activeDist_ids = []
def __init__(self, A2B, label=None, s=1.0, **kwargs): super(Frame, self).__init__() if "c" in kwargs: kwargs.pop("c") if "color" in kwargs: kwargs.pop("color") self.s = s self.x_axis = Line3D([], [], [], color="r", **kwargs) self.y_axis = Line3D([], [], [], color="g", **kwargs) self.z_axis = Line3D([], [], [], color="b", **kwargs) self.draw_label = label is not None self.label = label if self.draw_label: self.label_indicator = Line3D([], [], [], color="k", **kwargs) self.label_text = Text3D(0, 0, 0, text="", zdir="z") self.set_data(A2B, label)
def show3d(self): """Plot facemarks in 3D projection""" self.clear() if self.facecap.is_detected: pts3d = self.facecap.facemarks['3D'] for i, j in connections: p, q = pts3d[i], pts3d[j] line = Line3D((p[0], q[0]), (p[1], q[1]), (p[2], q[2]), c='green') self.ax.add_line(line) self.ax.scatter(*pts3d.T, c='black', linewidths=0.4, alpha=0.4) elev = cv2.getTrackbarPos('Eval', 'Axes') azim = cv2.getTrackbarPos('Azim', 'Axes') self.rotate_axes(elev, azim) self.imshow('3D Mask')
def __init__(self, H, show_direction=True, n_frames=10, s=1.0, **kwargs): super(Trajectory, self).__init__() self.show_direction = show_direction self.trajectory = Line3D([], [], [], **kwargs) self.key_frames = [Frame(np.eye(4), s=s, **kwargs) for _ in range(n_frames)] if self.show_direction: self.direction_arrow = Arrow3D( [0, 0], [0, 0], [0, 0], mutation_scale=20, lw=1, arrowstyle="-|>", color="k") self.set_data(H)
def add_edge(self): '''create new edge (or not if condition is not fulfilled)''' newEdge_id = self.edges.add_edge(self.v_source_ind, self.v_target_ind) if newEdge_id is not None: if self.USE_COLLECTIONS: segments = [ self.xyz[self.edges.source_target[j], :] for j in self.edges.array_ind[newEdge_id] ] new_edge_col = Line3DCollection(segments, color=self.colors_e[0], lw=self.lw) self.ax.add_collection3d(new_edge_col) self.edges_lines[newEdge_id] = new_edge_col else: for j in self.edges.array_ind[newEdge_id]: edge = self.edges.source_target[j] st = list(edge) line = Line3D(self.x[st], self.y[st], self.z[st], color=self.colors_e[0], lw=self.lw) self.ax.add_artist(line) self.edges_lines.append(line) # deactivate previous active edge if self.e_active_ind is not None: color = self.colors_e[self.UC.edges[self.e_active_ind].type] self.reset_active_e_color(color, self.lw) self.e_active_ind = newEdge_id # activate new edge self.reset_active_e_color(self.color_active, self.lw_active) if self.display_report: print(' added edge: {}'.format(self.UC.edges[newEdge_id])) if self.parent is not None: self.parent.unitCellChanged.emit() self.parent.selectedEdgeChanged.emit(self.e_active_ind) self.v_source_ind = None self.v_target_ind = None
def geo3d(XYZ, CON, axes, color): """Plot the 3d model """ axes.set_xlabel('x') axes.set_ylabel('y') axes.set_zlabel('z') # draw nodes for node, xyz in enumerate(XYZ): axes.scatter(xyz[0], xyz[1], xyz[2], c='k', alpha=1, marker='s') # draw edges for ele, con in enumerate(CON): xs = [XYZ[con[0]][0], XYZ[con[1]][0]] ys = [XYZ[con[0]][1], XYZ[con[1]][1]] zs = [XYZ[con[0]][2], XYZ[con[1]][2]] line = Line3D(xs, ys, zs, linewidth=1.0, color=color) axes.add_line(line)
def __init__(self, tracks, xlim=None, ylim=None, zlim=None, line_kws=None): super().__init__(tracks) tracks = tracks.sort_values(['trackid', 'frame']) tracks['pointid'] = tracks.groupby('trackid').cumcount() tracks['n_pts'] = tracks.groupby('trackid')['trackid'].transform( 'count') # set up keyword arguments line_kws = {} if line_kws is None else line_kws.copy() line_kws.update(animated=True) # compute axis limits xlim = (np.floor(tracks['x'].min()), np.ceil(tracks['x'].max())) if xlim is None else xlim ylim = (np.floor(tracks['y'].min()), np.ceil(tracks['y'].max())) if ylim is None else ylim framelim = (tracks['frame'].min(), tracks['frame'].max()) fig = Figure() FigureCanvasAgg(fig) ax = fig.add_axes([0, 0, 1, 1], projection='3d') ax.set_xlim3d(xlim) ax.set_ylim3d(ylim) ax.set_zlim3d(framelim) lines = { trackid: Line3D([], [], [], **line_kws) for trackid in tracks['trackid'].unique() } self.figure = fig self.ax = ax self._tracks = tracks self._framelim = framelim # artists on plot that will be updated self._lines = lines
def __init__(self, ax, onselect=None, useblit=True, lineprops=None, button=None): LassoSelector.__init__(self, ax, onselect, useblit=useblit, button=button) self.verts = None if lineprops is None: lineprops = dict() if useblit: lineprops['animated'] = True self.line = Line3D([], [], [], **lineprops) self.line.set_visible(False) self.ax.add_line(self.line) self.artists = [self.line]
def visualize(data, a, s, e): plt.figure('3D') ax = plt.gca(projection='3d') plt.ion() for d in data: plt.cla() plt.title('a{}_s{}_e{}'.format(a, s, e)) ax.scatter(d[:,0], d[:,1], d[:,2], c='r') ax.set_xlim(-3, 3) ax.set_ylim(-3, 3) ax.set_zlim(-3, 3) ax.set_zlabel('Z') ax.set_ylabel('Y') ax.set_xlabel('X') for j in range(19): c1 = J[0][j] c2 = J[1][j] ax.add_line(Line3D([d[c1, 0], d[c2, 0]], [d[c1, 1],d[c2, 1]],[d[c1, 2],d[c2, 2]], color='blue')) try: plt.pause(0.05) except Exception: pass
def draw_line(ax, points, **kwargs): """Draw a line segment between multiple points. Parameters ---------- ax : Axes The axes for drawing the line segment. points : (N, D) np.ndarray A list of points between the line is drawn. **kwargs Additional keyword arguments for drawing the line. Returns ------- coll : Line2D or Line3D The created line. Examples -------- >>> from lattpy import plotting >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots() >>> points = np.array([[1, 0], [0.7, 0.7], [0, 1], [-0.7, 0.7], [-1, 0]]) >>> _ = plotting.draw_line(ax, points) >>> ax.margins(0.1, 0.1) >>> plt.show() """ dim = len(points[0]) if dim < 3: line = Line2D(*points.T, **kwargs) elif dim == 3: line = Line3D(*points.T, **kwargs) else: raise ValueError(f"Can't draw line with dimension {dim}") ax.add_line(line) return line
def key_press_callback(self, event): if event.key == 'shift': # Run optimization algorithm. x_wp, y_wp, z_wp, psi_wp = self.waypoints.get_data() x = snap.Trajectory1D(x_wp) y = snap.Trajectory1D(y_wp) z = snap.Trajectory1D(z_wp, der=2) psi = snap.Trajectory1D(psi_wp, der=2) self.xy_lines = [] self.xz_lines = [] self.xyz_lines = [] self.xyz_vectors = [[], []] self.xyz_axis.clear() self.xyz_figure.canvas.draw() print('Running optimization routine...') self.trajectory = snap.QrPath(x, y, z, psi, power=self.power, tilt=self.tilt, guess=self.guess) T = self.trajectory.optimize() tdata = np.arange(0, sum(T), 0.1) xdata = [x(t) for t in tdata] ydata = [y(t) for t in tdata] zdata = [z(t) for t in tdata] self.xy_lines.append( Line2D(xdata, ydata, linestyle='-', marker='', color='b')) self.xz_lines.append( Line2D(xdata, zdata, linestyle='-', marker='', color='b')) self.xyz_lines.append( Line3D(xdata, ydata, zdata, linestyle='-', marker='', color='k')) self.xy_axis.add_line(self.xy_lines[-1]) self.xy_figure.canvas.restore_region(self.xy_background) self.xy_axis.draw_artist(self.xy_lines[-1]) self.xy_figure.canvas.blit(self.xy_axis.bbox) self.xz_axis.add_line(self.xz_lines[-1]) self.xz_figure.canvas.restore_region(self.xz_background) self.xz_axis.draw_artist(self.xz_lines[-1]) self.xz_figure.canvas.blit(self.xz_axis.bbox) self.xyz_axis.add_line(self.xyz_lines[-1]) self.xyz_figure.canvas.restore_region(self.xyz_background) self.xyz_axis.draw_artist(self.xyz_lines[-1]) self.xyz_figure.canvas.blit(self.xyz_axis.bbox) wp_t = [0] for t in T: wp_t.append(wp_t[-1] + t) for t in wp_t: self.xyz_vectors[0].append(Line3D([x(t, d=0), x(t, d=0) + x(t, d=1)], [y(t, d=0), y(t, d=0) + y(t, d=1)], [z(t, d=0), z(t, d=0) + z(t, d=1)], \ color='m', lw=2, marker='o', markeredgecolor='m')) self.xyz_axis.add_line(self.xyz_vectors[0][-1]) self.xyz_figure.canvas.restore_region(self.xyz_background) self.xyz_axis.draw_artist(self.xyz_vectors[0][-1]) self.xyz_figure.canvas.blit(self.xyz_axis.bbox) self.xyz_vectors[1].append(Line3D([x(t, d=0), x(t, d=0) + x(t, d=2)], [y(t, d=0), y(t, d=0) + y(t, d=2)], [z(t, d=0), z(t, d=0) + z(t, d=2)], \ color='c', lw=2, marker='o', markeredgecolor='c')) self.xyz_axis.add_line(self.xyz_vectors[1][-1]) self.xyz_figure.canvas.restore_region(self.xyz_background) self.xyz_axis.draw_artist(self.xyz_vectors[1][-1]) self.xyz_figure.canvas.blit(self.xyz_axis.bbox) self.xyz_lines.append( Line3D(x(t), y(t), z(t), color='w', linestyle='', marker='o', markeredgecolor='k')) self.xyz_axis.add_line(self.xyz_lines[-1]) self.xyz_figure.canvas.restore_region(self.xyz_background) self.xyz_axis.draw_artist(self.xyz_lines[-1]) self.xyz_figure.canvas.blit(self.xyz_axis.bbox) elif event.key == 'z': # Save trajectory to file. datafile = open(self.filename, 'wb') pickle.dump(self.trajectory, datafile) datafile.close() print('Trajectory saved to data file.', end='\n\n') elif event.key == 't': # Toggle waypoint adjustment. self.waypoints.toggle = not self.waypoints.toggle print('Waypoint adjustment toggled.', end='\n\n')
def __init__(self, users, drones, groups, drones_paths, drones_diagrams, coverage, parameters): # Исходные данные self.area_x = parameters['area_x'] self.area_y = parameters['area_y'] self.area_z = parameters['drones_height'] self.users = users self.drones = drones self.drones_paths = drones_paths self.diagrams = drones_diagrams self.coverage = coverage self.max_simulation_time = parameters['max_simulation_time'] self.delta_t = parameters['delta_t'] self.delta_t_vis = 0.1 self.delta_diff = self.delta_t_vis / self.delta_t self.total_time_steps = int(self.max_simulation_time / self.delta_t_vis) self.groups_number = parameters['groups_number'] self.drones_number = parameters['drones_number'] gridsize = (5, 2) self.fig = plt.figure(dpi=100, figsize=(10, 7)) self.ax1 = plt.subplot2grid(gridsize, (0, 0), projection='3d', colspan=2, rowspan=3) self.ax2 = plt.subplot2grid(gridsize, (3, 0), colspan=1, rowspan=2) self.ax3 = plt.subplot2grid(gridsize, (3, 1), colspan=1, rowspan=2) self.ax1.set_xlim(0, self.area_x) self.ax1.set_ylim(0, self.area_y) self.ax1.set_zlim(0, self.area_z) self.ax1.xaxis.set_pane_color((0, 0, 0, 0.01)) self.ax1.yaxis.set_pane_color((0, 0, 0, 0.01)) self.ax1.zaxis.set_pane_color((0, 0, 0, 0.01)) self.ax1.set_zticks(np.arange(0, self.area_z + 10, 10)) self.ax1.set_xlabel("x, m") self.ax1.set_ylabel("y, m") self.ax1.set_zlabel("H, m") self.ax2.set_xlabel("Modelling time, s") self.ax2.set_ylabel("Coverage probability, %") self.ax2.set_xlim( -self.max_simulation_time * 0.05, self.max_simulation_time + self.max_simulation_time * 0.05) self.ax2.set_ylim(-8, 108) self.ax2.grid(alpha=0.3) self.ax3.set_xlabel("Modelling time, s") self.ax3.set_ylabel("Coverage probability, %") self.ax3.grid(alpha=0.3) colors = [ ['#0026FF', '#7C96FF'], # Color 1 in picture ['#FF2100', '#FF7E75'], # Color 2 in picture ['#009E56', '#00E57E'], # Color 3 in picture ['#57007F', '#8D00CE'], # Color 4 in picture ['#FF6A00', '#FFAA10'], # Color 5 in picture ['#0af5f5', '#4cfcfc'], # Color 6 in picture ['#71c78a', '#b5ffca'] # Color 7 in picture ] self.group = groups # Создаем объекты Line3D, в которые передаем координаты всего, что нужно отрисовать, в нулевой момент времени self.groups_leaders_line = [] self.groups_line = [] self.groups_circle = [] self.drones_line = [] self.drones_radius_circle = [] self.drones_path_line = [] self.drones_diagrams_line = [] # self.rad = np.sqrt(26.648092476442518**2 - 18**2) ant = Antenna(parameters) distance_3d = ant.get_distance_on_snr(parameters['snr_threshold']) self.rad = np.sqrt(distance_3d**2 - (parameters['drones_height'] - parameters['users_height'])**2) self.r_angles = np.linspace(0, 2 * np.pi, 30) for g in range(self.groups_number): self.groups_leaders_line.append( Line3D(self.users[0, self.group[g][0], 0], self.users[0, self.group[g][0], 1], self.users[0, self.group[g][0], 2], color=colors[g][0], linestyle='', marker='D')) self.groups_line.append( Line3D(self.users[0, self.group[g][1:], 0], self.users[0, self.group[g][:1], 1], self.users[0, self.group[g][1:], 2], color=colors[g][1], linestyle='', marker='o')) self.ax1.add_line(self.groups_leaders_line[g]) self.ax1.add_line(self.groups_line[g]) for d in range(self.drones_number): self.drones_line.append( Line3D(self.drones[0, d, 0], self.drones[0, d, 1], self.drones[0, d, 2], color='black', linestyle='', marker='o')) self.drones_radius_circle.append( Line3D(self.drones[0, d, 0] + self.rad * np.cos(self.r_angles), self.drones[0, d, 1] + self.rad * np.sin(self.r_angles), 2, color='black', lw=0.5)) self.drones_path_line.append( Line3D([self.drones[0, d, 0], self.drones_paths[0, d, 0]], [self.drones[0, d, 1], self.drones_paths[0, d, 1]], [self.drones[0, d, 2], self.drones_paths[0, d, 2]], color='black', linestyle='--', lw=0.7)) self.ax1.add_line(self.drones_line[d]) self.ax1.add_line(self.drones_radius_circle[d]) self.ax1.add_line(self.drones_path_line[d]) if self.diagrams.size: # Если массив диаграмм не пустой i = 0 for reg in self.diagrams[0]: for line in reg: self.drones_diagrams_line.append( Line3D([line[0][0], line[1][0]], [line[0][1], line[1][1]], [0, 0], color='#550055', lw=0.7)) self.ax1.add_line(self.drones_diagrams_line[i]) i += 1 self.ax2_coverage_x = [0] self.ax2_coverage_y = [self.coverage[0]] self.coverage_line = Line2D(self.ax2_coverage_x, self.ax2_coverage_y) self.ax2.add_line(self.coverage_line) self.ax3_coverage_x = [0] self.ax3_coverage_y = [self.coverage[0]] self.coverage_line_2 = Line2D(self.ax3_coverage_x, self.ax3_coverage_y) self.ax3.add_line(self.coverage_line_2)
def execute(self, si): filenamebase = si.createfilenamebase() #PRR is calculated by PacketMetric, loading it here prr = np.load(filenamebase+"_prr.npy") print "="*40 print "Executing TopologyGraph:" print "filenamebase\t\t", filenamebase print "="*40 fig = plt.figure(figsize=(13,10), subplotpars = SubplotParams(left = 0.05, bottom = 0.05, top = 0.95, right = 0.75)) ax = axes3d.Axes3D(fig, azim = -60, elev = 30) consist = np.zeros(si.nodes) xarr = np.zeros(si.nodes) yarr = np.zeros(si.nodes) zarr = np.zeros(si.nodes) packs = [] ifile = open(filenamebase+"_id2xyz.pickle", "r") id2xyz_dict = pickle.load(ifile) ifile.close() # print id2xyz_dict for id1 in range(1, si.nodes+1): (x, y, z) = id2xyz_dict[id1] xarr[id1-1] = x yarr[id1-1] = y zarr[id1-1] = z # print "x = ",xarr[id1-1] xmin,xmax = ax.get_xlim3d() ymin,ymax = ax.get_ylim3d() zmin,zmax = ax.get_zlim3d() ax.set_xlim3d(0, xmax+1) ax.set_ylim3d(0, ymax+1) ax.set_zlim3d(0, zmax+1) ax.set_xlabel('X [m]') ax.set_ylabel('Y [m]') ax.set_zlabel('Z [m]') ax.scatter(xarr,yarr,zarr,zdir='z') #### Start plotting lines#### for id1 in range(1, si.nodes+1): for id2 in range(1, si.nodes+1): if prr[id1][id2] == 0: linecolor = None alpha = 0.0 if prr[id1][id2] >= 0.5: linecolor = 'b' alpha = 1.0 if prr[id1][id2] >= 0.95: linecolor = 'g' alpha = 1.0 if prr[id1][id2] >= 0.99: linecolor = 'k' alpha = 1.0 (x, y, z) = id2xyz_dict[id1] (x2, y2, z2) = id2xyz_dict[id2] packs.append( Line3D([x, x2], [y, y2], [z, z2], color=linecolor, linewidth=0.5, alpha=alpha) ) text = "#Nodes: " + str(si.nodes) + ", " + \ "Size: " + str(si.distance) plt.title('Topology\n(' + text +')') for p in packs: ax.add_artist(p) p.set_clip_box(ax.bbox) prr_gt_0 = Line2D([0, 0.1], [0, 0.1], color='r', linewidth=0.8) prr_lt_0_5 = Line2D([0,0.1], [0, 0.1], color='b', linewidth=0.8) prr_lt_0_95 = Line2D([0, 0.1], [0, 0.1], color='g', linewidth=0.8) prr_gt_0_99 = Line2D([0, 0.1], [0, 0.1], color='k', linewidth=0.8) plt.legend( (prr_gt_0, prr_lt_0_5, prr_lt_0_95, prr_gt_0_99, ), ('0 < PRR < 0.5', '0.5 < PRR < 0.95', '0.95 < PRR < 0.99', '0.99 < PRR < 1', ), # bbox_to_anchor=(0.05,0.95), # borderaxespad = 0., loc = 2, fancybox = 'True') plt.savefig(filenamebase+"_topology.pdf")
ax.set_aspect('equal') ax.grid() ax.add_line(line1) ax.add_line(line2) ax.add_line(line3) ax.add_line(line4) ax.add_line(line5) fig.canvas.draw() else: ax = fig.add_subplot(111, projection='3d') line1 = Line3D( [], [], [], color='g', ls='-', lw=1.0, # link chain start in 3D marker='o', mew=1.0, mec='k', mfc='g') line2 = Line3D( [], [], [], color='b', ls='-', lw=2.0, # link chain motion in 3D marker='o', mew=1.0, mec='k',
def draw(self, renderer): if isSupportedRenderer(renderer): if self._invalidy or self._invalidx or self._invalidz: self.recache() if self.get_zdata() is None: self._zorig = np.array([0]*len(self.get_xdata())) renderer.use_gl = True glcanvas = get_glcanvas() if self.axes is not None: tag = self.axes trans = self.axes.transAxes elif self.figure is not None: tag = self.figure trans = self.figure.transFpigure glcanvas.frame_request(self, trans) # if not glcanvas.has_vbo_data(self): glcanvas.start_draw_request(self) #3dpath = (self.get_xdata(), self.get_ydata(), self_zdata()) #path = Path(self._xy) if self._invalidz: self.set_3d_properties(zs=self.get_zdata(), zdir='z') if glcanvas.has_vbo_data(self): d = glcanvas.get_vbo_data(self) for x in d: x['v'].need_update = True # path.zvalues = self.get_zdata() self._invalidz = False gc = renderer.new_gc() ln_color_rgba = self._get_rgba_ln_color() gc.set_foreground(ln_color_rgba, isRGBA=True) gc.set_linewidth(self._linewidth) if self._marker.get_marker() == ',': gc.set_linewidth(0) if self._gl_3dpath is None: self.verts3d_to_3dpath() if len(self._gl_3dpath) == 3: renderer.gl_draw_path(gc, self._gl_3dpath, trans, rgbFace = self._facecolor, linestyle = self._linestyle) else: fc = None if self._facecolor is None else [self._facecolor] renderer.gl_draw_path_collection_e( gc, None, self._gl_3dpath, None, self._gl_offset, None, fc, [ln_color_rgba], [self._linewidth], self._linestyle, self._antialiased, self._url, None, lighting = self._gl_lighting, stencil_test = False, view_offset = self._gl_voffset, array_idx = self._gl_array_idx) if len(self._marker.get_path()) != 0: marker_path = None marker_trans = None m_facecolor = self.get_markerfacecolor() m_edgecolor = self.get_markeredgecolor() m_edgewidth = self.get_markeredgewidth() m_size = renderer.points_to_pixels(self._markersize) #marker_path is bitmap (texture) #marker_trans is marker_size and other info (liken marker_every) marker_path = self.update_marker_texture(renderer) marker_trans = (m_size,) renderer.gl_draw_markers(gc, marker_path, marker_trans, self._gl_3dpath[:3], trans, array_idx = self._gl_array_idx) glcanvas.end_draw_request() gc.restore() finish_gl_drawing(glcanvas, renderer, tag, trans) renderer.use_gl = False else: v = Line3D.draw(self, renderer)
def __init__(self, D, C=None, G=None, Gate_objects=None, Camera_object=None, Floor_object=None, fig=None, ax=0, speed=1, fps=25, trail_time=1., axis_length=2., view=(90, -90), equal_lims=25, xlims=None, ylims=None, zlims=None): #past time [sec] highlighting position data with a different color self.trail_time = trail_time #length [m] of quadrotor body axes self.axis_length = axis_length #speed of animation self.speed = speed #frames per second for the visualization self.fps = fps # interval/period in which the data is visualized interval = int(1000 / fps) #in ms #downsample drone data to the visualization sampling rate D = self.downsample(D, fps / speed) #downsample camera data to the visualization sampling rate if C is not None: C = self.downsample(C, fps / speed) print('visualization sampling rate is {:.2f} Hz'.format(fps)) #get the objects to visualize from hierarchical header Pose_objects = self.get_pose_objects( D, Gate_objects) #here add the drone(s) moving objects #add drawable lines for position, trail, body xyz to each object Pose_objects = self.add_lines_to_objects(Pose_objects) #make a figure if fig is None: fig = plt.figure(figsize=(10, 10)) self.ax = fig.add_subplot(1, 1, 1, projection="3d") else: self.ax = fig.axes[ax] #add lines to current axis self.ax = self.add_lines_to_axis(self.ax, Pose_objects) # add static gates to axis if Gate_objects is not None: self.add_gates_to_axis(self.ax, Gate_objects) #add camera frame to axis if (Camera_object is not None) and (C is not None): #make a camera object with position information etc self.camera_object = { 'name': 'camera', 'time': C.ts.values, 'position': C.loc[:, ('cam_pos_x', 'cam_pos_y', 'cam_pos_z')].values, 'rotation': C.loc[:, ('cam_rot_x_quat', 'cam_rot_y_quat', 'cam_rot_z_quat', 'cam_rot_w_quat')].values, 'object': Camera_object, 'line': Line3D([], [], [], color='black') } #add camera object as line to the axis self.ax.add_line(self.camera_object['line']) else: #if no camera data available set this variable to None (important, will be checked in the draw method) self.camera_object = None #add gaze projection to axis if G is not None: ts_trace = G.ts.values ts_drone = D.ts.values idx = [np.argmin(np.abs(ts_trace - _t)) for _t in ts_drone] ts_trace = G.loc[:, ('ts')].iloc[idx].values p_origin = G.loc[:, ('cam_pos_x', 'cam_pos_y', 'cam_pos_z')].iloc[idx].values norm_ray = G.loc[:, ('norm_ray_x', 'norm_ray_y', 'norm_ray_z')].iloc[idx].values p_close_intersect = G.loc[:, ( 'close_intersect_pos_x', 'close_intersect_pos_y', 'close_intersect_pos_z')].iloc[idx].values ind = np.isnan(p_close_intersect[:, 0]).flatten() p_endpoint = p_close_intersect p_endpoint[ind, :] = p_origin[ind, :] + norm_ray[ind, :] * 1000. ray_length = G.loc[:, ('close_intersect_distance')].iloc[idx] ray_length[ind] = 1000. # make a camera object with position information etc self.trace_object = { 'name': 'camera', 'time': ts_trace, 'origin': p_origin, 'endpoint': p_endpoint, 'norm_ray': norm_ray, 'length': ray_length, 'line': Line3D([], [], [], color='cyan') } # add camera object as line to the axis self.ax.add_line(self.trace_object['line']) else: self.trace_object = None #save objects as global variable self.Pose_objects = Pose_objects #save time as global variable self.t = self.Pose_objects[0]['time'] #label the axes self.ax.set_xlabel('X [m]') self.ax.set_ylabel('Y [m]') self.ax.set_zlabel('Z [m]') #set the view self.ax.view_init(elev=view[0], azim=view[1]) #set axis limits #if equal axis limits requested if equal_lims is not None: if isinstance(equal_lims, tuple) or isinstance(equal_lims, list): lims = tuple(equal_lims) else: lims = (-equal_lims, equal_lims) self.ax.set_xlim(lims) self.ax.set_ylim(lims) self.ax.set_zlim(lims) #if individual axis limits or none are requested else: min_vals = np.nanmin(self.Pose_objects[0]['position'], axis=0) max_vals = np.nanmax(self.Pose_objects[0]['position'], axis=0) if xlims is None: xlims = (min_vals[0], max_vals[0]) self.ax.set_xlim(xlims) if ylims is None: ylims = (min_vals[1], max_vals[1]) self.ax.set_ylim(ylims) if zlims is None: zlims = (min_vals[2], max_vals[2]) self.ax.set_zlim(zlims) #make the animation animation.TimedAnimation.__init__(self, fig, interval=interval, repeat=False, blit=False)
def __init__(self, qs, ts, t_final, max_year, ax): eph = get_ephemerides(max_year=max_year) earth = eph["earth"] mars = eph["mars"] # ts is in years, and is as such very small. we scale it to days, to fit with eph days_ts = [(t * UNIT_TIME) / 3600 / 24 for t in ts] qs = [get_position_cartesian_from_spherical(x, y, z) for x, y, z in qs] self.xs, self.ys, self.zs = np.array( qs ).T # get individual coordinate sets for plotting self.t_final = t_final ax.set_title("animation") self.ani_ax = ax xs_earth = [] ys_earth = [] zs_earth = [] xs_mars = [] ys_mars = [] zs_mars = [] for t in days_ts: t_eph = get_ephemerides_on_day(eph, day_index=t) xs_earth.append(t_eph["earth"]["x"]) ys_earth.append(t_eph["earth"]["y"]) zs_earth.append(t_eph["earth"]["z"]) xs_mars.append(t_eph["mars"]["x"]) ys_mars.append(t_eph["mars"]["y"]) zs_mars.append(t_eph["mars"]["z"]) self.xs_earth = xs_earth self.ys_earth = ys_earth self.zs_earth = zs_earth self.xs_mars = xs_mars self.ys_mars = ys_mars self.zs_mars = zs_mars self.earth_xdata = [self.xs_earth[0]] self.earth_ydata = [self.ys_earth[0]] self.earth_zdata = [self.zs_earth[0]] self.earth_line = Line3D( self.earth_xdata, self.earth_ydata, self.earth_zdata, color="deepskyblue" ) self.ani_ax.add_line(self.earth_line) self.mars_xdata = [self.xs_mars[0]] self.mars_ydata = [self.ys_mars[0]] self.mars_zdata = [self.zs_mars[0]] self.mars_line = Line3D( self.mars_xdata, self.mars_ydata, self.mars_zdata, color="orange" ) self.ani_ax.add_line(self.mars_line) self.xdata = [self.xs[0]] self.ydata = [self.ys[0]] self.zdata = [self.zs[0]] self.traj_line = Line3D(self.xdata, self.ydata, self.zdata, color="black") self.ani_ax.add_line(self.traj_line) # -- SUN -- ax.scatter(0, 0, 0, c="gold", marker="o") self.ani_ax.set_xlim(-1.5, 1.5) self.ani_ax.set_ylim(-1.5, 1.5) self.ani_ax.set_zlim(-1, 1) self.ani_terminate = False