def write_body(self): try: from matplotlib.path import Path except ImportError: Path = None from matplotlib.patches import Circle, Polygon else: from matplotlib.patches import Circle, PathPatch indices = self.X[:, 2].argsort() for a in indices: xy = self.X[a, :2] if a < self.natoms: r = self.d[a] / 2 if ((xy[1] + r > 0) and (xy[1] - r < self.h) and (xy[0] + r > 0) and (xy[0] - r < self.w)): circle = Circle(xy, r, facecolor=self.colors[a]) circle.draw(self.renderer) else: a -= self.natoms c = self.T[a] if c != -1: hxy = self.D[c] if Path is None: line = Polygon((xy + hxy, xy - hxy)) else: line = PathPatch(Path((xy + hxy, xy - hxy))) line.draw(self.renderer)
def animate(currentNode = currentNode): while 1: newNode = q.get() if currentNode: currentNode.remove() circle = Circle(newNode,0.1) currentNode = ax.add_patch(circle) circle.set_fc('r') fig.canvas.draw()
def circle(xy=None, x=None, y=None, **kwargs): if xy is None: if x is None or y is None: raise 'circle: need x and y' xy = array([x,y]) c = Circle(xy=xy, **kwargs) a=gca() c.set_clip_box(a.bbox) a.add_artist(c) return c
def draw_vswr_circles(self, vswr_radii, labels=False): for r in vswr_radii: c = Circle((0, 0), r, ls='dashed', **self.patch_options_light) c.set_clip_path(self.smith_circle) c.set_clip_box(self.ax.bbox) self.ax.add_patch(c) if labels: for r in vswr_radii: if r > 0: vswr = (1 + r)/(1 - r) self.ax.text(0, r, '%.1f' % vswr, **self.label_options)
def make_animation_frames(name, semimajor, planet_radius, star_radius, star_color, orbital_period): #not affiliated with Animal Planet. center = np.array([0.5,0.5]) angle = np.random.uniform(0, 2*np.pi) planet_center = center+semimajor*np.array([1,0]) fig = Figure(figsize=(6,6)) axis = fig.add_subplot(1, 1, 1) star = Circle(center, radius=star_radius, color=star_color) orbit = Circle(center, radius=semimajor, fill=False, linestyle='dashed', color='gray') planet = Circle(planet_center, radius=planet_radius, color='green') axis.add_patch(star) axis.add_patch(orbit) axis.add_patch(planet) axis.axis('off') filenames = [] #set 50 days to be 5 seconds orbital_period = orbital_period/100.*5. #let's put the period in seconds fps = 100. print 'orbital period = ', orbital_period nframe = int(orbital_period*fps) #round off orbital_period = nframe/fps omega = 2*np.pi/orbital_period angles = np.linspace(0, 2*np.pi, nframe) if not os.path.exists("frames"): os.makekdir("frames") if not os.path.exists("gifs"): os.makekdir("gifss") print angles print "nframe = ", nframe for i,theta in enumerate(angles): canvas = FigureCanvas(fig) planet.center = center+semimajor*np.array([np.cos(theta),np.sin(theta)]) filename = ("frames/%.4d_"%i)+remove_space(name)+'.png' fig.savefig(filename) filenames.append(filename) #animate gifname = "gifs/%s.gif" % remove_space(name) frame_names = " ".join(filenames) cmd = "convert -delay 1 %s %s" % (frame_names, gifname) print cmd os.system(cmd)
def add_breadcrumb(self): """ Adds a breadcrumb """ c = Circle(self._loc, radius = 16.25) c.set_facecolor('0.65') # grey c.set_edgecolor('black') c.set_zorder(zorders['breadcrumbs']) c.set_fill(True) self.view.add_artist(c) self.breadcrumbs.append(c) self.draw()
def circle( xy, radius, color="lightsteelblue", facecolor="none", alpha=1, ax=None ): """ add a circle to ax= or current axes """ # from .../pylab_examples/ellipse_demo.py e = Circle( xy=xy, radius=radius ) if ax is None: ax = plt.gca() # ax = subplot( 1,1,1 ) ax.add_artist(e) e.set_clip_box(ax.bbox) e.set_edgecolor( color ) e.set_facecolor( facecolor ) # "none" not None e.set_alpha( alpha )
def scatter_plot(self, equators=True, tagging=True, depth_cap=None): if depth_cap is None: depth_cap = self.height fig = plt.figure(figsize=(12, 10)) ax = fig.add_subplot(111, projection="3d") plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0) xs = [self.nodes[self.root].coord.x] ys = [self.nodes[self.root].coord.y] zs = [self.nodes[self.root].coord.z] plot_color_board = ["blue", "red", "yellow", "green", "black"] font0 = FontProperties() font0.set_size(8) current_generation = deque([self.root]) next_generation = True while next_generation: next_generation = deque() while current_generation: n = current_generation.popleft() if self.nodes[n].depth <= depth_cap: xs.append(self.nodes[n].coord.x) ys.append(self.nodes[n].coord.y) zs.append(self.nodes[n].coord.z) if tagging: ax.text(self.nodes[n].coord.x + 0.01, self.nodes[n].coord.y + 0.01, self.nodes[n].coord.z + 0.01, ("n{0}".format(n)), fontproperties=font0) for child in self.nodes[n].children: next_generation.append(child) if self.nodes[n].depth <= depth_cap: xe = [self.nodes[n].coord.x, self.nodes[child].coord.x] ye = [self.nodes[n].coord.y, self.nodes[child].coord.y] ze = [self.nodes[n].coord.z, self.nodes[child].coord.z] ax.plot(xe, ye, ze, plot_color_board[self.nodes[n].depth % 5]) current_generation = next_generation ax.scatter(xs, ys, zs, c="r", marker="o") global_radius = self.nodes[self.root].radius * 1.12 if equators: for axis in ["x", "y", "z"]: circle = Circle((0, 0), global_radius * 1.1) circle.set_clip_box(ax.bbox) circle.set_edgecolor("gray") circle.set_alpha(0.3) circle.set_facecolor("none") # "none" not None ax.add_patch(circle) art3d.pathpatch_2d_to_3d(circle, z=0, zdir=axis) ax.set_xlim([-1.2 * global_radius, 1.2 * global_radius]) ax.set_ylim([-1.2 * global_radius, 1.2 * global_radius]) ax.set_zlim([-1.2 * global_radius, 1.2 * global_radius]) ax.set_xlabel("X Label") ax.set_ylabel("Y Label") ax.set_zlabel("Z Label") plt.show()
class Annotate(object): def __init__(self): self.ax = plt.gca() # self.rect = Rectangle((0,0), 1, 1) self.circ = Circle((0,0), 1, alpha=0.1) self.x0 = None self.y0 = None self.x1 = None self.y1 = None # self.ax.add_patch(self.rect) self.ax.add_patch(self.circ) self.press = None self.ax.figure.canvas.mpl_connect('button_press_event', self.on_press) self.ax.figure.canvas.mpl_connect('motion_notify_event', self.on_motion) self.ax.figure.canvas.mpl_connect('button_release_event', self.on_release) def on_press(self, event): print 'press' self.press = 1 self.x0 = event.xdata self.y0 = event.ydata def on_motion(self, event): if self.press is None: return self.x1 = event.xdata self.y1 = event.ydata radius = ((self.x1 - self.x0)**2 + (self.y1 - self.y0)**2)**0.5 self.circ.set_radius(radius) self.circ.center = self.x0, self.y0 # ###self.rect.set_width(self.x1 - self.x0) # ###self.rect.set_height(self.y1 - self.y0) # ###self.rect.set_xy((self.x0, self.y0)) self.ax.figure.canvas.draw() def on_release(self, event): print 'release' self.press = None self.x1 = event.xdata self.y1 = event.ydata radius = ((self.x1 - self.x0) ** 2 + (self.y1 - self.y0) ** 2) ** 0.5 self.circ.set_radius(radius) self.circ.center = self.x0, self.y0 # ###self.rect.set_width(self.x1 - self.x0) # ###self.rect.set_height(self.y1 - self.y0) # ###self.rect.set_xy((self.x0, self.y0)) self.ax.figure.canvas.draw()
def __init__(self, axes, sim, type_to_radius, type_to_color): assert len(type_to_radius) == len(type_to_color) particle_types_arr = sim.types self._typeToRadius = type_to_radius self._typeToColor = type_to_color self._particleCircles = [] self._sim = sim for particleType in particle_types_arr: c = Circle((0, 0, 0), type_to_radius[particleType], ) c.set_color(self._typeToColor[particleType]) self._particleCircles.append(c) axes.add_patch(c) axes.set_xlim([0, sim.domain_size[0]]) axes.set_ylim([0, sim.domain_size[1]]) axes.set_aspect('equal')
def draw_chart_axes(self): # make outer circle self.smith_circle = Circle((0, 0), 1, transform=self.ax.transData, fc='none', **self.patch_options_axis) self.ax.add_patch(self.smith_circle) # make constant r=1 circle z0_circle = Circle((0.5, 0), 0.5, transform=self.ax.transData, fc='none', **self.patch_options_axis) z0_circle.set_clip_path(self.smith_circle) z0_circle.set_clip_box(self.ax.bbox) self.ax.add_patch(z0_circle) # make x-axis line = Line2D([-1,1],[0,0], **self.patch_options_axis) line.set_clip_path(self.smith_circle) line.set_clip_box(self.ax.bbox) self.ax.add_line(line)
class SelectablePoint: def __init__(self, xy, label, fig): self.point = Circle( (xy[0], xy[1]), .25, figure=fig) self.label = label self.cidpress = self.point.figure.canvas.mpl_connect('button_press_event', self.onClick) def onClick(self, e): if self.point.contains(e)[0]: print self.label
def myCorrPlot(df): """ Correlation plot ( ~ corrplot with R) Takes a Pandas DataFrame as input and returns the plot which can then be shown with plot.show(), saved to a file with plot.savefig(), or manipulated in any other standard matplotlib way. Forked from https://github.com/louridas/corrplot """ plt.figure(1) ax = plt.subplot(1, 1, 1, aspect='equal') poscm = cm.get_cmap('Blues') negcm = cm.get_cmap('Reds') labels = df.columns for pair in combinations(labels, 2): corr = pearsonr(df[pair[0]].values, df[pair[1]].values)[0] clrmap = poscm if corr >= 0 else negcm circle = Circle((labels.get_loc(pair[0]),labels.get_loc(pair[1])), radius = 0.4) circle.set_edgecolor('black') circle.set_facecolor(clrmap(np.abs(corr))) mirrorCircle = Circle((labels.get_loc(pair[1]),labels.get_loc(pair[0])), radius = 0.4) mirrorCircle.set_edgecolor('black') mirrorCircle.set_facecolor(clrmap(np.abs(corr))) ax.add_artist(circle) ax.add_artist(mirrorCircle) ax.set_xlim(-1, len(labels)) ax.set_ylim(-1, len(labels)) ax.xaxis.tick_top() xtickslocs = np.arange(len(labels)) ax.set_xticks(xtickslocs) ax.set_xticklabels(labels, rotation=30, fontsize='small', ha='left') ax.invert_yaxis() ytickslocs = np.arange(len(labels)) ax.set_yticks(ytickslocs) ax.set_yticklabels(labels, fontsize='small') return plt
def draw_impedance_circles(self, intercept_x_coords, intercept_angles, labels=False): r_circle_coords, x_circle_coords, rs, xs = self._impedance_circle_coords(intercept_x_coords, intercept_angles) for center, radius in chain(r_circle_coords, x_circle_coords): c = Circle(center, radius, **self.patch_options_dark) c.set_clip_path(self.smith_circle) c.set_clip_box(self.ax.bbox) self.ax.add_patch(c) if labels: for x, r in zip(intercept_x_coords, rs): self.ax.text(x + 0.04, 0.03, '%.0f' % round(self.z0*r), **self.label_options) for a, x in zip(intercept_angles, xs): r = (a - 90) if x > 0 else (a + 90) a = np.radians(a) d = 1.04 self.ax.text(d*cos(a), d*sin(a), '%.0fj' % round(self.z0*x), rotation=r, **self.label_options)
def draw_admittance_circles(self, intercept_x_coords, intercept_angles, labels=False): r_circle_coords, x_circle_coords, rs, xs = self._impedance_circle_coords(intercept_x_coords, intercept_angles) # admittance circles have same coords as impedance ones, except flipped # on the y-axis for (x, y), radius in chain(r_circle_coords, x_circle_coords): c = Circle((-x, -y), radius, **self.patch_options_light) c.set_clip_path(self.smith_circle) c.set_clip_box(self.ax.bbox) self.ax.add_patch(c) if labels: for x, r in zip(intercept_x_coords, rs): self.ax.text(-x, 0, '%.1f' % (1/(50*r)), **self.label_options) for a, x in zip(intercept_angles, xs): r = (a - 90) if x < 0 else (a + 90) a = np.radians(a) self.ax.text(cos(pi - a), sin(pi - a), '%.1f' % (1/(50*x)), rotation=r, **self.label_options)
def __init__(self): self.ax = plt.gca() # self.rect = Rectangle((0,0), 1, 1) self.circ = Circle((0,0), 1, alpha=0.1) self.x0 = None self.y0 = None self.x1 = None self.y1 = None # self.ax.add_patch(self.rect) self.ax.add_patch(self.circ) self.press = None self.ax.figure.canvas.mpl_connect('button_press_event', self.on_press) self.ax.figure.canvas.mpl_connect('motion_notify_event', self.on_motion) self.ax.figure.canvas.mpl_connect('button_release_event', self.on_release)
def shooting_plot(shot_df, plot_size=(12,11), gridNum=30, mymap=plt.get_cmap('Spectral')): from matplotlib.patches import Circle x = shot_df.LOC_X[shot_df['LOC_Y']<425.1] y = shot_df.LOC_Y[shot_df['LOC_Y']<425.1] (shotVals, shotNumber) = find_shot_vals(shot_df, gridNum) fig = plt.figure(figsize=plot_size) cmap = mymap ax = plt.axes([0.1, 0.1, 0.8, 0.8]) draw_court(outer_lines=False) plt.xlim(-250,250) plt.ylim(422.5, -47.5) norm = mpl.colors.Normalize(vmin=-0.5, vmax = -0.1) import math def logistic(x): return 20 / (1 + math.exp(-0.18*(x-np.median(shotNumber.get_array())))) for i, shots in enumerate(shotVals): restricted = Circle(shotNumber.get_offsets()[i], radius=shotNumber.get_array()[i], color=cmap(norm(shots)),alpha=0.8, fill=True) restricted.radius = logistic( np.sqrt(restricted.radius) ) if restricted.radius > 240/gridNum: restricted.radius=240/gridNum ax.add_patch(restricted) ax2 = fig.add_axes([0.92, 0.1, 0.02, 0.8]) cb = mpl.colorbar.ColorbarBase(ax2,cmap=cmap, orientation='vertical') cb.set_label('next-possession value') cb.set_ticks([0.0, 0.25, 0.5, 0.75, 1.0]) cb.set_ticklabels(['-0.5','-0.4', '-0.3','-0.2', '-0.1']) plt.show() return ax
def __init__(self, vl, room_shape, start_iter): super(EnvironmentReader,self).__init__(win_size=[700,700], win_loc=pos, title='Environment') self.vl = vl self.cur_iter = start_iter self.cur_i = 0 self.max_iter = np.max(vl['Iter num']) self.maxx = room_shape[0][1] self.maxy = room_shape[1][1] self.cntr_x = np.mean(room_shape[0]) self.cntr_y = np.mean(room_shape[1]) self.x_hist = []; self.y_hist = [] self.canvas.mpl_connect('resize_event',lambda x: self.update_background()) self.pos, = self.ax.plot([],[],color='g',animated=True) self.vel = Arrow([0,0],[1,0],arrowstyle='-|>, head_length=3, head_width=3', animated=True, linewidth=4) self.ax.add_patch(self.vel) #self.radius, = self.ax.plot([],[],color='r',animated=True) self.clockcounter = self.ax.text(self.maxx,room_shape[1][0], '',ha='right',size='large', animated=True) self.iters = self.ax.text(self.maxx-1, room_shape[1][0]+3, '',ha='right',animated=True) self.target = Circle([0,0],0,animated=True,color='r') self.target.set_radius(11) self.ax.add_artist(self.target) self.ax.set_xlim(room_shape[0]) self.ax.set_ylim(room_shape[1]) self.draw_plc_flds() self.draw_HMM_sectors() self.predicted_counter = self.ax.text(self.maxx,room_shape[1][0]+10,'', ha='right',size='large',animated=True) self.prediction_hist = None #self.cur_sec = Rectangle([0,0],self.HMM.dx,self.HMM.dy,fill=True, # color='k',animated=True) #self.ax_env.add_patch(self.cur_sec) self.canvas.draw()
def __init__(self, cloud, selection_shape, z_color=False, unlabeled_color = (1,0,0), labeled_color = (0,0,1)): self.selection_shape = selection_shape self.unlabeled_color = np.array(unlabeled_color) self.labeled_color = np.array(labeled_color) assert not np.all(unlabeled_color == labeled_color) self.fig = plt.figure('label rope ends', figsize=(24,12)) self.fig.clear() self.ax = self.fig.add_subplot(111, aspect='equal') if cloud.shape[1] == 6: self.cloud = cloud else: self.cloud = np.c_[cloud[:,:3], np.tile(self.unlabeled_color, (cloud.shape[0],1))] if z_color: z_min = self.cloud[:,2].min() z_max = self.cloud[:,2].max() self.z_color = np.empty((len(self.cloud),3)) for i in range(len(self.cloud)): f = (self.cloud[i,2] - z_min) / (z_max - z_min) self.z_color[i,:] = np.array(colorsys.hsv_to_rgb(f,1,1)) else: self.z_color = None self.scatters = [] self.rescatter_cloud() self.ax.autoscale(False) if self.selection_shape == 'rectangle' or self.selection_shape == 'square': self.rect = Rectangle((0,0), 0, 0, facecolor='None', edgecolor='green', linestyle='dashed') self.ax.add_patch(self.rect) elif self.selection_shape == 'circle': self.circle = Circle((0,0), 0, facecolor='None', edgecolor='green', linestyle='dashed') self.ax.add_patch(self.circle) self.x0 = None self.y0 = None self.x1 = None self.y1 = None self.fig.canvas.mpl_connect('button_press_event', self.on_press) self.fig.canvas.mpl_connect('button_release_event', self.on_release) self.motion_notify_cid = None self.fig.canvas.mpl_connect('key_press_event', self.on_key) plt.show()
def enable_cursor(self): self.cid_on_mouse_move = self.fig.canvas.mpl_connect('motion_notify_event', self._on_mouse_move) self.fig.canvas.mpl_connect('button_press_event', self._on_mouse_press) #self.cid_on_mouse_leave = self.fig.canvas.mpl_connect('axes_leave_event', self._on_mouse_leave) #self.cid_resize = self.fig.canvas.mpl_connect('resize_event', self._resize) self.cid_draw = self.fig.canvas.mpl_connect('draw_event', self._draw) self.cursor_text = Text(0.7, 0.1, 'n/a', horizontalalignment='left', verticalalignment='center', #bbox=dict(facecolor='white', alpha=1, ec='gray', pad=10), color='white', fontsize='small', alpha=0.8, backgroundcolor='gray', family='monospace', clip_box=self.ax.bbox, animated=True, transform = self.ax.transAxes) self.ax.add_artist(self.cursor_text) self.circle_matched_term = Circle((100,100), 0.02, alpha=0.5, color='green', animated=True) self.ax.add_patch(self.circle_matched_term)
def __init__(self, message, net, direction, *args, **kwargs): Circle.__init__(self, self._get_pos(message, net, direction), *args, **kwargs)
def im_phot(directory,gain,im_file,aperture): """ Perform photometry on the image """ # Read in fits image file and create array with wcs coordinates os.chdir(directory) hdulist = fits.open(im_file) w = WCS(im_file) data = hdulist[0].data data[np.isnan(data)] = 0 hdulist.close() # Calculate center point of image (RA, Dec) if not input by user targetra, targetdec = w.all_pix2world(len(data[:,0])/2,len(data[0,:])/2,0) # Use SEP for background subtraction and source detection datasw = data.byteswap().newbyteorder().astype('float64') bkg = sep.Background(datasw) data_bgs = data - bkg data_bgs[data_bgs < 0] = 0 mean = np.mean(data_bgs) median = np.median(data_bgs) std = bkg.globalrms objects = sep.extract(data_bgs,3,err=bkg.globalrms) objra, objdec = w.all_pix2world(objects['x'],objects['y'],0) # Find dummy magnitudes using aperture photometry and plot images fig, ax = plt.subplots() image = plt.imshow(data_bgs,cmap='gray',vmin=(mean-3*std), vmax=(mean+3*std),origin='lower') sepmag = [] sepmagerr = [] ra = [] dec = [] xpixel = [] ypixel = [] for i in range(len(objects)): # Perform circular aperture photometry flux,fluxerr,flag = sep.sum_circle(data_bgs,objects['x'][i], objects['y'][i],aperture,err=std,gain=gain) mag = -2.5*np.log10(flux) maglimit1 = -2.5*np.log10((flux+fluxerr)) maglimit2 = -2.5*np.log10((flux-fluxerr)) magerr1 = np.abs(mag-maglimit1) magerr2 = np.abs(mag-maglimit2) magerr = (magerr1+magerr2)/2 # Save object properties to arrays sepmag.append(mag) sepmagerr.append(magerr) ra.append(objra[i]) dec.append(objdec[i]) xpixel.append(objects['x'][i]) ypixel.append(objects['y'][i]) # Plot the detections on the image out = Circle(xy=(objects['x'][i],objects['y'][i]),radius=aperture) out.set_facecolor('none') out.set_edgecolor('red') ax.add_artist(out) plt.savefig(directory+'detections.png') return targetra,targetdec,sepmag,sepmagerr,ra,dec,xpixel,ypixel
def gauge(labels=['LOW','MEDIUM','HIGH','EXTREME'], \ colors=['#007A00','#0063BF','#FFCC00','#ED1C24'], Probability=1, fname=False): N = len(labels) colors = colors[::-1] """ begins the plotting """ gauge_img = io.BytesIO() fig, ax = plt.subplots() ang_range, mid_points = degree_range(4) labels = labels[::-1] """ plots the sectors and the arcs """ patches = [] for ang, c in zip(ang_range, colors): # sectors patches.append(Wedge((0., 0.), .4, *ang, facecolor='w', lw=2)) # arcs patches.append( Wedge((0., 0.), .4, *ang, width=0.10, facecolor=c, lw=2, alpha=0.5)) [ax.add_patch(p) for p in patches] """ set the labels (e.g. 'LOW','MEDIUM',...) """ for mid, lab in zip(mid_points, labels): ax.text(0.35 * np.cos(np.radians(mid)), 0.35 * np.sin(np.radians(mid)), lab, \ horizontalalignment='center', verticalalignment='center', fontsize=14, \ fontweight='bold', rotation = rot_text(mid)) """ set the bottom banner and the title """ r = Rectangle((-0.4, -0.1), 0.8, 0.1, facecolor='w', lw=2) ax.add_patch(r) ax.text(0, -0.05, 'Churn Probability ' + np.round(Probability,2).astype(str), horizontalalignment='center', \ verticalalignment='center', fontsize=22, fontweight='bold') """ plots the arrow now """ pos = (1 - Probability) * 180 ax.arrow(0, 0, 0.225 * np.cos(np.radians(pos)), 0.225 * np.sin(np.radians(pos)), \ width=0.04, head_width=0.09, head_length=0.1, fc='k', ec='k') ax.add_patch(Circle((0, 0), radius=0.02, facecolor='k')) ax.add_patch(Circle((0, 0), radius=0.01, facecolor='w', zorder=11)) """ removes frame and ticks, and makes axis equal and tight """ ax.set_frame_on(False) ax.axes.set_xticks([]) ax.axes.set_yticks([]) ax.axis('equal') plt.tight_layout() plt.savefig(gauge_img, format='png') gauge_img.seek(0) url = base64.b64encode(gauge_img.getvalue()).decode() return url
def create_base(box_bg='#CCCCCC', arrow1='#88CCFF', arrow2='#88FF88', supervised=True): plt.figure(figsize=(9, 6), facecolor='w') ax = plt.axes((0, 0, 1, 1), xticks=[], yticks=[], frameon=False) ax.set_xlim(0, 9) ax.set_ylim(0, 6) patches = [Rectangle((0.3, 3.6), 1.5, 1.8, zorder=1, fc=box_bg), Rectangle((0.5, 3.8), 1.5, 1.8, zorder=2, fc=box_bg), Rectangle((0.7, 4.0), 1.5, 1.8, zorder=3, fc=box_bg), Rectangle((2.9, 3.6), 0.2, 1.8, fc=box_bg), Rectangle((3.1, 3.8), 0.2, 1.8, fc=box_bg), Rectangle((3.3, 4.0), 0.2, 1.8, fc=box_bg), Rectangle((0.3, 0.2), 1.5, 1.8, fc=box_bg), Rectangle((2.9, 0.2), 0.2, 1.8, fc=box_bg), Circle((5.5, 3.5), 1.0, fc=box_bg), Polygon([[5.5, 1.7], [6.1, 1.1], [5.5, 0.5], [4.9, 1.1]], fc=box_bg), FancyArrow(2.3, 4.6, 0.35, 0, fc=arrow1, width=0.25, head_width=0.5, head_length=0.2), FancyArrow(3.75, 4.2, 0.5, -0.2, fc=arrow1, width=0.25, head_width=0.5, head_length=0.2), FancyArrow(5.5, 2.4, 0, -0.4, fc=arrow1, width=0.25, head_width=0.5, head_length=0.2), FancyArrow(2.0, 1.1, 0.5, 0, fc=arrow2, width=0.25, head_width=0.5, head_length=0.2), FancyArrow(3.3, 1.1, 1.3, 0, fc=arrow2, width=0.25, head_width=0.5, head_length=0.2), FancyArrow(6.2, 1.1, 0.8, 0, fc=arrow2, width=0.25, head_width=0.5, head_length=0.2)] if supervised: patches += [Rectangle((0.3, 2.4), 1.5, 0.5, zorder=1, fc=box_bg), Rectangle((0.5, 2.6), 1.5, 0.5, zorder=2, fc=box_bg), Rectangle((0.7, 2.8), 1.5, 0.5, zorder=3, fc=box_bg), FancyArrow(2.3, 2.9, 2.0, 0, fc=arrow1, width=0.25, head_width=0.5, head_length=0.2), Rectangle((7.3, 0.85), 1.5, 0.5, fc=box_bg)] else: patches += [Rectangle((7.3, 0.2), 1.5, 1.8, fc=box_bg)] for p in patches: ax.add_patch(p) plt.text(1.45, 4.9, "Training\nText,\nDocuments,\nImages,\netc.", ha='center', va='center', fontsize=14) plt.text(3.6, 4.9, "Feature\nVectors", ha='left', va='center', fontsize=14) plt.text(5.5, 3.5, "Machine\nLearning\nAlgorithm", ha='center', va='center', fontsize=14) plt.text(1.05, 1.1, "New Text,\nDocument,\nImage,\netc.", ha='center', va='center', fontsize=14) plt.text(3.3, 1.7, "Feature\nVector", ha='left', va='center', fontsize=14) plt.text(5.5, 1.1, "Predictive\nModel", ha='center', va='center', fontsize=12) if supervised: plt.text(1.45, 3.05, "Labels", ha='center', va='center', fontsize=14) plt.text(8.05, 1.1, "Expected\nLabel", ha='center', va='center', fontsize=14) plt.text(8.8, 5.8, "Supervised Learning Model", ha='right', va='top', fontsize=18) else: plt.text(8.05, 1.1, "Likelihood\nor Cluster ID\nor Better\nRepresentation", ha='center', va='center', fontsize=12) plt.text(8.8, 5.8, "Unsupervised Learning Model", ha='right', va='top', fontsize=18)
class SmithChart(object): z0 = 50 current_plane = None two_port = None show_matched_termination_cursor = True gain_cursor = False def __init__(self, ax=None, show_cursor=True, admittance=True, labels=False): self.ax = ax if ax else gca() self.fig = self.ax.figure self.draw_smith_chart(admittance, labels) if show_cursor: self.enable_cursor() def _impedance_circle_coords(self, intercept_x_coords, intercept_angles): # find coords for constant R circles rs = 2/(1 - asarray(intercept_x_coords)) - 1 # convert to desired resistances r_circle_coords = [((r/(r+1), 0), 1/(r + 1)) for r in rs] # find coords for constant X circles intercept_angles = np.radians(intercept_angles) xs = np.sin(intercept_angles)/(1 - np.cos(intercept_angles)) # convert to desired reactances x_circle_coords = [((1, 1/x), abs(1/x)) for x in xs] return r_circle_coords, x_circle_coords, rs, xs def draw_impedance_circles(self, intercept_x_coords, intercept_angles, labels=False): r_circle_coords, x_circle_coords, rs, xs = self._impedance_circle_coords(intercept_x_coords, intercept_angles) for center, radius in chain(r_circle_coords, x_circle_coords): c = Circle(center, radius, **self.patch_options_dark) c.set_clip_path(self.smith_circle) c.set_clip_box(self.ax.bbox) self.ax.add_patch(c) if labels: for x, r in zip(intercept_x_coords, rs): self.ax.text(x + 0.04, 0.03, '%.0f' % round(self.z0*r), **self.label_options) for a, x in zip(intercept_angles, xs): r = (a - 90) if x > 0 else (a + 90) a = np.radians(a) d = 1.04 self.ax.text(d*cos(a), d*sin(a), '%.0fj' % round(self.z0*x), rotation=r, **self.label_options) def draw_admittance_circles(self, intercept_x_coords, intercept_angles, labels=False): r_circle_coords, x_circle_coords, rs, xs = self._impedance_circle_coords(intercept_x_coords, intercept_angles) # admittance circles have same coords as impedance ones, except flipped # on the y-axis for (x, y), radius in chain(r_circle_coords, x_circle_coords): c = Circle((-x, -y), radius, **self.patch_options_light) c.set_clip_path(self.smith_circle) c.set_clip_box(self.ax.bbox) self.ax.add_patch(c) if labels: for x, r in zip(intercept_x_coords, rs): self.ax.text(-x, 0, '%.1f' % (1/(50*r)), **self.label_options) for a, x in zip(intercept_angles, xs): r = (a - 90) if x < 0 else (a + 90) a = np.radians(a) self.ax.text(cos(pi - a), sin(pi - a), '%.1f' % (1/(50*x)), rotation=r, **self.label_options) def draw_vswr_circles(self, vswr_radii, labels=False): for r in vswr_radii: c = Circle((0, 0), r, ls='dashed', **self.patch_options_light) c.set_clip_path(self.smith_circle) c.set_clip_box(self.ax.bbox) self.ax.add_patch(c) if labels: for r in vswr_radii: if r > 0: vswr = (1 + r)/(1 - r) self.ax.text(0, r, '%.1f' % vswr, **self.label_options) def draw_chart_axes(self): # make outer circle self.smith_circle = Circle((0, 0), 1, transform=self.ax.transData, fc='none', **self.patch_options_axis) self.ax.add_patch(self.smith_circle) # make constant r=1 circle z0_circle = Circle((0.5, 0), 0.5, transform=self.ax.transData, fc='none', **self.patch_options_axis) z0_circle.set_clip_path(self.smith_circle) z0_circle.set_clip_box(self.ax.bbox) self.ax.add_patch(z0_circle) # make x-axis line = Line2D([-1,1],[0,0], **self.patch_options_axis) line.set_clip_path(self.smith_circle) line.set_clip_box(self.ax.bbox) self.ax.add_line(line) def draw_smith_chart(self, admittance, labels): # plot options for constant z/y circles and axes self.patch_options_light = {'fc':'none', 'color':'#474959', 'alpha':0.2, 'lw':1} self.patch_options_dark = {'fc':'none', 'color':'#474959', 'alpha':0.5, 'lw':1} self.patch_options_axis = {'color':'black', 'alpha':0.8, 'lw':1.5} # options for z/y circle labels self.label_options = {'ha':'center', 'va':'center', 'size':'9', 'alpha':0.5}#, #'bbox':dict(fc='white', ec='none', alpha=0.5)} #self.label_options = {'ha':'center', 'va':'center', 'size':'10', 'alpha':0.5} # x-axis coordinates where constant R circles will intersect intercept_x_coords = arange(-0.75, 1, 0.25) # angles where constant X circles will intersect (in degrees relative # to positive x-axis) intercept_angles = arange(40, 360, 40) # radii for vswr circles vswr_radii = arange(0, 1, 0.2) self.draw_chart_axes() self.draw_impedance_circles(intercept_x_coords, intercept_angles, labels) self.draw_admittance_circles(intercept_x_coords, intercept_angles, labels=0) self.draw_vswr_circles(vswr_radii, labels) self.ax.grid(0) self.ax.axis('equal') self.ax.axis(np.array([-1.1, 1.1, -1.1, 1.1])) self.save_background() def enable_cursor(self): self.cid_on_mouse_move = self.fig.canvas.mpl_connect('motion_notify_event', self._on_mouse_move) self.fig.canvas.mpl_connect('button_press_event', self._on_mouse_press) #self.cid_on_mouse_leave = self.fig.canvas.mpl_connect('axes_leave_event', self._on_mouse_leave) #self.cid_resize = self.fig.canvas.mpl_connect('resize_event', self._resize) self.cid_draw = self.fig.canvas.mpl_connect('draw_event', self._draw) self.cursor_text = Text(0.7, 0.1, 'n/a', horizontalalignment='left', verticalalignment='center', #bbox=dict(facecolor='white', alpha=1, ec='gray', pad=10), color='white', fontsize='small', alpha=0.8, backgroundcolor='gray', family='monospace', clip_box=self.ax.bbox, animated=True, transform = self.ax.transAxes) self.ax.add_artist(self.cursor_text) self.circle_matched_term = Circle((100,100), 0.02, alpha=0.5, color='green', animated=True) self.ax.add_patch(self.circle_matched_term) def plot_circle(self, center, radius, text='', text_color='black', circle_color='red',\ filled=False, circle_alpha=0.2, linestyle='solid', hatch=None): text_alpha = 0.7 text_x_offset = 0.15 text_y_offset = 0.1 # calculate position for text a, b = center # find closet point to edge of circle x = a*(1 - radius/sqrt(a**2 + b**2)) y = b*(1 - radius/sqrt(a**2 + b**2)) dist_to_circle = sqrt(x**2 + y**2) #print 'dist to sphere: ', sqrt(x**2 + y**2) if (x**2 + y**2) == 1: text_x_offset *= -1 text_y_offset *= -1 #textpos = ((a - x)/radius + text_x_offset, (b - y)/radius + text_y_offset) textpos = (x/dist_to_circle + text_x_offset, y/dist_to_circle + text_y_offset) else: textpos = (x + text_x_offset, y + text_y_offset) #print 'textpos: ', textpos # make actual circle c = Circle(center, radius, fc=circle_color, ec='white', alpha=circle_alpha, fill=filled, linestyle=linestyle, hatch=hatch) self.ax.add_patch(c) self.ax.annotate(text, (x, y), color=text_color,\ fontsize='small', alpha=text_alpha, xycoords='data', xytext=textpos,\ arrowprops=dict(arrowstyle="->", alpha=text_alpha,\ connectionstyle="arc3,rad=0.17")) def draw_stability_circles(self, two_port, plane='both', label=None): filled = True if plane == 'source' or plane == 'both': for i, (center, radius, circle_stable) in enumerate(zip(*two_port.source_stability_circle())): if circle_stable: hatch = None color = 'green' else: hatch = '/' color = 'red' if label is None: label_actual = '\n(%0.2f MHz)' % (two_port.f[i]/1e6) if two_port.f is not None else '' label_actual = 'Source' + label_actual else: label_actual = label self.plot_circle((center.real, center.imag), radius, text=label_actual, filled=filled,\ text_color='black', circle_color=color, hatch=hatch) if plane == 'load' or plane == 'both': for i, (center, radius, circle_stable) in enumerate(zip(*two_port.load_stability_circle())): if circle_stable: hatch = None color = 'green' else: hatch = '/' color = 'red' if label is None: label_actual = '\n(%0.2f MHz)' % (two_port.f[i]/1e6) if two_port.f is not None else '' label_actual = 'Load' + label_actual else: label_actual = label self.plot_circle((center.real, center.imag), radius, text=label_actual, filled=filled,\ text_color='black', circle_color=color, hatch=hatch) self.save_background() def plot_gain_circles(self, two_port, gains_db=None, plane='source', \ gain_cursor=True, surface=False): self.two_port = two_port self.gain_cursor = gain_cursor self.current_plane = plane max_gain = self.two_port.g_max() if (self.two_port.kt() < 1).any(): max_gain = self.two_port.max_double_sided_mismatched_gain() if gains_db == None: gains_db = np.trunc(10*db(max_gain)[0]*linspace(0.5, 1, 4))/10 if surface: filled = False circle_alpha = 0.7 linestyle = 'dashed' else: filled = True circle_alpha = 0.2 linestyle = 'solid' for g in gains_db: if plane == 'source': center, radius = self.two_port.available_gain_circle(un_db(g)) self.ax.set_title('Source plane') elif plane == 'load': center, radius = self.two_port.operating_gain_circle(un_db(g)) self.ax.set_title('Load plane') text = str(g) + ' dB' self.plot_circle((center[0].real, center[0].imag), radius[0], text=text, filled=filled,\ text_color='black', circle_color='orange', circle_alpha=circle_alpha,\ linestyle=linestyle) if not surface: self.save_background() return num_segments = 1000 i, r = meshgrid(linspace(-1.1, 1.1, num_segments), linspace(-1.1, 1.1, num_segments)) gamma = i + 1j*r term = OnePort(s=gamma.reshape(-1)) if plane == 'source': g = self.two_port.g_a(term) elif plane == 'load': g = self.two_port.g_p(term) g = db(g).reshape(num_segments, num_segments) g[abs(gamma) > 1] = nan im = self.ax.imshow(g, origin='lower', extent=(-1.1, 1.1, -1.1, 1.1), interpolation='bicubic', alpha=0.9) im.set_clim(gains_db[0], db(max_gain)) self.save_background() def _on_mouse_press(self, event): if event.button == 3: print 'clearing' self.fig.canvas.restore_region(self.background, bbox=self.ax.bbox) def _on_mouse_move(self, event): if event.xdata is None or event.ydata is None: return gamma = event.xdata + 1j*event.ydata cursor_port = OnePort(s=gamma) self.fig.canvas.restore_region(self.background, bbox=self.ax.bbox) self.update_gain_cursor(cursor_port) self.update_info_box(cursor_port) #self.fig.canvas.draw() self.fig.canvas.blit(self.ax.bbox) def update_gain_cursor(self, cursor_port): if not self.gain_cursor or self.two_port is None: return if self.current_plane == 'source': term_matched = (cursor_port*self.two_port).out().conj() term_resulting = (self.two_port*term_matched).inp() else: term_matched = (self.two_port*cursor_port).inp().conj() term_resulting = (term_matched*self.two_port).out() self.circle_matched_term.center = real(term_matched.s), imag(term_matched.s) if abs(term_matched.s) > 1 or abs(term_resulting.s) > 1: self.circle_matched_term.set_color('r') else: self.circle_matched_term.set_color('g') self.ax.draw_artist(self.circle_matched_term) def update_info_box(self, cursor_port): z = cursor_port.z y = cursor_port.y data = '$\\Gamma$ = {:>7.2f} $\\angle$ {:>+8.3f}$^{{\\circ}}$'.format(float(abs(cursor_port.s)), float(degrees(angle(cursor_port.s)))) data += '\nVSWR = {:>7.2f}'.format(float(cursor_port.vswr())) data += '\nMM = {:>7.2f} dB'.format(float(db(cursor_port.mismatch()))) data += '\nZ = {:>7.2f}{:>+8.2f}j '.format(float(real(z)), float(imag(z))) if self.two_port is not None: if self.current_plane == 'source': term_matched = (cursor_port*self.two_port).out().conj() gain = self.two_port.g_t(cursor_port, term_matched) else: term_matched = (self.two_port*cursor_port).inp().conj() gain = self.two_port.g_t(term_matched, cursor_port) x = float(imag(z)) w = 2*pi*self.two_port.f[0] if x > 0: hf = 'H' lc = x/w else: hf = 'F' lc = 1/(w*x) val, prefix = to_eng_form(abs(lc)) data += '({:>3.2f} {}{}) '.format(val, prefix, hf) data += '$\\Omega$' data += '\n = {:>7.2f} // {:>+8.2f}j '.format(float(1/real(y)), float(-1/imag(y))) if self.two_port is not None: x = float(-1/imag(y)) w = 2*pi*self.two_port.f[0] if x > 0: hf = 'H' lc = x/w else: hf = 'F' lc = 1/(w*x) val, prefix = to_eng_form(abs(lc)) data += '({:>3.2f} {}{}) '.format(val, prefix, hf) data += '$\\Omega$' if self.gain_cursor and self.two_port is not None: gain_str = '{:>7.2f} dB'.format(float(db(gain))) if gain > 0 else 'n/a' data += '\nG = ' + gain_str self.cursor_text.set_text(data) self.ax.draw_artist(self.cursor_text) def plot_s_param(self, s, color='blue'): self.plot_line(s, color) self.save_background() def plot_line(self, points, color='blue'): r, t = abs(points), angle(points) l = Line2D(r*cos(t), r*sin(t), color=color) self.ax.add_line(l) def save_background(self): self.fig.canvas.draw() self.background = self.fig.canvas.copy_from_bbox(self.ax.bbox) def _on_mouse_leave(self, event): pass def _resize(self, event): self.save_background() print 'resize\n' #self.ax.draw(None) #self.fig.canvas.draw() #self.fig.canvas.restore_region(self.background, bbox=self.ax.bbox) def _draw(self, event): self.fig.canvas.mpl_disconnect(self.cid_draw) #self.fig.canvas.restore_region(self.background, bbox=self.ax.bbox) self.save_background() self.cid_draw = self.fig.canvas.mpl_connect('draw_event', self._draw)
class Annotate(object): def __init__(self, cloud, selection_shape, z_color=False, unlabeled_color = (1,0,0), labeled_color = (0,0,1)): self.selection_shape = selection_shape self.unlabeled_color = np.array(unlabeled_color) self.labeled_color = np.array(labeled_color) assert not np.all(unlabeled_color == labeled_color) self.fig = plt.figure('label rope ends', figsize=(24,12)) self.fig.clear() self.ax = self.fig.add_subplot(111, aspect='equal') if cloud.shape[1] == 6: self.cloud = cloud else: self.cloud = np.c_[cloud[:,:3], np.tile(self.unlabeled_color, (cloud.shape[0],1))] if z_color: z_min = self.cloud[:,2].min() z_max = self.cloud[:,2].max() self.z_color = np.empty((len(self.cloud),3)) for i in range(len(self.cloud)): f = (self.cloud[i,2] - z_min) / (z_max - z_min) self.z_color[i,:] = np.array(colorsys.hsv_to_rgb(f,1,1)) else: self.z_color = None self.scatters = [] self.rescatter_cloud() self.ax.autoscale(False) if self.selection_shape == 'rectangle' or self.selection_shape == 'square': self.rect = Rectangle((0,0), 0, 0, facecolor='None', edgecolor='green', linestyle='dashed') self.ax.add_patch(self.rect) elif self.selection_shape == 'circle': self.circle = Circle((0,0), 0, facecolor='None', edgecolor='green', linestyle='dashed') self.ax.add_patch(self.circle) self.x0 = None self.y0 = None self.x1 = None self.y1 = None self.fig.canvas.mpl_connect('button_press_event', self.on_press) self.fig.canvas.mpl_connect('button_release_event', self.on_release) self.motion_notify_cid = None self.fig.canvas.mpl_connect('key_press_event', self.on_key) plt.show() def rescatter_cloud(self): for scatter in self.scatters: scatter.remove() self.scatters = [] if self.z_color is not None: ul_inds = np.absolute((self.cloud[:,3:] - self.unlabeled_color)).sum(axis=1) == 0 # unlabeled inds self.scatters.append(plt.scatter(self.cloud[ul_inds,0], self.cloud[ul_inds,1], c=self.z_color[ul_inds,:], edgecolors=self.z_color[ul_inds,:], marker=',', s=5)) self.scatters.append(plt.scatter(self.cloud[~ul_inds,0], self.cloud[~ul_inds,1], c=self.cloud[~ul_inds,3:], edgecolors=self.cloud[~ul_inds,3:], marker='o', s=20)) else: self.scatters.append(plt.scatter(self.cloud[:,0], self.cloud[:,1], c=self.cloud[:,3:], edgecolors=self.cloud[:,3:], marker=',', s=5)) def on_press(self, event): if event.xdata < self.ax.get_xlim()[0] or event.xdata > self.ax.get_xlim()[1] or \ event.ydata < self.ax.get_ylim()[0] or event.ydata > self.ax.get_ylim()[1]: return self.x0 = event.xdata self.y0 = event.ydata self.motion_notify_cid = self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion) def on_release(self, event): if self.motion_notify_cid: self.fig.canvas.mpl_disconnect(self.motion_notify_cid) self.motion_notify_cid = None if self.selection_shape == 'rectangle' or self.selection_shape == 'square': x0 = min(self.x0, self.x1) x1 = max(self.x0, self.x1) y0 = min(self.y0, self.y1) y1 = max(self.y0, self.y1) inside_rect_inds = (x0 <= self.cloud[:,0]) * (self.cloud[:,0] <= x1) * (y0 <= self.cloud[:,1]) * (self.cloud[:,1] <= y1) num_pts_inside_rect = inside_rect_inds.sum() self.cloud[inside_rect_inds,3:] = np.tile(self.labeled_color, (num_pts_inside_rect,1)) elif self.selection_shape == 'circle': inside_circle_inds = np.apply_along_axis(np.linalg.norm, 1, self.cloud[:,:2] - np.array(self.circle.center)) <= self.circle.get_radius() num_pts_inside_circle = inside_circle_inds.sum() self.cloud[inside_circle_inds,3:] = np.tile(self.labeled_color, (num_pts_inside_circle,1)) self.rescatter_cloud() plt.draw() def on_motion(self, event): if event.xdata < self.ax.get_xlim()[0] or event.xdata > self.ax.get_xlim()[1] or \ event.ydata < self.ax.get_ylim()[0] or event.ydata > self.ax.get_ylim()[1]: return if self.selection_shape == 'rectangle': self.x1 = event.xdata self.y1 = event.ydata elif self.selection_shape == 'circle' or self.selection_shape == 'square': side = max(abs(event.xdata - self.x0), abs(event.ydata - self.y0)) self.x1 = self.x0 + np.sign(event.xdata - self.x0) * side self.y1 = self.y0 + np.sign(event.ydata - self.y0) * side if self.selection_shape == 'rectangle' or self.selection_shape == 'square': self.rect.set_width(self.x1 - self.x0) self.rect.set_height(self.y1 - self.y0) self.rect.set_xy((self.x0, self.y0)) elif self.selection_shape == 'circle': self.circle.center = ((self.x1 + self.x0)/2.0, (self.y0 + self.y1)/2.0) self.circle.set_radius(side/2.0) plt.draw() def on_key(self, event): if event.key == 'q': sys.exit(0) if event.key == 'd': plt.close(self.fig)
def plot_state_qsphere(state, figsize=None, ax=None, show_state_labels=True, show_state_phases=False, use_degrees=False, *, rho=None): """Plot the qsphere representation of a quantum state. Here, the size of the points is proportional to the probability of the corresponding term in the state and the color represents the phase. Args: state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state. figsize (tuple): Figure size in inches. ax (matplotlib.axes.Axes): An optional Axes object to be used for the visualization output. If none is specified a new matplotlib Figure will be created and used. Additionally, if specified there will be no returned Figure since it is redundant. show_state_labels (bool): An optional boolean indicating whether to show labels for each basis state. show_state_phases (bool): An optional boolean indicating whether to show the phase for each basis state. use_degrees (bool): An optional boolean indicating whether to use radians or degrees for the phase values in the plot. Returns: Figure: A matplotlib figure instance if the ``ax`` kwag is not set Raises: ImportError: Requires matplotlib. VisualizationError: if input is not a valid N-qubit state. QiskitError: Input statevector does not have valid dimensions. Example: .. jupyter-execute:: from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_qsphere %matplotlib inline qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = Statevector.from_instruction(qc) plot_state_qsphere(state) """ if not HAS_MATPLOTLIB: raise ImportError('Must have Matplotlib installed. To install, run "pip install ' 'matplotlib".') try: import seaborn as sns except ImportError: raise ImportError('Must have seaborn installed to use ' 'plot_state_qsphere. To install, run "pip install seaborn".') rho = DensityMatrix(state) num = rho.num_qubits if num is None: raise VisualizationError("Input is not a multi-qubit quantum state.") # get the eigenvectors and eigenvalues eigvals, eigvecs = linalg.eigh(rho.data) if figsize is None: figsize = (7, 7) if ax is None: return_fig = True fig = plt.figure(figsize=figsize) else: return_fig = False fig = ax.get_figure() gs = gridspec.GridSpec(nrows=3, ncols=3) ax = fig.add_subplot(gs[0:3, 0:3], projection='3d') ax.axes.set_xlim3d(-1.0, 1.0) ax.axes.set_ylim3d(-1.0, 1.0) ax.axes.set_zlim3d(-1.0, 1.0) ax.axes.grid(False) ax.view_init(elev=5, azim=275) # start the plotting # Plot semi-transparent sphere u = np.linspace(0, 2 * np.pi, 25) v = np.linspace(0, np.pi, 25) x = np.outer(np.cos(u), np.sin(v)) y = np.outer(np.sin(u), np.sin(v)) z = np.outer(np.ones(np.size(u)), np.cos(v)) ax.plot_surface(x, y, z, rstride=1, cstride=1, color='k', alpha=0.05, linewidth=0) # Get rid of the panes ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) # Get rid of the spines ax.w_xaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) ax.w_yaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) ax.w_zaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) # Get rid of the ticks ax.set_xticks([]) ax.set_yticks([]) ax.set_zticks([]) # traversing the eigvals/vecs backward as sorted low->high for idx in range(eigvals.shape[0]-1, -1, -1): if eigvals[idx] > 0.001: # get the max eigenvalue state = eigvecs[:, idx] loc = np.absolute(state).argmax() # remove the global phase from max element angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi) angleset = np.exp(-1j * angles) state = angleset * state d = num for i in range(2 ** num): # get x,y,z points element = bin(i)[2:].zfill(num) weight = element.count("1") zvalue = -2 * weight / d + 1 number_of_divisions = n_choose_k(d, weight) weight_order = bit_string_index(element) angle = (float(weight) / d) * (np.pi * 2) + \ (weight_order * 2 * (np.pi / number_of_divisions)) if (weight > d / 2) or ((weight == d / 2) and (weight_order >= number_of_divisions / 2)): angle = np.pi - angle - (2 * np.pi / number_of_divisions) xvalue = np.sqrt(1 - zvalue ** 2) * np.cos(angle) yvalue = np.sqrt(1 - zvalue ** 2) * np.sin(angle) # get prob and angle - prob will be shade and angle color prob = np.real(np.dot(state[i], state[i].conj())) if prob > 1: # See https://github.com/Qiskit/qiskit-terra/issues/4666 prob = 1 colorstate = phase_to_rgb(state[i]) alfa = 1 if yvalue >= 0.1: alfa = 1.0 - yvalue if not np.isclose(prob, 0) and show_state_labels: rprime = 1.3 angle_theta = np.arctan2(np.sqrt(1 - zvalue ** 2), zvalue) xvalue_text = rprime * np.sin(angle_theta) * np.cos(angle) yvalue_text = rprime * np.sin(angle_theta) * np.sin(angle) zvalue_text = rprime * np.cos(angle_theta) element_text = '$\\vert' + element + '\\rangle$' if show_state_phases: element_angle = (np.angle(state[i]) + (np.pi * 4)) % (np.pi * 2) if use_degrees: element_text += '\n$%.1f^\\circ$' % (element_angle * 180/np.pi) else: element_angle = pi_check(element_angle, ndigits=3).replace('pi', '\\pi') element_text += '\n$%s$' % (element_angle) ax.text(xvalue_text, yvalue_text, zvalue_text, element_text, ha='center', va='center', size=12) ax.plot([xvalue], [yvalue], [zvalue], markerfacecolor=colorstate, markeredgecolor=colorstate, marker='o', markersize=np.sqrt(prob) * 30, alpha=alfa) a = Arrow3D([0, xvalue], [0, yvalue], [0, zvalue], mutation_scale=20, alpha=prob, arrowstyle="-", color=colorstate, lw=2) ax.add_artist(a) # add weight lines for weight in range(d + 1): theta = np.linspace(-2 * np.pi, 2 * np.pi, 100) z = -2 * weight / d + 1 r = np.sqrt(1 - z ** 2) x = r * np.cos(theta) y = r * np.sin(theta) ax.plot(x, y, z, color=(.5, .5, .5), lw=1, ls=':', alpha=.5) # add center point ax.plot([0], [0], [0], markerfacecolor=(.5, .5, .5), markeredgecolor=(.5, .5, .5), marker='o', markersize=3, alpha=1) else: break n = 64 theta = np.ones(n) ax2 = fig.add_subplot(gs[2:, 2:]) ax2.pie(theta, colors=sns.color_palette("hls", n), radius=0.75) ax2.add_artist(Circle((0, 0), 0.5, color='white', zorder=1)) offset = 0.95 # since radius of sphere is one. if use_degrees: labels = ['Phase\n(Deg)', '0', '90', '180 ', '270'] else: labels = ['Phase', '$0$', '$\\pi/2$', '$\\pi$', '$3\\pi/2$'] ax2.text(0, 0, labels[0], horizontalalignment='center', verticalalignment='center', fontsize=14) ax2.text(offset, 0, labels[1], horizontalalignment='center', verticalalignment='center', fontsize=14) ax2.text(0, offset, labels[2], horizontalalignment='center', verticalalignment='center', fontsize=14) ax2.text(-offset, 0, labels[3], horizontalalignment='center', verticalalignment='center', fontsize=14) ax2.text(0, -offset, labels[4], horizontalalignment='center', verticalalignment='center', fontsize=14) if return_fig: if get_backend() in ['module://ipykernel.pylab.backend_inline', 'nbAgg']: plt.close(fig) return fig
def circles(x, y, s, c='b', vmin=None, vmax=None, **kwargs): """ Make a scatter of circles plot of x vs y, where x and y are sequence like objects of the same lengths. The size of circles are in data scale. Parameters ---------- x,y : scalar or array_like, shape (n, ) Input data s : scalar or array_like, shape (n, ) Radius of circle in data unit. c : color or sequence of color, optional, default : 'b' `c` can be a single color format string, or a sequence of color specifications of length `N`, or a sequence of `N` numbers to be mapped to colors using the `cmap` and `norm` specified via kwargs. Note that `c` should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. (If you insist, use `color` instead.) `c` can be a 2-D array in which the rows are RGB or RGBA, however. vmin, vmax : scalar, optional, default: None `vmin` and `vmax` are used in conjunction with `norm` to normalize luminance data. If either are `None`, the min and max of the color array is used. kwargs : `~matplotlib.collections.Collection` properties Eg. alpha, edgecolor(ec), facecolor(fc), linewidth(lw), linestyle(ls), norm, cmap, transform, etc. Returns ------- paths : `~matplotlib.collections.PathCollection` Examples -------- a = np.arange(11) circles(a, a, a*0.2, c=a, alpha=0.5, edgecolor='none') plt.colorbar() License -------- This code is under [The BSD 3-Clause License] (http://opensource.org/licenses/BSD-3-Clause) """ if np.isscalar(c): kwargs.setdefault('color', c) c = None if 'fc' in kwargs: kwargs.setdefault('facecolor', kwargs.pop('fc')) if 'ec' in kwargs: kwargs.setdefault('edgecolor', kwargs.pop('ec')) if 'ls' in kwargs: kwargs.setdefault('linestyle', kwargs.pop('ls')) if 'lw' in kwargs: kwargs.setdefault('linewidth', kwargs.pop('lw')) patches = [Circle((x_, y_), s_) for x_, y_, s_ in np.broadcast(x, y, s)] collection = PatchCollection(patches, **kwargs) if c is not None: collection.set_array(np.asarray(c)) collection.set_clim(vmin, vmax) ax = plt.gca() ax.add_collection(collection) ax.autoscale_view() if c is not None: plt.sci(collection) return collection
def myscatter(ax, colormap, x, y, radii, colors): for x1,y1,r,c in zip(x, y, radii, colormap(colors)): ax.add_patch(Circle((x1,y1), r, fc=c))
class BallBeam(): """ BallBeam Simple ball and beam simulation built to interface easily with OpenAI's gym environments. System dynamics --------------- dx/dt = v(t) dv/dt = -m*g*sin(theta(t))/((I + 1)*m) Parameters ---------- time_step : time of one simulation step, float (s) beam_length : length of beam, float (units) max_angle : max of abs(angle), float (rads) init_velocity : initial speed of ball, float (units/s) """ def __init__(self, timestep=0.01, beam_length=1.08, max_angle=20*3.14/180, init_velocity=0.0): self.dt = timestep # time step self.g = 9.82 # gravity self.r = 0.0159 # ball radius self.L = beam_length # beam length self.I = (2/5*self.r**2 ) # solid ball inertia (omits mass) self.init_velocity = init_velocity # initial velocity self.max_angle = max_angle # max beam angle (rad) self.reset() self.human_rendered = False self.machine_rendered = False def reset(self): radius = self.L/2 # beam radius self.t = 0.0 # time self.x = 0.4 # ball position x self.y = self.r # ball position y self.v = self.init_velocity # ball velocity self.theta = 0.0 # beam angle (rad) self.dtheta = 0.0 # beam angle change (rad) self.v_x = 0.0 # velocity x component self.v_y = 0.0 # velocity y component self.lim_x = [-cos(self.theta)*radius, # geam limits x cos(self.theta)*radius] self.lim_y = [-sin(self.theta)*radius, # beam limits y sin(self.theta)*radius] def update(self, angle): """ Update simulation with one time step Parameters ---------- angle : angle the beam should be set to, float (rad) """ radius = self.L/2 # simulation could be improved further by using voltage as input and a # motor simulation deciding theta theta = max(-self.max_angle, min(self.max_angle, angle)) # store angle change for angular velocity self.dtheta = (theta - self.theta) self.theta = theta if self.on_beam: x = self.x y = self.y # dynamics on beam self.v += (x*self.dtheta*self.dtheta-self.g*sin(self.theta))*(5/7)*self.dt self.x += self.v*self.dt self.y = self.r/cos(self.theta) + self.x*sin(self.theta) # keep track of velocities for x and y self.v_x = (self.x - x)/self.dt self.v_y = (self.y - y)/self.dt else: # free fall dynamics off beam self.v_y -= self.g*self.dt self.v = (self.v_x**2 + self.v_y**2)**0.5 self.x += self.v_x*self.dt self.y += self.v_y*self.dt # edge of beam self.lim_x = [-cos(self.theta)*radius, cos(self.theta)*radius] self.lim_y = [-sin(self.theta)*radius, sin(self.theta)*radius] # update time self.t += self.dt def _init_render(self, setpoint, mode): """ Initialize rendering """ radius = self.L/2 if mode == 'human': self.human_rendered = True plt.ion() fig, ax = plt.subplots(1, 1, figsize=(8, 4)) fig.canvas.set_window_title('Beam & Ball') ax.set(xlim = (-2*radius, 2*radius), ylim = (-self.L/2, self.L/2)) # draw ball self.ball_plot = Circle((self.x, self.y), self.r) ax.add_patch(self.ball_plot) ax.patches[0].set_color('red') # draw beam ax.plot([-cos(self.theta)*radius, cos(self.theta)*radius], [-sin(self.theta)*radius, sin(self.theta)*radius], lw=4, color='black') ax.plot(0.0, 0.0, '.', ms=20) if setpoint is not None: ax.add_patch(Polygon( \ [[setpoint*cos(self.theta), -0.01*self.L + setpoint*sin(self.theta)], [setpoint*cos(self.theta) - 0.015*self.L, -0.03*self.L + setpoint*sin(self.theta)], [setpoint*cos(self.theta) + 0.015*self.L, -0.03*self.L + setpoint*sin(self.theta)]])) ax.patches[1].set_color('red') self.fig = fig self.ax = ax else: self.machine_rendered = True fig, ax = plt.subplots(1, 1, figsize=(8, 4)) # avoid drawing plot but still initialize _ = fig.canvas.set_window_title('Beam & Ball') _ = ax.set(xlim = (-2*radius, 2*radius), ylim = (-self.L/2, self.L/2)) # draw ball self.ball_plot = Circle((self.x, self.y), self.r) _ = ax.add_patch(self.ball_plot) _ = ax.patches[0].set_color('red') # draw beam _ = ax.plot([-cos(self.theta)*radius, cos(self.theta)*radius], [-sin(self.theta)*radius, sin(self.theta)*radius], lw=4, color='black') _ = ax.plot(0.0, 0.0, '.', ms=20) if setpoint is not None: _ = ax.add_patch(Polygon( \ [[setpoint*cos(self.theta), -0.01*self.L + setpoint*sin(self.theta)], [setpoint*cos(self.theta) - 0.015*self.L, -0.03*self.L + setpoint*sin(self.theta)], [setpoint*cos(self.theta) + 0.015*self.L, -0.03*self.L + setpoint*sin(self.theta)]])) _ = ax.patches[1].set_color('red') self.machine_fig = fig self.machine_ax = ax def render(self, setpoint=None, mode='human'): """ Render simulation at it's current state Parameters ---------- setpoint : optional marking of the ball setpoint, float (units) mode : rendering mode, str [human, machine] """ if (not self.human_rendered and mode == 'human') or \ (not self.machine_rendered and mode == 'machine'): self._init_render(setpoint, mode) if mode == 'human': # update ball self.ball_plot.set_center((self.x, self.y)) # update beam self.ax.lines[0].set(xdata=self.lim_x, ydata=self.lim_y) # mark setpoint if setpoint is not None: self.ax.patches[1].set_xy( \ [[setpoint*cos(self.theta), -0.01*self.L + setpoint*sin(self.theta)], [setpoint*cos(self.theta) - 0.015*self.L, -0.03*self.L + setpoint*sin(self.theta)], [setpoint*cos(self.theta) + 0.015*self.L, -0.03*self.L + setpoint*sin(self.theta)]]) # update figure self.fig.canvas.draw() self.fig.canvas.flush_events() else: # update ball _ = self.ball_plot.set_center((self.x, self.y)) # update beam _ = self.machine_ax.lines[0].set(xdata=self.lim_x, ydata=self.lim_y) # mark setpoint if setpoint is not None: _ = self.machine_ax.patches[1].set_xy( \ [[setpoint*cos(self.theta), -0.01*self.L + setpoint*sin(self.theta)], [setpoint*cos(self.theta) - 0.015*self.L, -0.03*self.L + setpoint*sin(self.theta)], [setpoint*cos(self.theta) + 0.015*self.L, -0.03*self.L + setpoint*sin(self.theta)]]) # update figure _ = self.machine_fig.canvas.draw() _ = self.machine_fig.canvas.flush_events() @property def on_beam(self): """ Check if ball is still on the beam Returns ------- on_beam : if ball is still located on the beam, bool """ return self.lim_x[0] < self.x and self.lim_x[1] > self.x
def __init__(self, map, schedule): self.map = map self.schedule = schedule aspect = map["map"]["dimensions"][0] / map["map"]["dimensions"][1] self.fig = plt.figure(frameon=False, figsize=(4 * aspect, 4)) self.ax = self.fig.add_subplot(111, aspect='equal') self.fig.subplots_adjust(left=0, right=1, bottom=0, top=1, wspace=None, hspace=None) # self.ax.set_frame_on(False) self.patches = [] self.artists = [] self.agents = dict() self.agent_names = dict() # create boundary patch xmin = -0.5 ymin = -0.5 xmax = map["map"]["dimensions"][0] - 0.5 ymax = map["map"]["dimensions"][1] - 0.5 # self.ax.relim() plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) # self.ax.set_xticks([]) # self.ax.set_yticks([]) # plt.axis('off') # self.ax.axis('tight') # self.ax.axis('off') self.patches.append( Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, facecolor='none', edgecolor='red')) for o in map["map"]["obstacles"]: x, y = o[0], o[1] self.patches.append( Rectangle((x - 0.5, y - 0.5), 1, 1, facecolor='red', edgecolor='red')) # create agents: self.T = 0 # draw goals first for d, i in zip(map["agents"], range(0, len(map["agents"]))): if "goal" in d: goals = [d["goal"]] if "potentialGoals" in d: goals = [goal for goal in d["potentialGoals"]] for goal in goals: self.patches.append( Rectangle((goal[0] - 0.25, goal[1] - 0.25), 0.5, 0.5, facecolor=Colors[i % len(Colors)], edgecolor='black', alpha=0.5)) for d, i in zip(map["agents"], range(0, len(map["agents"]))): name = d["name"] self.agents[name] = Circle((d["start"][0], d["start"][1]), 0.3, facecolor=Colors[i % len(Colors)], edgecolor='black') self.agents[name].original_face_color = Colors[i % len(Colors)] self.patches.append(self.agents[name]) self.T = max(self.T, schedule["schedule"][name][-1]["t"]) self.agent_names[name] = self.ax.text(d["start"][0], d["start"][1], name.replace('agent', '')) self.agent_names[name].set_horizontalalignment('center') self.agent_names[name].set_verticalalignment('center') self.artists.append(self.agent_names[name]) # self.ax.set_axis_off() # self.fig.axes[0].set_visible(False) # self.fig.axes.get_yaxis().set_visible(False) # self.fig.tight_layout() self.anim = animation.FuncAnimation(self.fig, self.animate_func, init_func=self.init_func, frames=int(self.T + 1) * 10, interval=100, blit=True)
def circles(self, x, y, s, c='b', vmin=None, vmax=None, **kwargs): """ See https://gist.github.com/syrte/592a062c562cd2a98a83 Make a scatter plot of circles. Similar to plt.scatter, but the size of circles are in data scale. Parameters ---------- x, y : scalar or array_like, shape (n, ) Input data s : scalar or array_like, shape (n, ) Radius of circles. c : color or sequence of color, optional, default : 'b' `c` can be a single color format string, or a sequence of color specifications of length `N`, or a sequence of `N` numbers to be mapped to colors using the `cmap` and `norm` specified via kwargs. Note that `c` should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. (If you insist, use `color` instead.) `c` can be a 2-D array in which the rows are RGB or RGBA, however. vmin, vmax : scalar, optional, default: None `vmin` and `vmax` are used in conjunction with `norm` to normalize luminance data. If either are `None`, the min and max of the color array is used. kwargs : `~matplotlib.collections.Collection` properties Eg. alpha, edgecolor(ec), facecolor(fc), linewidth(lw), linestyle(ls), norm, cmap, transform, etc. Returns ------- paths : `~matplotlib.collections.PathCollection` Examples -------- a = np.arange(11) circles(a, a, s=a*0.2, c=a, alpha=0.5, ec='none') plt.colorbar() License -------- This code is under [The BSD 3-Clause License] (http://opensource.org/licenses/BSD-3-Clause) """ if np.isscalar(c): kwargs.setdefault('color', c) c = None if 'fc' in kwargs: kwargs.setdefault('facecolor', kwargs.pop('fc')) if 'ec' in kwargs: kwargs.setdefault('edgecolor', kwargs.pop('ec')) if 'ls' in kwargs: kwargs.setdefault('linestyle', kwargs.pop('ls')) if 'lw' in kwargs: kwargs.setdefault('linewidth', kwargs.pop('lw')) # You can set `facecolor` with an array for each patch, # while you can only set `facecolors` with a value for all. zipped = np.broadcast(x, y, s) patches = [Circle((x_, y_), s_) for x_, y_, s_ in zipped] collection = PatchCollection(patches, **kwargs) if c is not None: c = np.broadcast_to(c, zipped.shape).ravel() collection.set_array(c) collection.set_clim(vmin, vmax) ax = plt.gca() ax.add_collection(collection) ax.autoscale_view() # plt.draw_if_interactive() if c is not None: plt.sci(collection)
def extract_minutiae_cylinder(img_input, minutiae_input, ROI=None, num_ori=12, angle=None, processing=None): # for the latent or the low quality rolled print minutiae = minutiae_input.copy() img = img_input.copy() if processing == 'STFT': img = LP.STFT(img) elif processing == 'contrast': img = LP.local_constrast_enhancement(img) elif processing == 'texture': img = LP.FastCartoonTexture(img) sigma = 5**2 if ROI is not None: h, w = ROI.shape for i in range(h): for j in range(w): if ROI[i, j] == 0: img[i, j] = 255 h, w = ROI.shape col_sum = np.sum(ROI, axis=0) ind = [x for x in range(len(col_sum)) if col_sum[x] > 0] min_x = np.max([np.min(ind) - 32, 0]) max_x = np.min([np.max(ind) + 32, w]) row_sum = np.sum(ROI, axis=1) ind = [x for x in range(len(row_sum)) if row_sum[x] > 0] min_y = np.max([np.min(ind) - 32, 0]) max_y = np.min([np.max(ind) + 32, h]) ROI = ROI[min_y:max_y, min_x:max_x] img = img[min_y:max_y, min_x:max_x] minutiae[:, 0] = minutiae[:, 0] - min_x minutiae[:, 1] = minutiae[:, 1] - min_y else: h, w = img.shape[0:2] ROI = np.ones((h, w)) # rotate the image and ROI, and also update minutiae points h0, w0 = ROI.shape if angle is not None: h02 = (h0 + 1) / 2 w02 = (w0 + 1) / 2 img = rotate(img, angle) ROI = rotate(ROI, angle) h, w = ROI.shape h2 = (h + 1) / 2 w2 = (w + 1) / 2 angle = -angle / 180.0 * math.pi cosTheta = math.cos(angle) sinTheta = math.sin(angle) xx = (minutiae[:, 0] - w02) * cosTheta - (minutiae[:, 1] - h02) * sinTheta + w2 yy = (minutiae[:, 0] - w02) * sinTheta + (minutiae[:, 1] - h02) * cosTheta + h2 ori = minutiae[:, 2] - angle # minutiae[:, 0] = xx minutiae[:, 1] = yy minutiae[:, 2] = ori show = 0 if show: minu_num = minutiae.shape[0] fig, ax = plt.subplots(1) ax.set_aspect('equal') R = 10 arrow_len = 15 ax.imshow(img, cmap='gray') for i in range(0, minu_num): xx = minutiae[i, 0] yy = minutiae[i, 1] circ = Circle((xx, yy), R, color='r', fill=False) ax.add_patch(circ) ori = -minutiae[i, 2] dx = math.cos(ori) * arrow_len dy = math.sin(ori) * arrow_len ax.arrow(xx, yy, dx, dy, head_width=0.05, head_length=0.1, fc='r', ec='r') plt.show() h, w = ROI.shape minutiae_cylinder = np.zeros((h, w, num_ori), dtype=float) cylinder_ori = np.asarray(range(num_ori)) * math.pi * 2 / num_ori Y, X = np.mgrid[0:h, 0:w] minu_num = minutiae.shape[0] for i in range(0, minu_num): xx = minutiae[i, 0] yy = minutiae[i, 1] if yy < 0 or xx < 0: continue print xx, yy minu_num = minutiae.shape[0] fig, ax = plt.subplots(1) ax.set_aspect('equal') R = 10 arrow_len = 15 ax.imshow(img, cmap='gray') for i in range(0, minu_num): xx = minutiae[i, 0] yy = minutiae[i, 1] circ = Circle((xx, yy), R, color='r', fill=False) ax.add_patch(circ) ori = -minutiae[i, 2] dx = math.cos(ori) * arrow_len dy = math.sin(ori) * arrow_len ax.arrow(xx, yy, dx, dy, head_width=0.05, head_length=0.1, fc='r', ec='r') plt.show() weight = np.exp(-((X - xx) * (X - xx) + (Y - yy) * (Y - yy)) / sigma) ori = minutiae[i, 2] if ori < 0: ori += np.pi * 2 if ori > np.pi * 2: ori -= np.pi * 2 for j in range(num_ori): ori_diff = np.fabs(ori - cylinder_ori[j]) if ori_diff > np.pi * 2: ori_diff = ori_diff - np.pi * 2 ori_diff = np.min([ori_diff, np.pi * 2 - ori_diff]) minutiae_cylinder[:, :, j] += weight * np.exp(-ori_diff / np.pi * 6) show = 0 if show: fig, ax = plt.subplots(1) ax.set_aspect('equal') R = 10 arrow_len = 15 ax.imshow(img, cmap='gray') for i in range(0, minu_num): xx = minutiae[i, 0] yy = minutiae[i, 1] circ = Circle((xx, yy), R, color='r', fill=False) ax.add_patch(circ) ori = -minutiae[i, 2] dx = math.cos(ori) * arrow_len dy = math.sin(ori) * arrow_len ax.arrow(xx, yy, dx, dy, head_width=0.05, head_length=0.1, fc='r', ec='r') plt.show() return img, ROI, minutiae_cylinder
def circleFromRMS(xy, rad): cir = Circle(xy, rad) cir.set_clip_box(ax.bbox) cir.set_alpha(0.2) cir.set_facecolor(tableau20[0]) return cir
class CircleSpanSelector: """ Select a center/radius range of the circle for a matplotlib Axes Example usage: ax = subplot(111) ax.plot(x,y) def onselect(center, radius, x, y): print center, radius span = CircleSpanSelector(ax, onselect) """ def __init__(self, ax, onselect, minspan=None, useblit=False, circprops=None): """ Create a span selector in ax. When a selection is made, clear the span and call onselect with onselect(center, radius, x, y) where x and y are the coordinate used to calculate the radius and clear the span. If minspan is not None, ignore events smaller than minspan The span rect is drawn with rectprops; default circprops = dict(fc='blue', alpha=0.5) set the visible attribute to False if you want to turn off the functionality of the span selector """ if circprops is None: circprops = dict(fc='w', alpha=0.5) self.ax = ax self.visible = True self.canvas = ax.figure.canvas self.canvas.mpl_connect('motion_notify_event', self.onmove) self.canvas.mpl_connect('button_press_event', self.press) self.canvas.mpl_connect('button_release_event', self.release) self.canvas.mpl_connect('draw_event', self.update_background) self.circ = None self.background = None self.circprops = circprops self.onselect = onselect self.useblit = useblit self.minspan = minspan self.circ = Circle( (0,0), 1, **self.circprops) self.unit_verts = [v for v in self.circ.verts] self.circ.set_visible(False) if not self.useblit: self.ax.add_patch(self.circ) self.pressx = None def update_background(self, event): 'force an update of the background' if self.useblit: self.background = self.canvas.copy_from_bbox(self.ax.bbox) def ignore(self, event): 'return True if event should be ignored' return event.inaxes!=self.ax or not self.visible or event.button !=1 def press(self, event): 'on button press event' if self.ignore(event): return print "press" self.circ.set_visible(self.visible) self.pressx = event.xdata self.pressy = event.ydata self.circ.set_visible(False) return False def release(self, event): 'on button release event' if self.pressx is None or self.ignore(event): return if self.pressy is None or self.ignore(event): return self.canvas.draw() self.center = [self.pressx, self.pressy] self.radius = sqrt((event.xdata-self.center[0])**2 + (event.ydata-self.center[1])**2) y = event.ydata x = event.xdata if self.minspan is not None and radius<self.minspan: return self.onselect(self.center, self.radius, x, y) self.pressx = None self.pressy = None return False def update(self): 'draw using newfangled blit or oldfangled draw depending on useblit' if self.useblit: if self.background is not None: self.canvas.restore_region(self.background) self.ax.draw_artist(self.circ) self.canvas.blit(self.ax.bbox) else: self.canvas.draw_idle() return False def onmove(self, event): 'on motion notify event' if self.pressx is None or self.ignore(event): return if self.pressy is None or self.ignore(event): return self.center = [self.pressx,self.pressy] self.radius = sqrt((event.xdata-self.center[0])**2 + (event.ydata-self.center[1])**2) if self.radius > 0.5: self.circ.set_visible(True) else: self.circ.set_visible(False) self.circ.verts = [(v[0]*self.radius+self.center[0],v[1]*self.radius+self.center[1]) for v in self.unit_verts] pylab.draw() self.update() return False
min = tf.math.reduce_min(prediction) fps = 1 / (end_time - start_time) # prediction = prediction > 0.5 print(f"{image_file_name} MIN = {min}, MAX = {max}, FPS = {fps:.2f}") fig, axes = plt.subplots( 4, 5, figsize=(16, 16)) # the number of images in the grid is 5*5 (25) threshold = 0.5 for i, ax in enumerate(axes.flat): if i == prediction.shape[0]: break show_img = np.zeros((64, 64)) ax.imshow(prediction[i], cmap='gray', vmin=0, vmax=1) # ax.imshow(img[0]) cx, cy = np.unravel_index(prediction[i].argmax(), prediction[i].shape) if prediction[i, cx, cy] > threshold: patches = [Circle((cy, cx), radius=1, color='red')] for p in patches: ax.add_patch(p) ax.set_title(labels[i]) ax.imshow(img[0]) plt.subplots_adjust(left=0, bottom=0, right=1, top=0.97, wspace=0, hspace=0.25) plt.show() pass
def _add_patches(self, df, method, fill, ax, diagonal=True): width, height = df.shape patches = [] colors = [] for x in range(width): for y in range(height): if fill == 'lower' and x > y: continue elif fill == 'upper' and x < y: continue if diagonal is False and x == y: continue datum = (df.ix[x, y] + 1.) / 2. d = df.ix[x, y] d_abs = np.abs(d) #c = self.pvalues[x, y] rotate = -45 if d > 0 else +45 #cmap = self.poscm if d >= 0 else self.negcm if method in ['ellipse', 'square', 'rectangle', 'color']: if method == 'ellipse': func = Ellipse patch = func((x, y), width=1 * self.shrink, height=(self.shrink - d_abs * self.shrink), angle=rotate) else: func = Rectangle w = h = d_abs * self.shrink # FIXME shring must be <=1 offset = (1 - w) / 2. if method == 'color': w = 1 h = 1 offset = 0 patch = func((x + offset - .5, y + offset - .5), width=w, height=h, angle=0) if self.edgecolor: patch.set_edgecolor(self.edgecolor) # patch.set_facecolor(cmap(d_abs)) colors.append(datum) if d_abs > 0.05: patch.set_linestyle('dotted') # ax.add_artist(patch) patches.append(patch) # FIXME edgecolor is always printed elif method == 'circle': patch = Circle((x, y), radius=d_abs * self.shrink / 2.) if self.edgecolor: patch.set_edgecolor(self.edgecolor) # patch.set_facecolor(cmap(d_abs)) colors.append(datum) if d_abs > 0.05: patch.set_linestyle('dotted') # ax.add_artist(patch) patches.append(patch) elif method in ['number', 'text']: if d < 0: edgecolor = self.cm(-1.0) elif d >= 0: edgecolor = self.cm(1.0) d_str = "{:.2f}".format(d).replace( "0.", ".").replace(".00", "") ax.text(x, y, d_str, color=edgecolor, fontsize=self.fontsize, horizontalalignment='center', weight='bold', alpha=max(0.5, d_abs), withdash=False) elif method == 'pie': S = 360 * d_abs patch = [ Wedge((x, y), 1 * self.shrink / 2., -90, S - 90), Wedge((x, y), 1 * self.shrink / 2., S - 90, 360 - 90), ] # patch[0].set_facecolor(cmap(d_abs)) # patch[1].set_facecolor('white') colors.append(datum) colors.append(0.5) if self.edgecolor: patch[0].set_edgecolor(self.edgecolor) patch[1].set_edgecolor(self.edgecolor) # ax.add_artist(patch[0]) # ax.add_artist(patch[1]) patches.append(patch[0]) patches.append(patch[1]) else: raise ValueError( 'Method for the symbols is not known. Use e.g, square, circle') if self.binarise_color: colors = [1 if color > 0.5 else -1 for color in colors] if len(patches): col1 = PatchCollection( patches, array=np.array(colors), cmap=self.cm) ax.add_collection(col1) self.collection = col1
if __name__ == "__main__": import matplotlib.pyplot as plt ax = plt.gca() ax.set_aspect(1.) at = AnchoredText("Figure 1a", loc=2, frameon=True) at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") ax.add_artist(at) from matplotlib.patches import Circle ada = AnchoredDrawingArea(20, 20, 0, 0, loc=1, pad=0., frameon=False) p = Circle((10, 10), 10) ada.da.add_artist(p) ax.add_artist(ada) # draw an ellipse of width=0.1, height=0.15 in the data coordinate ae = AnchoredEllipse(ax.transData, width=0.1, height=0.15, angle=0., loc=3, pad=0.5, borderpad=0.4, frameon=True) ax.add_artist(ae) # draw a horizontal bar with length of 0.1 in Data coordinate # (ax.transData) with a label underneath. asb = AnchoredSizeBar(ax.transData, 0.1, r"1$^{\prime}$", loc=8,
def __init__(self, subarray, axes=None, autoupdate=True, tel_scale=2.0, alpha=0.7, title=None, radius=None, frame=GroundFrame()): self.frame = frame self.subarray = subarray # get the telescope positions. If a new frame is set, this will # transform to the new frame. self.tel_coords = subarray.tel_coords.transform_to(frame) # set up colors per telescope type tel_types = [str(tel) for tel in subarray.tels.values()] if radius is None: # set radius to the mirror radius (so big tels appear big) radius = [ np.sqrt(tel.optics.mirror_area.to("m2").value) * tel_scale for tel in subarray.tel.values() ] if title is None: title = subarray.name # get default matplotlib color cycle (depends on the current style) color_cycle = cycle(plt.rcParams['axes.prop_cycle'].by_key()['color']) # map a color to each telescope type: tel_type_to_color = {} for tel_type in list(set(tel_types)): tel_type_to_color[tel_type] = next(color_cycle) tel_color = [tel_type_to_color[ttype] for ttype in tel_types] patches = [] for x, y, r, c in zip(list(self.tel_coords.x.value), list(self.tel_coords.y.value), list(radius), tel_color): patches.append( Circle( xy=(x, y), radius=r, fill=True, color=c, alpha=alpha, )) # build the legend: legend_elements = [] for ttype in list(set(tel_types)): color = tel_type_to_color[ttype] legend_elements.append( Line2D([0], [0], marker='o', color=color, label=ttype, markersize=10, alpha=alpha, linewidth=0)) plt.legend(handles=legend_elements) self.tel_colors = tel_color self.autoupdate = autoupdate self.telescopes = PatchCollection(patches, match_original=True) self.telescopes.set_linewidth(2.0) self.axes = axes or plt.gca() self.axes.add_collection(self.telescopes) self.axes.set_aspect(1.0) self.axes.set_title(title) self._labels = [] self._quiver = None self.axes.autoscale_view()
def example(): #--------------------------------# # Parameters #--------------------------------# # Simulation wl = 400. k = 2*pi/wl w = 200 h = 800 m = 1 n = 2 # Plotting res = 500 xmax = 800 Ro = 1. #distance to measure field (m) angle_res = 100 #--------------------------------# # Algorithm dipoles = getDipoles(m,n,w,h) xs = ys = np.linspace(-xmax,xmax,res) X,Y = np.meshgrid(xs,ys) for di,d in enumerate(dipoles): R = getR(d[0],d[1],X,Y) phi = pi*(getPhase(m,n,di)) if di==0: Fz = 1/R*exp(1j*(k*R + phi)) else: Fz += 1/R*exp(1j*(k*R + phi)) # Plot Real Field fig = plt.figure() ax = fig.add_subplot(111) Fz *= -1 #flip values so plot color matches dipole color Fz /= np.amax(abs(Fz)) scale = 0.01 im = ax.imshow(Fz.real,extent=putil.getExtent(xs,ys),vmax=scale,vmin=-1*scale,cmap='RdBu') fig.colorbar(im) drawDipoleBox(m,n,w,h,ax) for di,d in enumerate(dipoles): p = getPhase(m,n,di) ax.add_patch(Circle(d,15,facecolor=colors[p])) # Power plot fig = plt.figure() ax = fig.add_subplot(111) P = abs(Fz)**2 P /= np.amax(P) im = ax.imshow(P,extent=putil.getExtent(xs,ys),vmax=sqrt(scale),cmap='hot') fig.colorbar(im) # Plot Farfield ff_fig = plt.figure() ff_ax = ff_fig.add_subplot(111,polar=True) ff_ax.grid(True) FFplot(ff_ax,wl,w,h,m,n,Ro=Ro,angle_res=angle_res) print getFF(wl,w,h,m,n,0) plt.show() return 0
for i in range(3): for j in range(n_col): ax = add_subplot(i, j, projection="3d") ax.axis("off") col1_axs = axs[:, :3] plot_neuron_morphology( label1_ids, label1_inputs, label1_outputs, col1_axs, row_label=True ) col1_axs[0, 1].set_title(label1) legend_elements = [] for ct in connection_types: p = Circle( (-1, -1), facecolor=connection_colors[ct], label=ct, linewidth=0, radius=1 ) legend_elements.append(p) col1_axs[2, 0].legend( handles=legend_elements, bbox_to_anchor=(0, 0), loc="upper left" ) col2_axs = axs[:, 3:] plot_neuron_morphology( label2_ids, label2_inputs, label2_outputs, col2_axs, row_label=True ) col2_axs[0, 1].set_title(label2) plt.tight_layout() stashfig(f"morpho-compare-{label1}_{label2}")
def add3Dcircle(x, y, z, r, color, axe, direction): #edgecolor="black" p = Circle((x, y), r, facecolor=color) axe.add_patch(p) art3d.pathpatch_2d_to_3d(p, z=z, zdir=direction)
import matplotlib.cm as cm import matplotlib.pyplot as plt from matplotlib.patches import Circle, PathPatch from matplotlib.path import Path from matplotlib.transforms import Affine2D import numpy as np r = np.random.rand(50) t = np.random.rand(50) * np.pi * 2.0 x = r * np.cos(t) y = r * np.sin(t) fig, ax = plt.subplots(figsize=(6, 6)) circle = Circle((0, 0), 1, facecolor='none', edgecolor=(0, 0.8, 0.8), linewidth=3, alpha=0.5) ax.add_patch(circle) im = plt.imshow(np.random.random((100, 100)), origin='lower', cmap=cm.winter, interpolation='spline36', extent=([-1, 1, -1, 1])) im.set_clip_path(circle) plt.plot(x, y, 'o', color=(0.9, 0.9, 1.0), alpha=0.8) # Dolphin from OpenClipart library by Andy Fitzsimon # <cc:License rdf:about="http://web.resource.org/cc/PublicDomain">
def runSlices(opsimName, metadata, simdata, fields, bins, args, opsDb, verbose=False): # Set up the movie slicer. movieslicer = setupMovieSlicer(simdata, bins) # Set up formatting for output suffix. sliceformat = '%s0%dd' % ('%', int(np.log10(len(movieslicer))) + 1) # Get the telescope latitude info. lat_tele = Site(name='LSST').latitude_rad # Run through the movie slicer slicePoints and generate plots at each point. for i, ms in enumerate(movieslicer): t = time.time() slicenumber = sliceformat % (i) if verbose: print(slicenumber) # Set up metrics. if args.movieStepsize != 0: tstep = args.movieStepsize else: tstep = ms['slicePoint']['binRight'] - bins[i] if tstep > 1: tstep = 40. / 24. / 60. / 60. # Add simple view of time to plot label. times_from_start = ms['slicePoint']['binRight'] - (int(bins[0]) + 0.16 - 0.5) # Opsim years are 365 days (not 365.25) years = int(times_from_start / 365) days = times_from_start - years * 365 plotlabel = 'Year %d Day %.4f' % (years, days) # Set up metrics. metricList, plotDictList = setupMetrics( opsimName, metadata, plotlabel=plotlabel, t0=ms['slicePoint']['binRight'], tStep=tstep, years=years, verbose=verbose) # Identify the subset of simdata in the movieslicer 'data slice' simdatasubset = simdata[ms['idxs']] # Set up opsim slicer on subset of simdata provided by movieslicer opslicer = slicers.OpsimFieldSlicer() # Set up metricBundles to combine metrics, plotdicts and slicer. bundles = [] sqlconstraint = '' for metric, plotDict in zip(metricList, plotDictList): bundles.append( metricBundles.MetricBundle(metric, opslicer, constraint=sqlconstraint, metadata=metadata, runName=opsimName, plotDict=plotDict)) # Remove (default) stackers from bundles, because we've already run them above on the original data. for mb in bundles: mb.stackerList = [] bundledict = metricBundles.makeBundlesDictFromList(bundles) # Set up metricBundleGroup to handle metrics calculation + plotting bg = metricBundles.MetricBundleGroup(bundledict, opsDb, outDir=args.outDir, resultsDb=None, saveEarly=False) # 'Hack' bundleGroup to just go ahead and run the metrics, without querying the database. simData = simdatasubset bg.fieldData = fields bg.setCurrent(sqlconstraint) bg.runCurrent(constraint=sqlconstraint, simData=simData) # Plot data each metric, for this slice of the movie, adding slicenumber as a suffix for output plots. # Plotting here, rather than automatically via sliceMetric method because we're going to rotate the sky, # and add extra legend info and figure text (for FilterColors metric). ph = plots.PlotHandler(outDir=args.outDir, figformat='png', dpi=72, thumbnail=False, savefig=False) obsnow = np.where(simdatasubset['observationStartMJD'] == simdatasubset['observationStartMJD'].max())[0] raCen = np.radians( np.mean(simdatasubset[obsnow]['observationStartLST'])) # Calculate horizon location. horizonlon, horizonlat = addHorizon(lat_telescope=lat_tele) # Create the plot for each metric and save it (after some additional manipulation). for mb in bundles: ph.setMetricBundles([mb]) fignum = ph.plot(plotFunc=plots.BaseSkyMap(), plotDicts={'raCen': raCen}) fig = plt.figure(fignum) ax = plt.gca() # Add horizon and zenith. plt.plot(horizonlon, horizonlat, 'k.', alpha=0.3, markersize=1.8) plt.plot(0, lat_tele, 'k+') # For the FilterColors metric, add some extra items. if mb.metric.name == 'FilterColors': # Add the time stamp info (plotlabel) with a fancybox. plt.figtext(0.75, 0.9, '%s' % (plotlabel), bbox=dict(boxstyle='Round, pad=0.7', fc='w', ec='k', alpha=0.5)) # Add a legend for the filters. filterstacker = stackers.FilterColorStacker() for i, f in enumerate(['u', 'g', 'r', 'i', 'z', 'y']): plt.figtext(0.92, 0.55 - i * 0.035, f, color=filterstacker.filter_rgb_map[f]) # Add a moon. moonRA = np.radians(np.mean(simdatasubset[obsnow]['moonRA'])) lon = -(moonRA - raCen - np.pi) % (np.pi * 2) - np.pi moonDec = np.radians(np.mean(simdatasubset[obsnow]['moonDec'])) # Note that moonphase is 0-100 (translate to 0-1). 0=new. moonPhase = np.mean(simdatasubset[obsnow]['moonPhase']) / 100. alpha = np.max([moonPhase, 0.15]) circle = Circle((lon, moonDec), radius=0.05, color='k', alpha=alpha) ax.add_patch(circle) # Add some explanatory text. ecliptic = Line2D([], [], color='r', label="Ecliptic plane") galaxy = Line2D([], [], color='b', label="Galactic plane") horizon = Line2D([], [], color='k', alpha=0.3, label="20 deg elevation limit") moon = Line2D([], [], color='k', linestyle='', marker='o', markersize=8, alpha=alpha, label="\nMoon (Dark=Full)\n (Light=New)") zenith = Line2D([], [], color='k', linestyle='', marker='+', markersize=5, label="Zenith") plt.legend( handles=[horizon, zenith, galaxy, ecliptic, moon], loc=[0.1, -0.35], ncol=3, frameon=False, title= 'Aitoff plot showing HA/Dec of simulated survey pointings', numpoints=1, fontsize='small') # Save figure. plt.savefig(os.path.join( args.outDir, mb.metric.name + '_' + slicenumber + '_SkyMap.png'), format='png', dpi=72) plt.close('all') dt, t = dtime(t) if verbose: print('Ran and plotted slice %s of movieslicer in %f s' % (slicenumber, dt))
def add_danger(self, danger_id): """ Appends a new danger to the appropriate list of `env`, and updates the `env` view. The position at which the danger is placed is computed based on the rover's location and direction, but also where on the robot that particular danger-detection sensor is located. """ """if danger_id == left_bumper: elif danger_id == right_bumper: elif danger_id == left_and_right_bumper: elif danger_id == front_left_cliff: elif danger_id == front_right_cliff: elif danger_id == left_cliff: elif danger_id == right_cliff: elif danger_id == white_tape_front_left: elif danger_id == white_tape_front_right: elif danger_id == white_tape_left: elif danger_id == white_tape_right: elif danger_id == left_wheel: elif danger_id == right_wheel: elif danger_id == middle_wheel: else: raise NotImplementedError() """ # Find the danger location using `danger_angle` and `danger_distance` # TODO: maybe later # danger_loc = conv_radial(self, danger_theta, danger_r) # Plot if (1 <= danger_id <= 3): # Bumper range in OIStopID """ Adds a bump """ c = Circle(self._loc, radius = 6.25) c.set_facecolor('0.65') # grey c.set_edgecolor('black') c.set_zorder(zorders['bumps']) c.set_fill(True) self.view.add_artist(c) self.bumps.append(c) self.draw() elif (4 <= danger_id <= 7): # Cliff range in OIStopID """ Adds a cliff """ c = Circle(self._loc, radius = 6.25) c.set_facecolor('0.65') # grey c.set_edgecolor('black') c.set_zorder(zorders['cliffs']) c.set_fill(True) self.view.add_artist(c) self.cliffs.append(c) self.draw() elif (12 <= danger_id <= 14): # Drop range in OIStopID """ Adds a drop """ c = Circle(self._loc, radius = 6.25) c.set_facecolor('0.65') # grey c.set_edgecolor('black') c.set_zorder(zorders['drops']) c.set_fill(True) self.view.add_artist(c) self.drops.append(c) self.draw() elif (8 <= danger_id <= 11): # White tape range in OIStopID """ Adds tape """ c = Circle(self._loc, radius = 6.25) c.set_facecolor('0.65') # grey c.set_edgecolor('black') c.set_zorder(zorders['tape']) c.set_fill(True) self.view.add_artist(c) self.tape.append(c) self.draw() else: raise NotImplementedError() # The following is the temporary workaround: sys.stderr.write("danger found: " + str(danger_id)) # TODO: check to see if enum strig is a thing
Ex, Ey = np.zeros((ny, nx)), np.zeros((ny, nx)) potential = np.zeros((ny, nx)) fig = plotter.figure() plot1 = fig.add_subplot(121) plot2 = fig.add_subplot(122) charge_colors = {True: '#aa0000', False: '#0000aa'} for x, y in zip(xLocationsOnRing, yLocationsOnRing): littleChargedParticle = chargedParticle(np.array([x, y]), dq) ex, ey = littleChargedParticle.electricFieldforPlotting(X, Y) Ex += ex Ey += ey potential += littleChargedParticle.electricPotentialforPlotting(X, Y) plot1.add_artist( Circle(littleChargedParticle.location, 0.01, color=charge_colors[littleChargedParticle.charge > 0])) plot2.add_artist( Circle(littleChargedParticle.location, 0.01, color=charge_colors[littleChargedParticle.charge > 0])) color = np.log(np.sqrt(Ex**2 + Ey**2)) plot1.streamplot(X, Y, Ex, Ey, color=color, linewidth=1, cmap=plotter.cm.inferno, density=3, arrowstyle='->',
def __init__(self, xy, *args, **kwargs): Circle.__init__(self, xy, *args, **kwargs)
xy1, z1 = (y, z), x else: xy1, z1 = (x, y), z text_path = TextPath((0, 0), s, size=size, usetex=usetex) trans = Affine2D().rotate(angle).translate(xy1[0], xy1[1]) p1 = PathPatch(trans.transform_path(text_path), **kwargs) ax.add_patch(p1) art3d.pathpatch_2d_to_3d(p1, z=z1, zdir=zdir) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') p = Circle((5, 5), 3) ax.add_patch(p) art3d.pathpatch_2d_to_3d(p, z=0, zdir="x") text3d(ax, (4, -2, 0), "X-axis", zdir="z", size=.5, usetex=False, ec="none", fc="k") text3d(ax, (12, 4, 0), "Y-axis", zdir="z", size=.5, usetex=False, angle=.5*3.14159, ec="none", fc="k") text3d(ax, (12, 10, 4), "Z-axis", zdir="y", size=.5, usetex=False, angle=.5*3.14159, ec="none", fc="k") text3d(ax, (1, 5, 0), r"$\displaystyle G_{\mu\nu} + \Lambda g_{\mu\nu} = \frac{8\pi G}{c^4} T_{\mu\nu} $", zdir="z", size=1, usetex=True, ec="none", fc="k")
matplotlib.rcParams['lines.linewidth'] = 2 pyplot.axis([0, gridWidth, 0, gridHeight]) pyplot.grid(True) # Setting the axis labels. pyplot.xlabel('X Space') pyplot.ylabel('Y Space') #Give the plot a title pyplot.title('Radius Search Plot Using Shapely (%d Points)' % (numberOfPoints)) # Draw the collision circle/boundary cir = Circle((circleX, circleY), radius=circleRadius, fc='b') cir.set_alpha(0.4) pyplot.gca().add_patch(cir) for idx, point in enumerate(pointList): style = 'go' iAlpha = 0.4 if(idx in matchingPoints): style = 'ro' iAlpha = 1 pyplot.plot(point[0], point[1], style, linewidth=1, markersize=3, alpha=iAlpha) pyplot.savefig(os.getcwd()+'/'+str(filename))
if (label == -1): xcord0.append(xPt) ycord0.append(yPt) else: xcord1.append(xPt) ycord1.append(yPt) fr.close() fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(xcord0, ycord0, marker='s', s=90) ax.scatter(xcord1, ycord1, marker='o', s=50, c='red') plt.title('Support Vectors Circled') circle = Circle((4.6581910000000004, 3.507396), 0.5, facecolor='none', edgecolor=(0, 0.8, 0.8), linewidth=3, alpha=0.5) ax.add_patch(circle) circle = Circle((3.4570959999999999, -0.082215999999999997), 0.5, facecolor='none', edgecolor=(0, 0.8, 0.8), linewidth=3, alpha=0.5) ax.add_patch(circle) circle = Circle((6.0805730000000002, 0.41888599999999998), 0.5, facecolor='none', edgecolor=(0, 0.8, 0.8), linewidth=3,
def __init__(self, xy, label, fig): self.point = Circle( (xy[0], xy[1]), .25, figure=fig) self.label = label self.cidpress = self.point.figure.canvas.mpl_connect('button_press_event', self.onClick)
def create_predict_update_chart(box_bg='#CCCCCC', arrow1='#88CCFF', arrow2='#88FF88'): plt.figure(figsize=(3, 3), facecolor='w') ax = plt.axes((0, 0, 1, 1), xticks=[], yticks=[], frameon=False) #ax.set_xlim(0, 10) #ax.set_ylim(0, 10) pc = Circle((4, 5), 0.5, fc=box_bg) uc = Circle((6, 5), 0.5, fc=box_bg) ax.add_patch(pc) ax.add_patch(uc) plt.text(4, 5, "Predict\nStep", ha='center', va='center', fontsize=14) plt.text(6, 5, "Update\nStep", ha='center', va='center', fontsize=14) #btm ax.annotate('', xy=(4.1, 4.5), xycoords='data', xytext=(6, 4.5), textcoords='data', size=20, arrowprops=dict(arrowstyle="simple", fc="0.6", ec="none", patchB=pc, patchA=uc, connectionstyle="arc3,rad=-0.5")) #top ax.annotate('', xy=(6, 5.5), xycoords='data', xytext=(4.1, 5.5), textcoords='data', size=20, arrowprops=dict(arrowstyle="simple", fc="0.6", ec="none", patchB=uc, patchA=pc, connectionstyle="arc3,rad=-0.5")) ax.annotate('Measurement ($\mathbf{z_k}$)', xy=(6.3, 5.4), xycoords='data', xytext=(6, 6), textcoords='data', size=18, arrowprops=dict(arrowstyle="simple", fc="0.6", ec="none")) ax.annotate('', xy=(4.0, 3.5), xycoords='data', xytext=(4.0, 4.5), textcoords='data', size=18, arrowprops=dict(arrowstyle="simple", fc="0.6", ec="none")) ax.annotate('Initial\nConditions ($\mathbf{x_0}$)', xy=(4.0, 5.5), xycoords='data', xytext=(2.5, 6.5), textcoords='data', size=18, arrowprops=dict(arrowstyle="simple", fc="0.6", ec="none")) plt.text(4, 3.4, 'State Estimate ($\mathbf{\hat{x}_k}$)', ha='center', va='center', fontsize=18) plt.axis('equal')
def plot_job_history(jobs, interval='year'): """Plots the job history of the user from the given list of jobs. Args: jobs (list): A list of jobs with type IBMQjob. interval (str): Interval over which to examine. Returns: fig: A Matplotlib figure instance. """ def get_date(job): """Returns a datetime object from a IBMQJob instance. Args: job (IBMQJob): A job. Returns: dt: A datetime object. """ return datetime.datetime.strptime(job.creation_date(), '%Y-%m-%dT%H:%M:%S.%fZ') current_time = datetime.datetime.now() if interval == 'year': bins = [(current_time - datetime.timedelta(days=k * 365 / 12)) for k in range(12)] elif interval == 'month': bins = [(current_time - datetime.timedelta(days=k)) for k in range(30)] elif interval == 'week': bins = [(current_time - datetime.timedelta(days=k)) for k in range(7)] binned_jobs = [0] * len(bins) if interval == 'year': for job in jobs: for ind, dat in enumerate(bins): date = get_date(job) if date.month == dat.month: binned_jobs[ind] += 1 break else: continue else: for job in jobs: for ind, dat in enumerate(bins): date = get_date(job) if date.day == dat.day and date.month == dat.month: binned_jobs[ind] += 1 break else: continue nz_bins = [] nz_idx = [] for ind, val in enumerate(binned_jobs): if val != 0: nz_idx.append(ind) nz_bins.append(val) total_jobs = sum(binned_jobs) colors = [ '#003f5c', '#ffa600', '#374c80', '#ff764a', '#7a5195', '#ef5675', '#bc5090' ] if interval == 'year': labels = [ '{}-{}'.format(str(bins[b].year)[2:], bins[b].month) for b in nz_idx ] else: labels = ['{}-{}'.format(bins[b].month, bins[b].day) for b in nz_idx] fig, ax = plt.subplots(1, 1, figsize=(5, 5)) # pylint: disable=invalid-name ax.pie(nz_bins[::-1], labels=labels, colors=colors, textprops={'fontsize': 14}, rotatelabels=True, counterclock=False) ax.add_artist(Circle((0, 0), 0.7, color='white', zorder=1)) ax.text(0, 0, total_jobs, horizontalalignment='center', verticalalignment='center', fontsize=26) fig.tight_layout() return fig
Z = loss(B0, B1, a=1, b=1.2, c=1, cx=cx, cy=cy) # Z = np.where(Z<600,Z,np.NAN) # Create a figure and a 3D Axes fig = plt.figure(figsize=(4.2, 3.1)) ax = fig.add_subplot(111, projection='3d') vmax = 800 ax.plot_surface(B0, B1, Z, alpha=0.7, cmap='coolwarm', vmax=vmax) ax.set_xlabel("$\\beta_1$", labelpad=0) ax.set_ylabel("$\\beta_2$", labelpad=0) ax.set_zlim(0, 500) ax.tick_params(axis='x', pad=0) ax.tick_params(axis='y', pad=0) ax.set_xlim(-w, w) ax.set_ylim(-h, h) safe = Circle(xy=(0, 0), radius=lmbda, color='grey') ax.add_patch(safe) art3d.pathpatch_2d_to_3d(safe, z=0) ax.plot([cx], [cy], marker='x', markersize=10, color='black') contr = ax.contour(B0, B1, Z, levels=50, linewidths=.5, cmap='coolwarm', zdir='z', offset=0, vmax=vmax)
def _add_patches(self, df, method, fill, ax, diagonal=True): from matplotlib.patches import Ellipse, Circle, Rectangle, Wedge from matplotlib.collections import PatchCollection width, height = df.shape patches = [] colors = [] for x in range(width): for y in range(height): if fill == 'lower' and x > y: continue elif fill == 'upper' and x < y: continue if diagonal is False and x == y: continue datum = (df.ix[x, y] + 1.) / 2. d = df.ix[x, y] d_abs = np.abs(d) #c = self.pvalues[x, y] rotate = -45 if d > 0 else +45 #cmap = self.poscm if d >= 0 else self.negcm if method in ['ellipse', 'square', 'rectangle', 'color']: if method == 'ellipse': func = Ellipse patch = func( (x, y), width=1 * self.shrink, height=(self.shrink - d_abs * self.shrink), angle=rotate) else: func = Rectangle w = h = d_abs * self.shrink # FIXME shring must be <=1 offset = (1 - w) / 2. if method == 'color': w = 1 h = 1 offset = 0 patch = func((x + offset - .5, y + offset - .5), width=w, height=h, angle=0) if self.edgecolor: patch.set_edgecolor(self.edgecolor) # patch.set_facecolor(cmap(d_abs)) colors.append(datum) if d_abs > 0.05: patch.set_linestyle('dotted') # ax.add_artist(patch) patches.append(patch) # FIXME edgecolor is always printed elif method == 'circle': patch = Circle((x, y), radius=d_abs * self.shrink / 2.) if self.edgecolor: patch.set_edgecolor(self.edgecolor) # patch.set_facecolor(cmap(d_abs)) colors.append(datum) if d_abs > 0.05: patch.set_linestyle('dotted') # ax.add_artist(patch) patches.append(patch) elif method in ['number', 'text']: if d < 0: edgecolor = self.cm(-1.0) elif d >= 0: edgecolor = self.cm(1.0) d_str = "{:.2f}".format(d).replace("0.", ".").replace(".00", "") ax.text(x, y, d_str, color=edgecolor, fontsize=self.fontsize, horizontalalignment='center', weight='bold', alpha=max(0.5, d_abs), withdash=False) elif method == 'pie': S = 360 * d_abs patch = [ Wedge((x, y), 1 * self.shrink / 2., -90, S - 90), Wedge((x, y), 1 * self.shrink / 2., S - 90, 360 - 90), ] # patch[0].set_facecolor(cmap(d_abs)) # patch[1].set_facecolor('white') colors.append(datum) colors.append(0.5) if self.edgecolor: patch[0].set_edgecolor(self.edgecolor) patch[1].set_edgecolor(self.edgecolor) # ax.add_artist(patch[0]) # ax.add_artist(patch[1]) patches.append(patch[0]) patches.append(patch[1]) else: raise ValueError( 'Method for the symbols is not known. Use e.g, square, circle' ) if self.binarise_color: colors = [1 if color > 0.5 else -1 for color in colors] if len(patches): col1 = PatchCollection(patches, array=np.array(colors), cmap=self.cm) ax.add_collection(col1) self.collection = col1
def plot_span_circle(fig: plt.Figure, ax: plt.Axes, R: PlanarTriangle, P: Triangle, i: int) -> None: c, r = get_span_circle(R, P, i) circle = Circle(c, r, linestyle="--", fill=None) ax.add_patch(circle)
def __init__(self, instance, schedule, duration): with open(instance) as map_file: map_data = yaml.load(map_file, Loader=yaml.SafeLoader) aspect = (map_data["map"]["dimensions"][0] + 2) / (map_data["map"]["dimensions"][1] + 2) self.fig, self.ax = plt.subplots(frameon=False, figsize=(4 * aspect, 4)) self.ax.set_aspect('equal') plt.axis('off') self.fig.subplots_adjust(left=0, right=1, bottom=0, top=1, wspace=None, hspace=None) xmin = -1 ymin = -1 xmax = map_data["map"]["dimensions"][0] + 1 ymax = map_data["map"]["dimensions"][1] + 1 plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) for o in map_data["map"]["obstacles"]: self.ax.add_patch( Rectangle(o, 1.0, 1.0, facecolor='gray', alpha=0.5)) for x in range(-1, map_data["map"]["dimensions"][0] + 1): self.ax.add_patch( Rectangle([x, -1], 1.0, 1.0, facecolor='gray', alpha=0.5)) self.ax.add_patch( Rectangle([x, map_data["map"]["dimensions"][1]], 1.0, 1.0, facecolor='gray', alpha=0.5)) for y in range(map_data["map"]["dimensions"][1]): self.ax.add_patch( Rectangle([-1, y], 1.0, 1.0, facecolor='gray', alpha=0.5)) self.ax.add_patch( Rectangle([map_data["map"]["dimensions"][0], y], 1.0, 1.0, facecolor='gray', alpha=0.5)) self.data = np.load(schedule) self.num_agents = len(map_data["agents"]) self.dt = self.data[1, 0] - self.data[0, 0] self.colors = [] self.robots = [] for i in range(self.num_agents): # plot trajectory # line = self.ax.plot(self.data[:,1+i*4], self.data[:,1+i*4+1],alpha=0.5,linewidth=2,linestyle='dashed') line = self.ax.plot(self.data[0:0, 1 + i * 4], self.data[0:0, 1 + i * 4 + 1], alpha=0.5, linewidth=2, linestyle='dashed') color = line[0].get_color() self.colors.append(color) # plot start and goal start = np.array(map_data["agents"][i]["start"]) goal = np.array(map_data["agents"][i]["goal"]) self.robots.append( Circle(start + np.array([0.5, 0.5]), 0.15, alpha=0.5, color=color)) self.ax.add_patch(self.robots[-1]) self.ax.add_patch( Rectangle(goal + np.array([0.3, 0.3]), 0.4, 0.4, alpha=0.5, color=color)) if duration < 0: duration = int(self.data[-1, 0]) else: duration = int(duration) self.anim = animation.FuncAnimation(self.fig, self.animate_func, init_func=self.init_func, frames=duration * 10, interval=100, blit=True)
def animate(self): if self.is_sim_mode == True: if MathsCalculations.CalcRange( self, MathsCalculations.GetVelocity(self), MathsCalculations.GetAngleOfProjection(self), MathsCalculations.GetElevation( self)) > MathsCalculations.CalcMaxHeight( self, MathsCalculations.GetVelocity(self), MathsCalculations.GetAngleOfProjection(self), MathsCalculations.GetElevation(self)): limit = MathsCalculations.CalcRange( self, MathsCalculations.GetVelocity(self), MathsCalculations.GetAngleOfProjection(self), MathsCalculations.GetElevation(self)) else: limit = MathsCalculations.CalcMaxHeight( self, MathsCalculations.GetVelocity(self), MathsCalculations.GetAngleOfProjection(self), MathsCalculations.GetElevation(self)) try: self.cl = self.figure_sm.clf() self.ax = self.figure_sm.add_subplot() self.circle = Circle((0, 0), 0.3) self.ax.add_artist(self.circle) self.ax.set_xlim([0, limit + (limit * 0.1)]) self.ax.set_ylim([0, limit + (limit * 0.1)]) self.animation1 = animation.FuncAnimation( self.figure_sm, self.animate_loop_sm, frames=np.arange( 0, MathsCalculations.CalcTimeTaken( self, float(self.veloinp_sm.text()), float(self.anglespin_sm.text()), float(self.elevinp_sm.text())), 0.01), interval=10, repeat=False) self.animation2 = animation.FuncAnimation( self.figure_sm, self.animate_trailloop_sm, frames=np.arange( 0, MathsCalculations.CalcTimeTaken( self, float(self.veloinp_sm.text()), float(self.anglespin_sm.text()), float(self.elevinp_sm.text())), 0.01), interval=10, repeat=False) self.canvas_sm.draw() except: print("Error") else: try: self.cl = self.figure_qm.clf() self.ax = self.figure_qm.add_subplot() self.circle = Circle((0, 0), 0.5) self.ax.add_artist(self.circle) self.ax.set_xlim([0, limit] + (limit * 0.1)) self.ax.set_ylim([0, limit] + (limit * 0.1)) self.animation = animation.FuncAnimation( self.figure_qm, self.animate_loop_qm, frames=np.arange( 0, MathsCalculations.CalcTimeTaken( self, float(self.veloinp_qm.text()), float(self.angleinp_qm.text()), float(self.elevinp_qm.text())), 0.01), interval=10, repeat=False) self.canvas_qm.draw() except: print("Error")
start_points=seed.T) ax2.streamplot(x, z, Vx, Vz - u, color=color, linewidth=1, cmap='afmhot', density=5, arrowstyle='-|>', arrowsize=1.0, minlength=0.4, start_points=seed.T) for ax in (ax1, ax2): # Add filled circle for sphere ax.add_patch(Circle((0, 0), a, color='C0', zorder=2)) ax.set_xlabel('$x$') ax.set_ylabel('$z$') ax.set_aspect('equal') ax.set_xlim(-0.7 * xlim, 0.7 * xlim) ax.set_ylim(-0.7 * zlim, 0.7 * zlim) fig.tight_layout() fig.savefig('./figures/stokesFlowStream.pdf') fig.show() """ Introduction to Python for Science & Engineering by David J. Pine Code last edited: 2018-09-15 Streamplot example using matplotlib """
data = np.array(data) xys = data[:, :2] sphere1s = data[:, 2:5] sphere2s = data[:, 5:8] point1s = data[:, 8:10] point2s = data[:, 10:12] color2 = '#d6191b' patches_circle = [] for xy, sphere1, sphere2, point1, point2 in zip( xys, sphere1s, sphere2s, point1s, point2s): xc = xy[0] + sphere2[0] - sphere1[0] yc = xy[1] + sphere2[1] - sphere1[1] r = sqrt(sphere1[2] * sphere1[2] + sphere2[2] * sphere2[2]) if invert_yaxis: circle = Circle((xc, -yc), r, color=color2) patches_circle.append(circle) else: circle = Circle((xc, yc), r, color=color2) patches_circle.append(circle) xc = xy[0] + point2[0] - sphere1[0] yc = xy[1] + point2[1] - sphere1[1] r = sphere1[2] if invert_yaxis: circle = Circle((xc, -yc), r, color=color2) patches_circle.append(circle) else: circle = Circle((xc, yc), r, color=color2) patches_circle.append(circle)