class PsdPreview(Preview): def __init__(self, master, dim, lf, hf, dpi=72, label="PSD", Z=None): Preview.__init__(self, master, dim, dpi, label) self.lf = lf self.hf = hf if self.ring: self.createRing() else: self.canvas.draw() def _createAxes(self): #axdef = SubplotZero(self.figure, 111) #ax = self.figure.add_subplot(axdef) ax = self.figure.add_axes([0.1,0.1,0.8,0.8], frameon=False) #ax.xaxis.set_offset_position(0.5) #ax.set_position([0, 0, 1, 1]) h = 0.5 ax.set_xlim(-h, h) ax.set_ylim(-h, h) ax.grid(True) self.ring = None self.img = ax.imshow(self.bg, cmap=cm.gray, extent=[-h, h, -h, h]) self.ax = ax def createRing(self): radius = float(self.hf) width = radius - float(self.lf) self.ring = Wedge((0,0), radius, 0, 360, width=width, alpha=0.15) # Full ring self.ax.add_patch(self.ring) self.canvas.draw() def updateFreq(self, lf, hf): self.lf = lf self.hf = hf if self.ring: self.ring.remove() self.ring = None if self.hf: self.createRing() def _update(self, Z): if self.ring: self.ring.remove() self.ring = None if self.hf: self.createRing() self.img.set_data(Z) self.img.autoscale() self.canvas.draw()
def image_acquisition(num_proj, camera_port=0, wait=0, hsv='v', fancy_out=True): hsv_dict = {'h': 0, 's': 1, 'v': 2} camera = cv2.VideoCapture(camera_port) camera.set(3, 2000) camera.set(4, 2000) try: dims = camera.read()[1][:, :, 2].shape + (num_proj, ) except TypeError: error = ('Camera returning None. Check camera settings (port) and' ' ensure camera is not being run by other software.') raise TypeError(error) im_stack = np.zeros(dims) if fancy_out: fig, ax = plt.subplots(figsize=(4, 4)) fig.canvas.set_window_title('Acquisition') patch = Wedge((.5, .5), .375, 90, 90, width=0.1) ax.add_patch(patch) ax.axis('equal') ax.set_xlim([0, 1]) ax.set_ylim([0, 1]) ax.axis('off') t = ax.text(0.5, 0.5, '0%%', fontsize=15, ha='center', va='center') # Acquires defined number of images (saves slice from hsv) for i in range(num_proj): _, im = camera.read() im_stack[:, :, i] = color.rgb2hsv(im)[:, :, hsv_dict[hsv]] if fancy_out: patch.set_theta1(90 - 360 * (i+1) /num_proj) progress = 100 * (i+1) / num_proj t.set_text('%02d%%' % progress) plt.pause(0.001) else: sys.stdout.write('\rProgress: [{0:20s}] {1:.0f}%'.format('#' * int(20*(i + 1) / num_proj), 100*((i + 1)/num_proj))) sys.stdout.flush() time.sleep(wait) del camera if fancy_out: plt.close() return im_stack
def pie(plot, p, values, colors=None, size=16, norm=True, xoff=0, yoff=0, halign=0.5, valign=0.5, xycoords='data', boxcoords=('offset points')): """ Draw a pie chart Args: plot (Tree): A Tree plot instance p (Node): A Node object values (list): A list of floats. colors (list): A list of strings to pull colors from. Optional. size (float): Diameter of the pie chart norm (bool): Whether or not to normalize the values so they add up to 360 xoff, yoff (float): X and Y offset. Optional, defaults to 0 halign, valign (float): Horizontal and vertical alignment within box. Optional, defaults to 0.5 """ x, y = _xy(plot, p) da = DrawingArea(size, size) r = size * 0.5 center = (r, r) x0 = 0 S = 360.0 if norm: S = 360.0 / sum(values) if not colors: c = _colors.tango() colors = [c.next() for v in values] for i, v in enumerate(values): theta = v * S if v: da.add_artist( Wedge(center, r, x0, x0 + theta, fc=colors[i], ec='none')) x0 += theta box = AnnotationBbox(da, (x, y), pad=0, frameon=False, xybox=(xoff, yoff), xycoords=xycoords, box_alignment=(halign, valign), boxcoords=boxcoords) plot.add_artist(box) plot.figure.canvas.draw_idle() return box
def _draw_patch_out_sets(self, ax, col_num, out_y, radius): for j in range(len(out_y)): # ax.add_patch(Wedge((self.x_values[col_num], out_y[j]-0.1), radius, 180, 360, color=self.greys[0], ec="none")) ax.add_patch( Wedge((self.x_values[col_num], out_y[j] - 0.1), radius, 180, 360, color='g', alpha=0.2, ec="none"))
def draw_geometry(self,a): # inner ring pin=PatchCollection([Wedge((0.,0.), 1.25, phi-3,phi+3, width=0.3) for phi in range(2,360,5)],cmap=plt.cm.bone,edgecolor='white',linewidths=0,zorder=1) pin.set_array(self.innertrack(arange(2,360,5),1)) a.add_collection(pin) # outer ring po=PatchCollection([Wedge((0.,0.), 1.6, phi-3,phi+3, width=0.3) for phi in range(2,360,5)],cmap=plt.cm.bone,edgecolor='white',linewidths=0,zorder=1) po.set_array(self.outertrack(arange(2,360,5),1)) a.add_collection(po) # marbles radii=1.15+0.25*where(np.mod(arange(self.ng),2)==0,0.,1.) c=PatchCollection([Circle((radii[i]*cos(2.*pi*phi/360.),radii[i]*sin(2.*pi*phi/360.)),0.13*(0.75*self.weights[i]/pi)**0.333) for i,phi in enumerate(self.DNA)], cmap=murmelfarbe,zorder=3) c.set_array(arange(self.ng)/(self.ng-1.)) a.add_collection(c) #a.scatter(cos(phi),sin(phi),marker='o',s=100,c=arange(self.ng),cmap=plt.cm.jet,zorder=3) #a.axis([-1.2,1.2,-1.2,1.2],'equal' a.axis('equal') atxt='generation: {0}\nscore: {1:.3f}'.format(self.gg,self.score) a.text(0,0,atxt, ha='center',va='center') #, fontsize=8)
def add_graphene(ax, R_p=20, t_gr=0.67, t_helm=0.3): W = 40 h = t_gr + 2 * t_helm h2 = t_gr facecolor_out = "#fafafa" facecolor_in = "#7c7c7c" rect1 = Rectangle((R_p, -h / 2), W - R_p, h, facecolor=facecolor_out) rect2 = Rectangle((-R_p, -h / 2), -(W - R_p), h, facecolor=facecolor_out) wedge1 = Wedge((R_p, 0), h / 2, 90, 270, facecolor=facecolor_out) wedge2 = Wedge((-R_p, 0), h / 2, -90, 90, facecolor=facecolor_out) rect3 = Rectangle((R_p, -t_gr / 2), W - R_p, t_gr, facecolor=facecolor_in) rect4 = Rectangle((-R_p, -t_gr / 2), -(W - R_p), t_gr, facecolor=facecolor_in) wedge3 = Wedge((R_p, 0), t_gr / 2, 90, 270, facecolor=facecolor_in) wedge4 = Wedge((-R_p, 0), t_gr / 2, -90, 90, facecolor=facecolor_in) for a in [rect1, rect2, wedge1, wedge2, rect3, rect4, wedge3, wedge4]: ax.add_artist(a)
def debug_no_heuristic(self, state, default, switch=True): if switch: (r_mu, r_sigma), (t_mu, t_sigma), (a_mu, a_sigma) = default x, y, a = state[0], state[1], state[2] cir = plt.gca().add_patch( Wedge(center=(x, y), r=r_mu + 2 * r_sigma, width=4 * r_sigma, fill=False, color=(0.5, 0.8, 0.5), theta1=np.degrees(a + t_mu - t_sigma * 2), theta2=np.degrees(a + t_mu + t_sigma * 2))) arr = plt.gca().add_patch( Wedge(center=(x, y), r=1.0, theta1=np.degrees(a + a_mu - a_sigma * 2), theta2=np.degrees(a + a_mu + a_sigma * 2), fill=False, color=(0.5, 0.8, 0.5))) raw_input('gaussian heuristic') self.remove([[cir, arr]])
def draw_geometry(self,a): # draw own look into a, which is a matplotlib axes/subplot instance p=PatchCollection([Wedge((0.,0.), 1.2, phi-3,phi+3, width=0.5) for phi in range(2,360,5)],cmap=plt.cm.bone,edgecolor='white',linewidths=0,zorder=1) p.set_array(self.trackpotential(arange(2,360,5))) a.add_collection(p) c=PatchCollection([Circle((cos(2.*pi*phi/360.),sin(2.*pi*phi/360.)),0.1) for i,phi in enumerate(self.DNA)], facecolor='c',edgecolor='k',linewidths=1.5,zorder=3) a.add_collection(c) a.axis('equal') plt.axis('off') atxt='generation: {0}\nscore: {1:.3f}'.format(self.gg,self.score) a.text(0,0,atxt, ha='center',va='center') #, fontsize=8)
def plot_heuristic(heuristic, color=(0.5, 0.8, 0.5), r=1.0, alpha=0.6): actors = [] for item in heuristic: state, biasing = item # cir = Ellipse(xy=(state[0], state[1]), width=biasing[0][1]*2*2, # height=biasing[1][1]*2*2, color=color, alpha=alpha, fill=False, linewidth=8) arr = Wedge(center=(state[0], state[1]), r=r, theta1=np.degrees(state[2] - biasing[2][1]*2), theta2=np.degrees(state[2] + biasing[2][1]*2), fill=False, color=color, linewidth=8) # actors.append([plt.gca().add_patch(cir), plt.gca().add_patch(arr)]) actors.append([plt.gca().add_patch(arr)]) plt.draw() return actors
def com_symbol(ax, center, radius, color='b'): '''Returns axis with center of mass symbol.''' c = plt.Circle(center, radius=radius, fill=False) w1 = Wedge(center, radius, 0., 90., color=color, ec=None, alpha=0.5) w2 = Wedge(center, radius, 180., 270., color=color, ec=None, alpha=0.5) ax.add_patch(w1) ax.add_patch(w2) ax.add_patch(c) return ax
def redraw_overplot_on_image(self, *args): self.ztv_frame.primary_image_panel.add_patch('phot_panel:star_center_patch', Circle([self.xcentroid, self.ycentroid], 0.125, color=self.aprad_color), no_redraw=True) self.ztv_frame.primary_image_panel.add_patch('phot_panel:star_aperture_patch', Circle([self.xcentroid, self.ycentroid], self.aprad, color=self.aprad_color, alpha=self.alpha), no_redraw=True) self.ztv_frame.primary_image_panel.add_patch('phot_panel:sky_aperture_patch', Wedge([self.xcentroid, self.ycentroid], self.skyradout, 0., 360., width=self.skyradout - self.skyradin, color=self.skyrad_color, alpha=self.alpha), no_redraw=False) self.hideshow_button.SetLabel(u"Hide")
def draw_robot_cone(self, cam_x, cam_y, cam_theta): axes = plt.gca() if self.cone is not None: self.cone.remove() self.cone = Wedge((cam_x, cam_y), 3, math.degrees(cam_theta) - self.h_fov/2, math.degrees(cam_theta) + self.h_fov/2, color="y", alpha=0.2, zorder=10) axes.add_patch(self.cone)
def plot_polar_hist(ax, data, n_bins=30, c=(0, 0), r=1.0, colour="blue"): """Given an axis, plots the polar histogram of the density of the angles""" hist, bins = np.histogram(data, bins=n_bins, density=True) for n in range(n_bins): d = hist[n] t1 = r2d(bins[n]) t2 = r2d(bins[n + 1]) w = Wedge(c, r, t1, t2, alpha=d, color=colour) ax.add_patch(w)
def draw_circles(ax, size, shot_data, averages, teamOrPlayer): """ Args: size (int): the size of the circles for the shot ranges shots (dataframe): the shot chart data of a player or team Returns: None, but plots the shot ranges """ global spotList shot = shot_data # ax = plt.gca() if (len(shot) == 0): return pd.set_option('display.max_columns', None) for spots in range(4 if size == 8 else 6): edge = Arc((0, 0), size * 20 * (spots + 1), size * 20 * (spots + 1), linewidth=1, color='black', alpha=1) cur_min = averages.get_min_list()[spots] cur_max = averages.get_max_list()[spots] cur_average = averages[spots] add_for_player = 3 if teamOrPlayer == "Player" else 0 cur_value = shot.iloc[0, 4 + 3 * spots + add_for_player] set_color = '' if (cur_value >= cur_average): set_color = 'green' cur_value = min( .65 * ((cur_value - cur_average)) / (cur_max - cur_average) + .02, .65) else: set_color = 'red' cur_value = min( .65 * (1 - ((cur_value - cur_min)) / (cur_average - cur_min)) + .02, .65) fill = Wedge((0, 0), size * 10 * (spots + 1), 0, 360, linewidth=0, width=size * 10, color=set_color, alpha=cur_value) spotList.append(edge) ax.add_patch(edge) spotList.append(fill) ax.add_patch(fill) return spotList
def make_patch_list(writer): from matplotlib.path import Path from matplotlib.patches import Circle, PathPatch, Wedge indices = writer.positions[:, 2].argsort() patch_list = [] for a in indices: xy = writer.positions[a, :2] if a < writer.natoms: r = writer.d[a] / 2 if writer.frac_occ: site_occ = writer.occs[writer.tags[a]] # first an empty circle if a site is not fully occupied if (np.sum([v for v in site_occ.values()])) < 1.0: # fill with white fill = '#ffffff' patch = Circle(xy, r, facecolor=fill, edgecolor='black') patch_list.append(patch) start = 0 # start with the dominant species for sym, occ in sorted(site_occ.items(), key=lambda x: x[1], reverse=True): if np.round(occ, decimals=4) == 1.0: patch = Circle(xy, r, facecolor=writer.colors[a], edgecolor='black') patch_list.append(patch) else: # jmol colors for the moment extent = 360. * occ patch = Wedge( xy, r, start, start + extent, facecolor=jmol_colors[atomic_numbers[sym]], edgecolor='black') patch_list.append(patch) start += extent else: if ((xy[1] + r > 0) and (xy[1] - r < writer.h) and (xy[0] + r > 0) and (xy[0] - r < writer.w)): patch = Circle(xy, r, facecolor=writer.colors[a], edgecolor='black') patch_list.append(patch) else: a -= writer.natoms c = writer.T[a] if c != -1: hxy = writer.D[c] patch = PathPatch(Path((xy + hxy, xy - hxy))) patch_list.append(patch) return patch_list
def wedge(radar): """ Make a HF-radar `matplotlib.patches.Wedge` from a StartAngle, SpreadAngle, Center (Longitude, Latitude), and Radius (radar range). """ r = ranges[int(radar["MHz"])] / 111.1 # deg2km theta1, theta2 = radar["StartAngle"], radar["SpreadAngle"] center = radar["Longitude"], radar["Latitude"] try: return Wedge(center, r, theta1 + theta2, theta1) except ValueError: return None
def draw_agent_ig(agent, i, ax): plt_color = plt_colors[i + 1] # colors = np.zeros((agent.global_state_history.shape[0], 4)) # colors[:, :3] = plt_color # colors[:, 3] = np.linspace(0.2, 1., agent.global_state_history.shape[0]) # colors = rgba2rgb(colors) ax.plot(agent.global_state_history[:agent.step_num - 1, 1], agent.global_state_history[:agent.step_num - 1, 2], color=plt_color) plan = agent.policy.best_paths.X[0].pose_seq fov = 60.0 for j in range(len(plan)): if j == 0: continue pose = plan[j] alpha = 1.0 - 0.2 * j c = rgba2rgb(plt_color + [float(alpha)]) heading = pose[2] * 180.0 / np.pi ax.add_patch( Wedge(center=pose[0:2], r=.75, theta1=(heading - fov / 2), theta2=(heading + fov / 2), fc=c, ec=c, fill=True)) # currentPose = agent.global_state_history[agent.step_num-1, (1,2,10)] currentPose = plan[0] heading = currentPose[2] * 180.0 / np.pi ax.add_patch( Wedge(center=currentPose[0:2], r=1., theta1=(heading - fov / 2), theta2=(heading + fov / 2), fc=plt_color, ec=plt_color, fill=True))
def draw_cat(ax): #body poly = [(3, 1), (4, 14), (5, 11), (8, 11), (9, 14), (10, 1)] polygon = Polygon(poly, fc="grey", ec="black", lw=4) ax.add_patch(polygon) #eyes circle = Circle((5.3, 8.5), 1.2, fc="white", ec="black", lw=4) ax.add_patch(circle) circle = Circle((7.7, 8.5), 1.2, fc="white", ec="black", lw=4) ax.add_patch(circle) #eyeballs circle = Circle((6, 8.3), 0.1, fc="black", ec="black", lw=4) ax.add_patch(circle) circle = Circle((7, 8.3), 0.1, fc="black", ec="black", lw=4) ax.add_patch(circle) #nose circle = Circle((6.5, 7.5), 0.3, fc="black", ec="black", lw=4) ax.add_patch(circle) #back legs wedge = Wedge((3, 1), 2, 86, 180, fc="grey", ec="black", lw=4) ax.add_patch(wedge) wedge = Wedge((10, 1), 2, 0, 94, fc="grey", ec="black", lw=4) ax.add_patch(wedge) #front legs ellipse = Ellipse((5.5, 1.2), 2, 1.5, fc="grey", ec="black", lw=4) ax.add_patch(ellipse) ellipse = Ellipse((7.5, 1.2), 2, 1.5, fc="grey", ec="black", lw=4) ax.add_patch(ellipse) #sunshine arc = Arc((6.5, 6.5), 5, 3, 0, 200, 340, lw=4, fill=False) ax.add_patch(arc) #moustache vertices = [(6.5, 5), (6.5, 7.5), (10, 6), (6.5, 7.5), (10, 6.5), (6.5, 7.5), (10, 7), (6.5, 7.5), (3, 6), (6.5, 7.5), (3, 6.5), (6.5, 7.5), (3, 7)] codes = [1, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2] path = Path(vertices, codes) lines = PathPatch(path, fill=False, lw=1) ax.add_patch(lines)
def updateMask(self, outerRadius, innerRadius=0): if self.ring is not None: self.ring.remove() center = self.dim / 2 width = outerRadius - innerRadius self.ring = Wedge((center, center), outerRadius, 0, 360, width=width, alpha=0.15) # Full ring self.ax.add_patch(self.ring) self.canvas.draw()
def wedge(self, path: Path) -> Wedge: """ Generates the patches wedge object corresponding to `path`.""" return Wedge((self.origin[0], self.origin[1]), self._wedge_outer_radius(path), self._angles[path].theta1, self._angles[path].theta2, width=self.wedge_width(path), label=self.format_text(path), facecolor=self.face_color(path), edgecolor=self.edge_color(path), linewidth=self.line_width(path), fill=True, alpha=self.alpha(path))
def plot_circle_plain_state(self): self.subplot.add_patch( Wedge((self.res.center, 0), self.res.max_shear, 0, 360, linewidth=3, edgecolor=self.color_scheme.edgecolor, alpha=0.9, facecolor='black', fill=False)) self.subplot.set_aspect('equal', 'datalim')
def plot_frame(self, idx: int, filename: str): fig, ax = plt.subplots(figsize=self.config["plotting"]["fig_size"]) plt.plot( self.response_vec.real, self.response_vec.imag, label=self.config["plotting"]["response"]["label"], c=self.config["plotting"]["response"]["color"], ) plt.plot( [-1.0, self.response_vec[idx].real], [0.0, self.response_vec[idx].imag], label=self.config["plotting"]["ray"]["label"], c=self.config["plotting"]["ray"]["color"], ) if self.config["plotting"]["axis_equal"]: plt.axis("equal") plt.xlim(*self.config["plotting"]["xlim"]) plt.xlabel(self.config["plotting"]["xlabel"]) plt.ylim(*self.config["plotting"]["ylim"]) plt.ylabel(self.config["plotting"]["ylabel"]) plt.grid(self.config["plotting"]["grid"]) plt.legend() smaller_angle = np.min(self.ray_angle[[0, idx]]) larger_angle = np.max(self.ray_angle[[0, idx]]) wedge = Wedge( (-1.0, 0.0), self.config["plotting"]["wedge"]["radius"], smaller_angle, larger_angle, ) patches = [wedge] patches.extend( Circle((-1.0, 0.0), self.config["plotting"]["wedge"]["radius"]) for _ in range(int(self.angle_change[idx] / 360.0))) pc = PatchCollection( patches, facecolors=[self.config["plotting"]["wedge"]["color"]], alpha=self.config["plotting"]["wedge"]["alpha"], ) title = (self.config["plotting"]["title_string"].replace( "{frequency}", f"{self.frequency_vec[idx]:.2e}").replace( "{angle_change}", f"{self.angle_change[idx]:.2f}")) plt.title(title) ax.add_collection(pc) fig.savefig( self.output_dir / filename, bbox_inches="tight", pad_inches=self.config["plotting"]["export"]["pad_inches"], dpi=self.config["plotting"]["export"]["dpi"], ) plt.close()
def atualizar_setor(setor: Wedge, abertura_min: float) -> [Wedge]: """Atualiza os valores de theta e opacidade do setor, movimentando-o""" global glob_multip_alpha # O valor de theta = valor atual + incremento (Se a soma não ultrapassar 360) # Se a soma ultrapassar 360, o valor será o resto da divisão (soma / 360) setor.set_theta1((setor.theta1 + glob_increm_ang) % 360) setor.set_theta2(setor.theta1 + abertura_min) # Se a opacidade do setor for maior que 0.4 ou for menor que o valor mínimo: # inverta de incremento para decremento ou vice-versa if setor.get_alpha() >= 0.4 or setor.get_alpha() < glob_incremento_alpha: glob_multip_alpha = (-1) * glob_multip_alpha setor.set_alpha(setor.get_alpha() + glob_incremento_alpha * glob_multip_alpha) return [setor]
def loop_matplotlib(tank): """This function uses adding and removing patches to animate the bike.""" plt.ion() # enables interactive plotting paths = tank.paths fig = plt.figure() ax = plt.axes(**find_display_bounds(tank.waypoints)) lc = mc.LineCollection(paths, linewidths=2, color="blue") ax.add_collection(lc) plt.show() # For plotting the bicycle axes = plt.gca() # Holds past locations of the bike, for plotting bike_trajectory = [(tank.x, tank.y)] # We need to keep this around to clear it after path updates path_patch = None prev_bike_patch = None prev_lookahead_patch = None # Main animation loop while True: if path_patch: path_patch.remove() path_patch = PathPatch(Path(bike_trajectory), fill=False, linewidth=2) axes.add_patch(path_patch) # Plot the bike as a wedge pointing in the direction bike.psi if prev_bike_patch: prev_bike_patch.remove() bike_heading = tank.heading * (180 / math.pi) # Converted to degrees wedge_angle = 45 # The angle covered by the wedge bike_polygon = Wedge((tank.x, tank.y), 0.3, bike_heading - wedge_angle / 2 + 180, bike_heading + wedge_angle / 2 + 180, fc="black") axes.add_patch(bike_polygon) prev_bike_patch = bike_polygon fig.canvas.flush_events() bike_trajectory.append((tank.x, tank.y)) speed, yaw_dot = tank.get_nav_command() tank.step(speed, yaw_dot) plt.ioff() plt.show()
def PieArray(axes, x_array, y_loc, radius, counts_array, colormap, **kwargs): for x, counts in zip(x_array, counts_array): total_count = sum(counts.itervalues()) axes.text(x, y_loc + radius + 0.05, str(total_count), ha='center') theta_1 = 0 for i, (key, value) in enumerate(counts.iteritems()): color = colormap[key] sweep = (float(value) / float(total_count)) * 360.0 w = Wedge((x,y_loc), radius, theta_1, theta_1 + sweep, color=color, label=key) theta_1 += sweep axes.add_patch(w) return True
def draw_geometry(self,a): # draw own look into a, which is a matplotlib axes/subplot instance p=PatchCollection([Wedge((0.,0.), 1.2, phi-3,phi+3, width=0.5) for phi in range(2,360,5)],cmap=plt.cm.bone,edgecolor='white',linewidths=0,zorder=1) p.set_array(self.trackpotential(arange(2,360,5),1)) a.add_collection(p) c=PatchCollection([Circle((cos(2.*pi*phi/360.),sin(2.*pi*phi/360.)),0.2*(0.75*self.weights[i]/pi)**0.333) for i,phi in enumerate(self.DNA)], cmap=murmelfarbe,zorder=3) c.set_array(arange(self.ng)/(self.ng-1.)) a.add_collection(c) #a.scatter(cos(phi),sin(phi),marker='o',s=100,c=arange(self.ng),cmap=plt.cm.jet,zorder=3) #a.axis([-1.2,1.2,-1.2,1.2],'equal' a.axis('equal') atxt='generation: {0}\nscore: {1:.3f}'.format(self.gg,self.score) a.text(0,0,atxt, ha='center',va='center') #, fontsize=8)
def updateMask(self, outerRadius, innerRadius=0): if self.ring is not None: self.ring.remove() center = self.dim / 2 width = outerRadius - innerRadius styleArgs = getWedgeExtraParams(center) self.ring = Wedge((center, center), outerRadius, 0, 360, width=width, **styleArgs) # Full ring self.ax.add_patch(self.ring) self.canvas.draw()
def add_to_ada(ada, pos_x, pos_y, radius, angle_s, angle_e, ring_width, color_code, alpha_value): ada.drawing_area.add_artist( Wedge( (pos_x, pos_y), radius, angle_s, angle_e, width=ring_width, fc=color_code # '#DAF7A6' , ec='none', alpha=alpha_value, antialiased=True))
def _plot_fibres(ax, x, y, fibre_size, id_array=None, color=(0.9, 0.9, 1.0), alpha=0.25, edge=True, for_printing=False): radius = fibre_size / 2.0 if for_printing is True: radius *= 1.7 edge_outer_radius = 1.05 * radius edge_width = 0.05 * radius if for_printing is True: text_size = 3 else: text_size = 2.5 for i in range(len(x)): # Add a circle with the fibre size circle = Circle((x[i], y[i]), radius=radius, color=color) ax.add_patch(circle) # Add an edge above the circle if edge == True: wedge = Wedge((x[i], y[i]), edge_outer_radius, 0.0, 360.0, width=edge_width, alpha=alpha) ax.add_patch(wedge) # Add a text with the ID if id_array is not None: ax.text(x[i], y[i], id_array[i], size=text_size, ha='center', va='center')
def add_venus_2D(center, radius, angle=0, ax=None, colors=('w', 'k')): #get 2 halves of venus theta1, theta2 = angle, angle + 180 #create wedge items for each half, with each color w1 = Wedge(center, radius, theta1, theta2, fc=colors[0], alpha=0.5) #w2 = Wedge(center, radius, theta2, theta1, fc=colors[1], alpha = 0.3) #add to specified axis ax.add_artist(w1) # for wedge in [w1, w2]: # ax.add_artist(wedge) # # return [w1, w2]
def create_child_rings(tree, level=2, level_angle=360, start_angle=0, rings=[], radius=WIDTH, center=(CENTER_X, CENTER_Y), size_attr="static"): from matplotlib.patches import Wedge child_size = 0 max_size = getattr(tree.size(), size_attr)() if len(tree.childs) == 0: return rings if max_size == 0: for name, node in tree.childs.items(): max_size += getattr(node.size(), size_attr)() if max_size == 0: return rings s_angle = start_angle sections = {} # Create child wedges for name, node in tree.childs.items(): size = getattr(node.size(), size_attr)() s = Section(node, size, max_size, level_angle, s_angle) sections[name] = s create_child_rings(node, level+1, s.angle, s_angle, rings, radius, center, size_attr) s_angle += s.angle child_size += size # Just a check if child_size > max_size: print("[{}] Ooops, child size is greater than max size".format(name)) for name, section in sections.items(): # Create tuple: (wedge, name) name = "{} {}".format(name, human_bytes(section.size)) tup = ( Wedge(center, level * radius, section.start_angle, section.start_angle + section.angle, width=radius, facecolor=ring_color(section.start_angle, level)), name) rings.append(tup) return rings
def loop_matplotlib(nav, bike, map_model): """This function uses adding and removing patches to animate the bike.""" plt.ion() # enables interactive plotting paths = map_model.paths fig = plt.figure() ax = plt.axes(**find_display_bounds(map_model.waypoints)) lc = mc.LineCollection(paths, linewidths=2, color="blue") ax.add_collection(lc) plt.show() # For plotting the bicycle axes = plt.gca() # Holds past locations of the bike, for plotting bike_trajectory = [(bike.xB, bike.yB)] # We need to keep this around to clear it after path updates path_patch = None prev_bike_patch = None prev_lookahead_patch = None # Main animation loop while True: if path_patch: path_patch.remove() path_patch = PathPatch(Path(bike_trajectory), fill=False, linewidth=2) axes.add_patch(path_patch) # Plot the bike as a wedge pointing in the direction bike.psi if prev_bike_patch: prev_bike_patch.remove() bike_heading = bike.psi * (180 / math.pi) # Converted to degrees wedge_angle = 45 # The angle covered by the wedge bike_polygon = Wedge((bike.xB, bike.yB), 0.3, bike_heading - wedge_angle / 2 + 180, bike_heading + wedge_angle / 2 + 180, fc="black") axes.add_patch(bike_polygon) prev_bike_patch = bike_polygon plt.show() plt.pause(0.00000000000001) bike_trajectory.append((bike.xB, bike.yB)) steerD = nav.get_steering_angle() # if new state has new target path then recalculate delta bike.update(bikeSim.new_state(bike, steerD))
def update_scan_field(self): """ Updates the location of the `scan_field` semi-circle displayed to indicate its location and the direction in which it is facing. If there was a no previous scan field, then will be added. Should be called whenever either location or needs to be called as part of the rover's move and rotate functions.) """ # Remove the old scan field, if there is one: w = self.scan_field if w != None: self.view.artists.remove(w) # Make a semi-circle with radius 100 at the current rover location: w = Wedge(self._loc, 100, self._direction - 90, self._direction + 90) w.set_facecolor('0.90') # grey w.set_edgecolor('none') w.set_zorder(zorders['scan_field']) w.set_fill(True) self.view.add_artist(w) self.scan_field = w
def initializeDrawing(self): self.waterLine, = self.ax.plot([0.0, 300.0], [self.waterLevelVal, self.waterLevelVal]) crestDrop = [self.crestVal[0], self.crestVal[1]-self.frontDropVal] waterPt = [(crestDrop[1]-self.frontHeightVal)/tan(radians(self.frontAngleVal)), self.frontHeightVal] landPt = [-(self.crestVal[1]-self.backHeightVal)/tan(radians(self.backAngleVal)), self.backHeightVal] x = [i[0] for i in [landPt, self.crestVal, crestDrop, waterPt]] y = [i[1] for i in [landPt, self.crestVal, crestDrop, waterPt]] self.duneLine, = self.ax.plot(x, y) baseGround = [self.crestVal[0] - self.baseOffsetVal, self.crestVal[1] - self.baseDropVal] baseTop = [baseGround[0], baseGround[1] + self.baseHeightVal] boomEnd = [baseTop[0] + self.boomLengthVal*cos(radians(self.boomAngleVal)), baseTop[1] + self.boomLengthVal*sin(radians(self.boomAngleVal))] self.oceanRange.setText(QString.number(boomEnd[0] + (boomEnd[1]-self.waterLevelVal)/tan(radians(self.mountAngleVal-60)), 'f', 1)) xb = [i[0] for i in [baseGround, baseTop, boomEnd]] yb = [i[1] for i in [baseGround, baseTop, boomEnd]] self.boomLine, = self.ax.plot(xb, yb) straightAngle = self.boomAngleVal - (90-self.mountAngleVal) - 90 + self.hingeAngleVal self.wedge = Wedge(boomEnd, 300, straightAngle-40, straightAngle+60, alpha=0.5, color='y') self.ax.add_artist(self.wedge) angle = -30+self.mountAngleVal+self.hingeAngleVal+self.boomAngleVal self.oceanRange.setText(QString.number(boomEnd[0] + (boomEnd[1]-self.waterLevelVal)*tan(radians(angle)), 'f', 1)) # Initialize cabling drawing cableMountBaseTop = [baseTop[0], baseTop[1] + self.cableMountHeight] pulleyA = [baseTop[0] + self.pulleyALocation*cos(radians(self.boomAngleVal)), baseTop[1] + self.pulleyALocation*sin(radians(self.boomAngleVal))] xc = [i[0] for i in [baseTop, cableMountBaseTop, pulleyA]] yc = [i[1] for i in [baseTop, cableMountBaseTop, pulleyA]] self.calculateCablingForces() self.cableLine, = self.ax.plot(xc, yc, 'k') self.fig.subplots_adjust(left=0.1)
import matplotlib as mpl from matplotlib.patches import Wedge import matplotlib.pyplot as plt mpl.rcParams['toolbar'] = 'None' plt.style.use('ggplot') fig, ax = plt.subplots(figsize=(3.5,3.5)) fig.canvas.set_window_title('Acquisition') patch = Wedge((.5, .5), .45, 90, 90, width=0.15) ax.add_patch(patch) ax.axis('equal') ax.set_xlim([0,1]) ax.set_ylim([0,1]) ax.axis('off') t = ax.text(0.5, 0.5, '0%%', fontsize=15, ha='center', va='center') di = 1 for i in range(0,360,di): patch.set_theta1(90 - i - di) progress = 100 * (i+di) / 360 t.set_text('%02d%%' % progress) plt.pause(0.0001) #plt.show() plt.close()
def reconstruct(self, downsample=(4, 4), crop=True, median_filter=False, kernel=9, recon_alg='fbp', sart_iters=1, crop_circle=False, save=True, fancy_out=True): """ Reconstruct the data using a radon transform. Reconstructed slices saved in folder specified upon class creation. # downsample: Downsample (local mean) data before reconstructing. Specify mean kernel size (height, width). # pre_filter: If True apply median filter to data before reconstructing # kernel: Kernel size to use for median filter """ if self.cor_offset >= 0: images = self.im_stack[:, self.cor_offset:] else: images = self.im_stack[:, :self.cor_offset] images = images[:, :, self.p0:self.num_images + self.p0] if crop: left, right, top, bottom = self.crop images = images[top:bottom, left:right] images = downscale_local_mean(images, downsample + (1, )) recon_height, recon_width = images.shape[:2] self.recon_data = np.zeros((recon_width, recon_width, recon_height)) if median_filter: print('Applying median filter...') for i in range(images.shape[-1]): sys.stdout.write('\rProgress: [{0:20s}] {1:.0f}%'.format('#' * int(20 * (i + 1) / images.shape[-1]), 100 * ((i + 1) / images.shape[-1]))) sys.stdout.flush() images[:, :, i] = medfilt(images[:, :, i], kernel_size=kernel) print('\nReconstructing...') if save: save_folder = os.path.join(self.folder, 'reconstruction') if not os.path.exists(save_folder): os.makedirs(save_folder) for the_file in os.listdir(save_folder): file_path = os.path.join(save_folder, the_file) if os.path.isfile(file_path): os.unlink(file_path) if fancy_out: fig, ax = plt.subplots(figsize=(4, 4)) fig.canvas.set_window_title('Reconstruction') patch = Wedge((.5, .5), .375, 90, 90, width=0.1) ax.add_patch(patch) ax.axis('equal') ax.set_xlim([0, 1]) ax.set_ylim([0, 1]) ax.axis('off') t = ax.text(0.5, 0.5, '0%%', fontsize=15, ha='center', va='center') for j in range(recon_height): # Update figure every other slice if fancy_out and j % 2 == 0: patch.set_theta1(90 - 360 * (j + 1) / recon_height) progress = 100 * (j + 1) / recon_height t.set_text('%02d%%' % progress) plt.pause(0.001) else: sys.stdout.write('\rProgress: [{0:20s}] {1:.0f}%'.format('#' * int(20 * (j + 1) / recon_height), 100 * ((j + 1) / recon_height))) sys.stdout.flush() sino_tmp = np.squeeze(images[j, :, :]) if recon_alg is 'sart': image_tmp = iradon_sart(sino_tmp, theta=self.angles) for i in range(sart_iters - 1): image_tmp = iradon_sart(sino_tmp, theta=self.angles, image=image_tmp) else: image_tmp = iradon(sino_tmp, theta=self.angles, filter=None, circle=True) # if crop_circle: # image_tmp = image_tmp[w0:wf, w0:wf] self.recon_data[:, :, j] = image_tmp if crop_circle: w = int((recon_width**2 / 2)**0.5) w = w if (w - recon_width) % 2 == 0 else w - 1 w0 = int((recon_width - w) / 2 ) wf = int(w0 + w) self.recon_data = self.recon_data[w0:wf, w0:wf] if save: for j in range(recon_height): image_tmp = self.recon_data[:, :, j] imsave(os.path.join(save_folder, '%04d.tif' % j), image_tmp) if fancy_out: plt.close()
class MainWindow(QMainWindow): def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.setWindowTitle('Lidar Boom Geometry') self.initializeValues() self.createLayout() self.initializeDrawing() def initializeValues(self): self.crestVal = [0.0, 6.5] self.backAngleVal = 2 self.backHeightVal = 4 self.frontAngleVal = 3 self.frontHeightVal = 1 self.frontDropVal = 1 self.baseDropVal = 1 self.baseOffsetVal = 12 self.baseHeightVal = 4 * 0.3048 self.boomAngleVal = 20 self.boomLengthVal = 44 * 0.3048 self.mountAngleVal = 80 self.hingeAngleVal = 10 self.mountLengthVal = 0.5 self.waterLevelVal = 1 # Cabling variables self.cableMountHeight = 5 * 0.3048 self.pulleyALocation = 34 * 0.3048 # Weights self.sensorWeight = 500 def drawBoomEnd(self): # The boom cut length = 15 height = 10 boomPts = [[0, 0], [length, 0], [length + height/tan(radians(self.mountAngleVal)), height], [0, height]] x = [i[0] for i in boomPts] y = [i[1] for i in boomPts] self.barAx.cla() self.barAx.plot(x, y, 'k') fill = Polygon(boomPts, facecolor='k') self.barAx.add_patch(fill) # The angled hinge hingeLength = sqrt((height/tan(radians(self.mountAngleVal)))**2 + height**2) angle = self.hingeAngleVal - 90 - (90 - self.mountAngleVal) hingePts = [boomPts[2], [boomPts[2][0] + hingeLength*cos(radians(angle)), boomPts[2][1] + hingeLength*sin(radians(angle))]] xh = [i[0] for i in hingePts] yh = [i[1] for i in hingePts] self.barAx.plot(xh, yh, 'k', lw=2) self.barAx.set_ylim([-2,12]) def initializeDrawing(self): self.waterLine, = self.ax.plot([0.0, 300.0], [self.waterLevelVal, self.waterLevelVal]) crestDrop = [self.crestVal[0], self.crestVal[1]-self.frontDropVal] waterPt = [(crestDrop[1]-self.frontHeightVal)/tan(radians(self.frontAngleVal)), self.frontHeightVal] landPt = [-(self.crestVal[1]-self.backHeightVal)/tan(radians(self.backAngleVal)), self.backHeightVal] x = [i[0] for i in [landPt, self.crestVal, crestDrop, waterPt]] y = [i[1] for i in [landPt, self.crestVal, crestDrop, waterPt]] self.duneLine, = self.ax.plot(x, y) baseGround = [self.crestVal[0] - self.baseOffsetVal, self.crestVal[1] - self.baseDropVal] baseTop = [baseGround[0], baseGround[1] + self.baseHeightVal] boomEnd = [baseTop[0] + self.boomLengthVal*cos(radians(self.boomAngleVal)), baseTop[1] + self.boomLengthVal*sin(radians(self.boomAngleVal))] self.oceanRange.setText(QString.number(boomEnd[0] + (boomEnd[1]-self.waterLevelVal)/tan(radians(self.mountAngleVal-60)), 'f', 1)) xb = [i[0] for i in [baseGround, baseTop, boomEnd]] yb = [i[1] for i in [baseGround, baseTop, boomEnd]] self.boomLine, = self.ax.plot(xb, yb) straightAngle = self.boomAngleVal - (90-self.mountAngleVal) - 90 + self.hingeAngleVal self.wedge = Wedge(boomEnd, 300, straightAngle-40, straightAngle+60, alpha=0.5, color='y') self.ax.add_artist(self.wedge) angle = -30+self.mountAngleVal+self.hingeAngleVal+self.boomAngleVal self.oceanRange.setText(QString.number(boomEnd[0] + (boomEnd[1]-self.waterLevelVal)*tan(radians(angle)), 'f', 1)) # Initialize cabling drawing cableMountBaseTop = [baseTop[0], baseTop[1] + self.cableMountHeight] pulleyA = [baseTop[0] + self.pulleyALocation*cos(radians(self.boomAngleVal)), baseTop[1] + self.pulleyALocation*sin(radians(self.boomAngleVal))] xc = [i[0] for i in [baseTop, cableMountBaseTop, pulleyA]] yc = [i[1] for i in [baseTop, cableMountBaseTop, pulleyA]] self.calculateCablingForces() self.cableLine, = self.ax.plot(xc, yc, 'k') self.fig.subplots_adjust(left=0.1) def update(self): # Dune calculations crestDrop = [self.crestVal[0], self.crestVal[1]-self.frontDropVal] waterPt = [(crestDrop[1]-self.frontHeightVal)/tan(radians(self.frontAngleVal)), self.frontHeightVal] landPt = [-(self.crestVal[1]-self.backHeightVal)/tan(radians(self.backAngleVal)), self.backHeightVal] xDune = [i[0] for i in [landPt, self.crestVal, crestDrop, waterPt]] yDune = [i[1] for i in [landPt, self.crestVal, crestDrop, waterPt]] # Base and boom calculations baseGround = [self.crestVal[0] - self.baseOffsetVal, self.crestVal[1] - self.baseDropVal] baseTop = [baseGround[0], baseGround[1] + self.baseHeightVal] boomEnd = [baseTop[0] + self.boomLengthVal*cos(radians(self.boomAngleVal)), baseTop[1] + self.boomLengthVal*sin(radians(self.boomAngleVal))] xBoom = [i[0] for i in [baseGround, baseTop, boomEnd]] yBoom = [i[1] for i in [baseGround, baseTop, boomEnd]] # Update drawing self.waterLine.set_ydata([self.waterLevelVal, self.waterLevelVal]) self.duneLine.set_xdata(xDune) self.duneLine.set_ydata(yDune) self.boomLine.set_xdata(xBoom) self.boomLine.set_ydata(yBoom) self.wedge.set_center(boomEnd) straightAngle = self.boomAngleVal - (90-self.mountAngleVal) - 90 + self.hingeAngleVal self.wedge.set_theta1(straightAngle-40) self.wedge.set_theta2(straightAngle+60) self.drawBoomEnd() # Calculate and draw cabling cableMountBaseTop = [baseTop[0], baseTop[1] + self.cableMountHeight] pulleyA = [baseTop[0] + self.pulleyALocation*cos(radians(self.boomAngleVal)), baseTop[1] + self.pulleyALocation*sin(radians(self.boomAngleVal))] xc = [i[0] for i in [baseTop, cableMountBaseTop, pulleyA]] yc = [i[1] for i in [baseTop, cableMountBaseTop, pulleyA]] self.cableLine.set_xdata(xc) self.cableLine.set_ydata(yc) self.calculateCablingForces() # Update the interface angle = -30+self.mountAngleVal+self.hingeAngleVal+self.boomAngleVal self.oceanRange.setText(QString.number(boomEnd[0] + (boomEnd[1]-self.waterLevelVal)*tan(radians(angle)), 'f', 1)) # Update the canvas self.fig.canvas.draw() def calculateCablingForces(self): h = self.pulleyALocation*sin(radians(self.boomAngleVal)) - self.cableMountHeight l = self.pulleyALocation*cos(radians(self.boomAngleVal)) innerAngle = abs(atan2(h,l) - radians(self.boomAngleVal)) f = (self.sensorWeight * sin(radians(90 - self.boomAngleVal)) / sin(innerAngle)) self.pulleyAForce.setText(QString.number(f, 'f', 1)) print degrees(innerAngle) def updateCrest(self, val): self.crestVal[1] = val self.update() def updateWaterLevel(self, val): self.waterLevelVal = val self.update() def updateBaseDrop(self, val): self.baseDropVal = val self.update() def updateBaseOffset(self, val): self.baseOffsetVal = val self.update() def updateBaseHeight(self, val): self.baseHeightVal = val self.update() def updateBoomAngle(self, val): self.boomAngleVal = val self.update() def updateBoomLength(self, val): self.boomLengthVal = val self.update() def updateMountAngle(self, val): self.mountAngleVal = val self.update() def updateHingeAngle(self, val): self.hingeAngleVal = val self.update() def updateCableTowerHeight(self, val): self.cableMountHeight = val self.update() def updatePulleyALocation(self, val): self.pulleyALocation = val self.update() def updateSensorWeight(self, val): self.sensorWeight = val self.update() def createLayout(self): self.mainFrame = QWidget() # Main horizontal layout mainLayout = QHBoxLayout() # Layouts controlLayout = QGridLayout() infoLayout = QGridLayout() leftLayout = QVBoxLayout() viewLayout = QVBoxLayout() line = QFrame(self.mainFrame) line.setFrameStyle(QFrame.HLine | QFrame.Raised) leftLayout.addLayout(controlLayout) leftLayout.addWidget(line) leftLayout.addLayout(infoLayout) leftLayout.addStretch() mainLayout.addLayout(leftLayout) mainLayout.addLayout(viewLayout) # Info List infoLayout.addWidget(QLabel('<b>LIDAR</b>'), 0, 0, 1, 2, Qt.AlignCenter) infoLayout.addWidget(QLabel('Ocean Sight Range:'), 1, 0) infoLayout.addWidget(QLabel('<b>Structural</b>'), 2, 0, 1, 2, Qt.AlignCenter) infoLayout.addWidget(QLabel('Force - Pulley A (lb)'), 3, 0) self.oceanRange = QLabel('-', self.mainFrame) self.pulleyAForce = QLabel('-', self.mainFrame) infoLayout.addWidget(self.oceanRange, 1, 1) infoLayout.addWidget(self.pulleyAForce, 3, 1) infoLayout.setColumnMinimumWidth(1, 100) # Control grid controlLayout.addWidget(QLabel('<b>Dune/Ocean</b>'), 0, 0, 1, 2, Qt.AlignCenter) controlLayout.addWidget(QLabel('Dune Crest'), 1, 0) controlLayout.addWidget(QLabel('Water Level'), 2, 0) controlLayout.addWidget(QLabel('<b>Boom Geometry</b>'), 3, 0, 1, 2, Qt.AlignCenter) controlLayout.addWidget(QLabel('Base Drop'), 4, 0) controlLayout.addWidget(QLabel('Base Offset'), 5, 0) controlLayout.addWidget(QLabel('Base Height'), 6, 0) controlLayout.addWidget(QLabel('Boom Length'), 7, 0) controlLayout.addWidget(QLabel('Boom Angle'), 8, 0) controlLayout.addWidget(QLabel('<b>Mount Geometry</b>'), 9, 0, 1, 2, Qt.AlignCenter) controlLayout.addWidget(QLabel('Mount Cut Angle'), 10, 0) controlLayout.addWidget(QLabel('Hinge Angle'), 11, 0) controlLayout.addWidget(QLabel('<b>Cabling Geometry</b>'), 12, 0, 1, 2, Qt.AlignCenter) controlLayout.addWidget(QLabel('Cable Mount Height'), 13, 0) controlLayout.addWidget(QLabel('Pulley A Location'), 14, 0) controlLayout.addWidget(QLabel('<b>Loading (lbs)</b>'), 15, 0, 1, 2, Qt.AlignCenter) controlLayout.addWidget(QLabel('LIDAR Weight'), 16, 0) controlLayout.addWidget(QLabel('Boom Weight'), 17, 0) self.crestHeight = QDoubleSpinBox(self.mainFrame) self.crestHeight.setSingleStep(0.1) self.crestHeight.setValue(self.crestVal[1]) controlLayout.addWidget(self.crestHeight, 1, 1) self.connect(self.crestHeight, SIGNAL('valueChanged(double)'), self.updateCrest) self.waterLevel = QDoubleSpinBox(self.mainFrame) self.waterLevel.setSingleStep(0.1) self.waterLevel.setValue(self.waterLevelVal) controlLayout.addWidget(self.waterLevel, 2, 1) self.connect(self.waterLevel, SIGNAL('valueChanged(double)'), self.updateWaterLevel) self.baseDrop = QDoubleSpinBox(self.mainFrame) self.baseDrop.setSingleStep(0.1) self.baseDrop.setValue(self.baseDropVal) controlLayout.addWidget(self.baseDrop, 4, 1) self.connect(self.baseDrop, SIGNAL('valueChanged(double)'), self.updateBaseDrop) self.baseOffset = QDoubleSpinBox(self.mainFrame) self.baseOffset.setSingleStep(0.1) self.baseOffset.setValue(self.baseOffsetVal) controlLayout.addWidget(self.baseOffset, 5, 1) self.connect(self.baseOffset, SIGNAL('valueChanged(double)'), self.updateBaseOffset) self.baseHeight = QDoubleSpinBox(self.mainFrame) self.baseHeight.setSingleStep(0.1) self.baseHeight.setValue(self.baseHeightVal) controlLayout.addWidget(self.baseHeight, 6, 1) self.connect(self.baseHeight, SIGNAL('valueChanged(double)'), self.updateBaseHeight) self.boomLength = QDoubleSpinBox(self.mainFrame) self.boomLength.setSingleStep(0.1) self.boomLength.setValue(self.boomLengthVal) controlLayout.addWidget(self.boomLength, 7, 1) self.connect(self.boomLength, SIGNAL('valueChanged(double)'), self.updateBoomLength) self.boomAngle = QDoubleSpinBox(self.mainFrame) self.boomAngle.setSingleStep(0.5) self.boomAngle.setMaximum(360) self.boomAngle.setValue(self.boomAngleVal) controlLayout.addWidget(self.boomAngle, 8, 1) self.connect(self.boomAngle, SIGNAL('valueChanged(double)'), self.updateBoomAngle) self.mountAngle = QDoubleSpinBox(self.mainFrame) self.mountAngle.setSingleStep(0.5) self.mountAngle.setMaximum(360) self.mountAngle.setValue(self.mountAngleVal) controlLayout.addWidget(self.mountAngle, 10, 1) self.connect(self.mountAngle, SIGNAL('valueChanged(double)'), self.updateMountAngle) self.hingeAngle = QDoubleSpinBox(self.mainFrame) self.hingeAngle.setSingleStep(0.5) self.hingeAngle.setMaximum(360) self.hingeAngle.setValue(self.hingeAngleVal) controlLayout.addWidget(self.hingeAngle, 11, 1) self.connect(self.hingeAngle, SIGNAL('valueChanged(double)'), self.updateHingeAngle) self.cableTowerHeight = QDoubleSpinBox(self.mainFrame) self.cableTowerHeight.setSingleStep(0.1) self.cableTowerHeight.setValue(self.cableMountHeight) controlLayout.addWidget(self.cableTowerHeight, 13, 1) self.connect(self.cableTowerHeight, SIGNAL('valueChanged(double)'), self.updateCableTowerHeight) self.pulleyADistance = QDoubleSpinBox(self.mainFrame) self.pulleyADistance.setSingleStep(0.1) self.pulleyADistance.setValue(self.pulleyALocation) controlLayout.addWidget(self.pulleyADistance, 14, 1) self.connect(self.pulleyADistance, SIGNAL('valueChanged(double)'), self.updatePulleyALocation) self.lidarWeight = QDoubleSpinBox(self.mainFrame) self.lidarWeight.setSingleStep(5) self.lidarWeight.setMaximum(9999999) self.lidarWeight.setValue(self.sensorWeight) controlLayout.addWidget(self.lidarWeight, 16, 1) self.connect(self.lidarWeight, SIGNAL('valueChanged(double)'), self.updateSensorWeight) # Create the axes self.fig = Figure((5.0, 4.0)) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self.mainFrame) self.ax = self.fig.add_subplot(211, aspect='equal') self.barAx = self.fig.add_subplot(212, aspect='equal') self.ax.set_xlim([-15,10]) self.drawBoomEnd() self.toolBar = NavigationToolbar(self.canvas, self.mainFrame) viewLayout.addWidget(self.canvas) viewLayout.addWidget(self.toolBar) # Set the main layout self.mainFrame.setLayout(mainLayout) self.setCentralWidget(self.mainFrame)
def createRing(self): radius = float(self.hf) width = radius - float(self.lf) self.ring = Wedge((0,0), radius, 0, 360, width=width, alpha=0.15) # Full ring self.ax.add_patch(self.ring) self.canvas.draw()