def multiple_optima(gene_number=937, resolution=80, model_restarts=10, seed=10000, max_iters=300, optimize=True, plot=True): """ Show an example of a multimodal error surface for Gaussian process regression. Gene 939 has bimodal behaviour where the noisy mode is higher. """ # Contour over a range of length scales and signal/noise ratios. length_scales = np.linspace(0.1, 60., resolution) log_SNRs = np.linspace(-3., 4., resolution) try:import pods except ImportError: print 'pods unavailable, see https://github.com/sods/ods for example datasets' return data = pods.datasets.della_gatta_TRP63_gene_expression(data_set='della_gatta',gene_number=gene_number) # data['Y'] = data['Y'][0::2, :] # data['X'] = data['X'][0::2, :] data['Y'] = data['Y'] - np.mean(data['Y']) lls = GPy.examples.regression._contour_data(data, length_scales, log_SNRs, GPy.kern.RBF) if plot: pb.contour(length_scales, log_SNRs, np.exp(lls), 20, cmap=pb.cm.jet) ax = pb.gca() pb.xlabel('length scale') pb.ylabel('log_10 SNR') xlim = ax.get_xlim() ylim = ax.get_ylim() # Now run a few optimizations models = [] optim_point_x = np.empty(2) optim_point_y = np.empty(2) np.random.seed(seed=seed) for i in range(0, model_restarts): # kern = GPy.kern.RBF(1, variance=np.random.exponential(1.), lengthscale=np.random.exponential(50.)) kern = GPy.kern.RBF(1, variance=np.random.uniform(1e-3, 1), lengthscale=np.random.uniform(5, 50)) m = GPy.models.GPRegression(data['X'], data['Y'], kernel=kern) m.likelihood.variance = np.random.uniform(1e-3, 1) optim_point_x[0] = m.rbf.lengthscale optim_point_y[0] = np.log10(m.rbf.variance) - np.log10(m.likelihood.variance); # optimize if optimize: m.optimize('scg', xtol=1e-6, ftol=1e-6, max_iters=max_iters) optim_point_x[1] = m.rbf.lengthscale optim_point_y[1] = np.log10(m.rbf.variance) - np.log10(m.likelihood.variance); if plot: pb.arrow(optim_point_x[0], optim_point_y[0], optim_point_x[1] - optim_point_x[0], optim_point_y[1] - optim_point_y[0], label=str(i), head_length=1, head_width=0.5, fc='k', ec='k') models.append(m) if plot: ax.set_xlim(xlim) ax.set_ylim(ylim) return m # (models, lls)
def draw_bar(xs, y, dat): global scale for ix in range(len(xs)): if dat[ix] > 0: color = "red" else: color = "blue" pl.arrow(xs[ix], y/2., scale*dat[ix], 0, color=color)
def plot_profile(self): self.logger.debug('Plotting Profile curves') try: xnew = np.linspace(self.time[0], self.time[-1], num=50) #Function handle for generating plot interpolate points f1 = lambda (tck): interpolate.splev(xnew, tck) ynew = np.array(map(f1, self.tcks)).T ax = pl.gca() color_list = ['r', 'g', 'b', 'c', 'y'] ax.set_color_cycle(color_list) pl.plot(self.time, self.var, 'x', xnew, ynew) # plot arrows arrow_scale = 40.0 dx = (self.time[-1] - self.time[0]) / arrow_scale dy = self.slopes.T * dx # transpose operation here for ii in range(self.n_sample): t = self.time[ii] X = self.var[ii, :] DY = dy[:, ii] for jj in range(self.n_var): pl.arrow(t, X[jj], dx, DY[jj], linewidth=1) pl.title('Plot of spline fitted biochem profile vs time') pl.xlabel('time') pl.ylabel('profile') pl.axis('tight') pl.show() except AttributeError: sys.stderr.writelines("Define Profile before trying to plot..!") raise
def arc(xx, yy, index, draw_dots=True): A = array([xx[0], yy[0]]) B = array([xx[1], yy[1]]) if draw_dots: plot(A[0], A[1], "ko") plot(B[0], B[1], "ko") AB = B-A AB_len = sqrt(sum(AB**2)) AB = AB / AB_len pAB = array([AB[1], -AB[0]]) AB_mid = (A+B)/2. if index == 1: R = AB_mid + pAB * AB_len/1.5 else: R = AB_mid + pAB * AB_len/4. r = sqrt(sum((A-R)**2)) P_arrow = R - pAB * r # Draw the arc from A to B centered at R phi1 = atan2((A-R)[1], (A-R)[0]) phi2 = atan2((B-R)[1], (B-R)[0]) n = 100 # number of divisions phi = linspace(phi1, phi2, n) xx = r*cos(phi)+R[0] yy = r*sin(phi)+R[1] plot(xx, yy, "k-", lw=2) x, x2 = xx[n/2-1:n/2+1] y, y2 = yy[n/2-1:n/2+1] dx = x2-x dy = y2-y arrow(x, y, dx/2, dy/2, fc="black", head_width=0.05)
def get_cov_ev(cov, plot=False): import numpy as np import pandas as pd cov = np.mat(cov) eig_vals, eig_vecs = np.linalg.eig(cov) df = pd.DataFrame() df['ev_x'] = eig_vecs[0, :].tolist()[0] df['ev_y'] = eig_vecs[1, :].tolist()[0] df['e_values'] = eig_vals df['e_values_sqrt'] = df.e_values.apply(np.sqrt) df.fillna(0, inplace=True) df = df.sort_values(by='e_values', ascending=False).reset_index() main_axis=df.ev_x[0] * df.e_values_sqrt[0], df.ev_y[0] * df.e_values_sqrt[0] angle = vector_to_angle(main_axis[0], main_axis[1]) # from -135 to 45 degrees angle = angle if angle >= -90 else 180+angle # to make it from -90 to 90 if plot: print('cov\n\t' + str(cov).replace('\n', '\n\t')) import pylab as plt samples = 100 df_original_multi_samples = pd.DataFrame(np.random.multivariate_normal([0, 0], cov, samples), columns=['X', 'Y']) df_original_multi_samples.plot.scatter(x='X', y='Y', alpha=0.1) m = df_original_multi_samples.max().max() plt.axis([-m, m, -m, m]) for i in [0, 1]: # 0 is the main eigenvector if df.ev_x[i] * df.e_values_sqrt[i] + df.ev_y[i] * df.e_values_sqrt[i]: # cannot plot 0 size vector plt.arrow(0, 0, df.ev_x[i] * df.e_values_sqrt[i], df.ev_y[i] * df.e_values_sqrt[i], head_width=0.15, head_length=0.15, length_includes_head=True, fc='k', ec='k') else: print('zero length eigenvector, skipping') plt.show() return df, angle
def plot_profile(self) : self.logger.debug('Plotting Profile curves') try : xnew = np.linspace(self.time[0],self.time[-1],num=50) #Function handle for generating plot interpolate points f1 = lambda(tck) : interpolate.splev(xnew,tck) ynew = np.array(map(f1,self.tcks)).T ax = pl.gca() color_list = ['r','g','b','c','y'] ax.set_color_cycle(color_list) pl.plot(self.time,self.var,'x',xnew,ynew); # plot arrows arrow_scale = 40.0 dx = (self.time[-1]-self.time[0])/arrow_scale; dy = self.slopes.T * dx # transpose operation here for ii in range(self.n_sample) : t = self.time[ii] X = self.var[ii,:] DY = dy[:,ii] for jj in range(self.n_var) : pl.arrow(t,X[jj],dx,DY[jj],linewidth=1) pl.title('Plot of spline fitted biochem profile vs time') pl.xlabel('time') pl.ylabel('profile') pl.axis('tight') pl.show() except AttributeError : sys.stderr.writelines( "Define Profile before trying to plot..!") raise
def plot_ROC_Risk(w, x, y, best_operating_point, risk, fname, title, TH=None, NoTH=None): from matplotlib import rc from numpy import ones import pylab rc('font', family='serif', size=20) fig = pylab.figure(1, figsize=(8, 8), dpi=100, facecolor='w') ax = fig.add_subplot(111) fig.hold(True) m = w[0] / w[1] line_x = arange(0, 1, 0.001) line_y = ones(1000) - m * line_x pylab.fill_between(x, ones(len(y)), y, facecolor='#D0D0D0') pylab.plot(x, y, 'r', linewidth=3) best = [x[best_operating_point], y[best_operating_point]] pylab.plot(best[0], best[1], '*k', markersize=20, label='Risk$^*$ ={0:.3f}'.format(risk)) pylab.plot(line_x, line_y, 'k', linewidth=3) midline = len(line_x) / 2 arrow_x, arrow_y = line_x[midline], line_y[midline] pylab.arrow(arrow_x, arrow_y, -w[0] * 0.15, -w[1] * 0.15, head_length=.02, head_width=.02, linewidth=2, color='black') pylab.axis([-0.005, 1.001, -0.005, 1.001]) pylab.xlabel('$FPR$') pylab.ylabel('$FNR$') pylab.title(title) if TH != None: pylab.plot(TH['fpr'], TH['fnr'], 'ob', markersize=12, label='TH Risk={0:.3f}'.format(TH['risk'])) if NoTH != None: pylab.plot(NoTH['fpr'], NoTH['fnr'], 'sc', markersize=12, label='BM Risk={0:.3f}'.format(NoTH['risk'])) pyplot.legend(numpoints=1, prop={'size': 16}) pylab.savefig(fname) pylab.grid() ax.set_aspect('equal') pylab.show() pylab.close()
def plotAssignment(idx, coords, centroids, warehouseCoord, output): V = max(idx) + 1 cmap = plt.cm.get_cmap('Dark2') customerColors = [cmap(1.0 * idx[i] / V) for i in range(len(idx))] centroidColors = [cmap(1.0 * i / V) for i in range(V)] xy = coords pylab.scatter([warehouseCoord[0]], [warehouseCoord[1]]) pylab.scatter(centroids[:,0], centroids[:,1], marker='o', s=500, linewidths=2, c='none') pylab.scatter(centroids[:,0], centroids[:,1], marker='x', s=500, linewidths=2, c=centroidColors) pylab.scatter(xy[:,0], xy[:,1], s=100, c=customerColors) for cluster in range(V): customerIndices = indices(cluster, idx) clusterCustomersCoords = [warehouseCoord] + [list(coords[i]) for i in customerIndices] N = len(clusterCustomersCoords) for i in range(N): j = (i+1) % N x = clusterCustomersCoords[i][0] y = clusterCustomersCoords[i][1] dx = clusterCustomersCoords[j][0] - clusterCustomersCoords[i][0] dy = clusterCustomersCoords[j][1] - clusterCustomersCoords[i][1] pylab.arrow(x, y, dx, dy, color=centroidColors[cluster], fc="k", head_width=1.0, head_length=2.5, length_includes_head=True) pylab.savefig(output) pylab.close()
def fig_spec(po, pos, sig_loc, typ=0): ax1 = py.subplot(gs[pos[2]:pos[3], pos[0]:pos[1]]) set_axis(ax1, -0.05, 1.05, letter= po) freq, time_spec, spec_mtrx = spectrogram(sig_loc, Fs, nperseg=2*Fs) im = py.pcolormesh(time_spec/60, freq, spec_mtrx, norm = LogNorm(vmin = 1e1, vmax=5e2), vmax=400, cmap= 'Greens') py.ylim(0,150) # cbar=py.colorbar() # cbar.ax.set_title('power ($mV^2$)', fontsize = 12) times = [2.9, 3.4, 6.3, 6.8] if typ=='naris': for time in times: py.axvline(time, color='grey', ls='--', lw=1) py.text(2.6, 160, 'naris block', color='black', fontsize=15) py.text(6, 160, 'naris block', color='black', fontsize=15) else: py.axvline(1.45, color='grey', ls='--', lw=4) py.text(1.45, 170, 'KX injection', color='black', fontsize=15) py.arrow(1.45, 165, 0, -10, length_includes_head=True, clip_on = False, head_width=0.1, head_length=4) # py.axvline(105, color='red', ls='--', lw=2) ax1.spines['right'].set_visible(False) ax1.spines['top'].set_visible(False) py.xlabel('Time (min)') py.ylabel('Frequency (Hz)') cax2 = make_axes_locatable(ax1).append_axes("right", size="5%", pad=0) cbar = py.colorbar(im, cax = cax2)#, format=mpl.ticker.FuncFormatter(fmt)) cbar.ax.set_title('$mV^2$', fontsize = 12) cbar.ax.tick_params(labelsize=12)
def triangle_vector_space(S,T,r, steps = 21): """ This draws the phase space in term of the triangular description of phase space, given a game specified by S, T and r. Steps defines the number ofdecrete steps to take in each axis. Note ==== This was a mostly experimental idea, it is not currently in use """ ##Initialise a population at a certain point, with small frequencies of mutants around it M = GP_evo3(S,T,r=r, steps = steps) pl.figure() pl.plot( [0,.5],[0,1], color = 'black', linewidth = 1 ) pl.plot( [0.5,1],[1,0], color = 'black', linewidth = 1 ) xa_s = np.linspace(0,1,101) pl.plot( xa_s, map(M.phi_R,xa_s), '--', color = 'black', linewidth = 2.5 ) pl.xlabel( '$x_A$', fontsize = 30 ) pl.ylabel( '$\\varphi$', fontsize = 30 ) for i in xrange(steps): for j in xrange(steps): arrow = delta_x(i,j,M) #print arrow pl.arrow( *arrow ) pl.show()
def plot_match_displacement(im1, locs1, locs2, matchscores, numMatches=-1): """ show a figure with lines where feats in im1 moved to in im2 input: im1 (image as array), locs1,locs2 (location of features), matchscores (as output from 'match'), numMatches (number of matches to plot) """ if numMatches == -1: numMatches = len(matchscores) pylab.gray() pylab.imshow(im1) cols1 = im1.shape[1] for i in range(numMatches): if matchscores[i] > 0: pylab.arrow(locs1[i, 1], locs1[i, 0], locs2[int(matchscores[i]), 1] - locs1[i, 1], locs2[int(matchscores[i]), 0] - locs1[i, 0], head_width=1.0, head_length=2.0, linewidth=0.5, fc='r', ec='r') pylab.axis('off') pylab.show()
def plot(self,plot_frame,**kwargs): import pylab as plb default_args = {'draw_frame':True, 'frame_head_width':20, 'contour_kwargs':{'edgecolor': 'none', 'linewidth': 0.0, 'facecolor': 'none'}} from pylab import plot,arrow lines = self.model.coords_from_frame(plot_frame) self.curves = list() #plot_args = kwargs.pop('plot_args',default_args) for line_key in lines.keys(): try: element_args = kwargs['contour_kwargs'][line_key] except KeyError: element_args = default_args['contour_kwargs'] line = lines[line_key] from matplotlib.patches import Polygon poly = Polygon(zip(line[0,:],line[1,:]),**element_args) #plb.plot([1,2,3,4]) plb.gca().add_patch(poly,) if 'draw_frame' in kwargs.keys(): if kwargs['draw_frame']: frame_args = dict() p = plot_frame['p'] a1 = plot_frame['a1'] a2 = plot_frame['a2'] frame_args['color'] = 'g' frame_args['head_width'] = kwargs['frame_head_width'] arrow(p[0],p[1],a1[0],a1[1],**frame_args) frame_args['color'] = 'b' frame_args['head_width'] = kwargs['frame_head_width'] arrow(p[0],p[1],a2[0],a2[1],**frame_args)
def plot_ch(): for job in jobs_orig: print "plane of", job.path pylab.clf() x_center = int((job.position(0)[0] + job.position(1)[0])/2) x_final = 50 + x_center #plane = np.concatenate((job.plane(y=50)[:, x_final:], # job.plane(y=50)[:, :x_final]), axis=1) plane = job.plane(y=50) myplane = plane[plane < 0.0] p0 = myplane.min() p12 = np.median(myplane) p14 = np.median(myplane[myplane<p12]) p34 = np.median(myplane[myplane>p12]) p1 = myplane.max() contour_values = (p0, p14, p12, p34, p1) pylab.title(r'$u=%.4f,\ D=%.4f,\ Q=%i$ ' % ((job.u_x**2+job.u_y**2)**0.5, job.D_minus, job.ch_objects)) car = pylab.imshow(plane, vmin=-0.001, vmax=0.0, interpolation='nearest') pylab.contour(plane, contour_values, linestyles='dashed', colors='white') print job.u_x, job.u_y pylab.grid(True) pylab.colorbar(car) pylab.arrow(1, 1, 2*job.u_x/(job.u_x if job.u_x else 1.0), 2*job.u_y/(job.u_y if job.u_y else 1.0), width=0.5) #imgfilename = 'plane_r20-y50-u_x%.4fD%.4fch%03i.png' % \ # (job.u_x, job.D_minus, job.ch_objects) imgfilename = 'plane_%s.png' % job.job_id pylab.savefig(imgfilename)
def add_point(event): x, y = event.xdata, event.ydata points.append((x, y)) pylab.cla() pylab.scatter(*zip(*points)) pylab.xlim(-10, 10) pylab.ylim(-10, 10) pylab.draw() if len(points) < 3: return c, r = three_point_circle(*points) cir = pylab.Circle(c, r) pylab.gca().add_patch(cir) for p in points: angle = angle_at_point(c, p) if angle < 0: angle += 2*np.pi if angle >= np.pi: angle = angle - np.pi print np.degrees(angle) dx, dy = np.array((np.cos(angle), np.sin(angle))) pylab.text(p[0], p[1], "%.2f"%np.degrees(angle)) pylab.arrow(p[0], p[1], dx, dy) pylab.show()
def arc(xx, yy, index): A = array([xx[0], yy[0]]) B = array([xx[1], yy[1]]) plot(A[0], A[1], "ko") plot(B[0], B[1], "ko") AB = B - A AB_len = sqrt(sum(AB**2)) AB = AB / AB_len pAB = array([AB[1], -AB[0]]) AB_mid = (A + B) / 2. if index == 1: R = AB_mid + pAB * AB_len / 1.5 else: R = AB_mid + pAB * AB_len / 4. r = sqrt(sum((A - R)**2)) P_arrow = R - pAB * r # Draw the arc from A to B centered at R phi1 = atan2((A - R)[1], (A - R)[0]) phi2 = atan2((B - R)[1], (B - R)[0]) n = 100 # number of divisions phi = linspace(phi1, phi2, n) xx = r * cos(phi) + R[0] yy = r * sin(phi) + R[1] plot(xx, yy, "k-", lw=2) x, x2 = xx[n / 2 - 1:n / 2 + 1] y, y2 = yy[n / 2 - 1:n / 2 + 1] dx = x2 - x dy = y2 - y arrow(x, y, dx / 2, dy / 2, fc="black", head_width=0.05)
def multiple_optima(gene_number=937, resolution=80, model_restarts=10, seed=10000, optim_iters=300): """Show an example of a multimodal error surface for Gaussian process regression. Gene 939 has bimodal behaviour where the noisey mode is higher.""" # Contour over a range of length scales and signal/noise ratios. length_scales = np.linspace(0.1, 60.0, resolution) log_SNRs = np.linspace(-3.0, 4.0, resolution) data = GPy.util.datasets.della_gatta_TRP63_gene_expression(gene_number) # data['Y'] = data['Y'][0::2, :] # data['X'] = data['X'][0::2, :] data["Y"] = data["Y"] - np.mean(data["Y"]) lls = GPy.examples.regression._contour_data(data, length_scales, log_SNRs, GPy.kern.rbf) pb.contour(length_scales, log_SNRs, np.exp(lls), 20, cmap=pb.cm.jet) ax = pb.gca() pb.xlabel("length scale") pb.ylabel("log_10 SNR") xlim = ax.get_xlim() ylim = ax.get_ylim() # Now run a few optimizations models = [] optim_point_x = np.empty(2) optim_point_y = np.empty(2) np.random.seed(seed=seed) for i in range(0, model_restarts): # kern = GPy.kern.rbf(1, variance=np.random.exponential(1.), lengthscale=np.random.exponential(50.)) kern = GPy.kern.rbf(1, variance=np.random.uniform(1e-3, 1), lengthscale=np.random.uniform(5, 50)) m = GPy.models.GPRegression(data["X"], data["Y"], kernel=kern) m["noise_variance"] = np.random.uniform(1e-3, 1) optim_point_x[0] = m["rbf_lengthscale"] optim_point_y[0] = np.log10(m["rbf_variance"]) - np.log10(m["noise_variance"]) # optimize m.optimize("scg", xtol=1e-6, ftol=1e-6, max_f_eval=optim_iters) optim_point_x[1] = m["rbf_lengthscale"] optim_point_y[1] = np.log10(m["rbf_variance"]) - np.log10(m["noise_variance"]) pb.arrow( optim_point_x[0], optim_point_y[0], optim_point_x[1] - optim_point_x[0], optim_point_y[1] - optim_point_y[0], label=str(i), head_length=1, head_width=0.5, fc="k", ec="k", ) models.append(m) ax.set_xlim(xlim) ax.set_ylim(ylim) return m # (models, lls)
def arrows(points_from, points_to, color='k', width=None, width_ratio=0.002, label=None, label_kw={}, margin_ratio=None, **kw): """draw arrows from each point_from to each point_to. - points_from, points_to: each is a seq of xy pairs. - color or c: arrow color(s). - width: arrow width(s), default to auto adjust with width_ratio. - width_ratio: set width to minimal_axisrange * width_ratio. - label=None: a list of strs to label the arrow heads. - label_kw: pass to pylab.text(x,y,txt,...) - margin_ratio: if provided as a number, canvas margins will be set to axisrange * margin_ratio. **kw: params pass to pylab.arrow(,...) """ # convert and valid check of the points points_from = asarray(points_from, float) points_to = asarray(points_to, float) num_points = len(points_from) if len(points_to) != num_points: raise ValueError('Length of two group of points unmatched') if not width: #auto adjust arrow widt min_range = min(asarray(xlim()).ptp(), asarray(ylim()).ptp()) width = min_range * width_ratio #vectorize colors and width if necessary color = kw.pop('c', color) if isscalar(color): color = [color] * num_points if isscalar(width): width = [width] * num_points #draw each arrow #?? length_include_head=True will break?? default = {'length_includes_head': False, 'alpha': 0.75} kw = dict(default, **kw) for (x0, y0), (x1, y1), w, c in zip(points_from, points_to, width, color): pylab.arrow(x0, y0, x1 - x0, y1 - y0, edgecolor=c, facecolor=c, width=w, **kw) if label: #label the arrow heads text_points(points_to, label, **label_kw) #hack fix of axis limits, otherwise some of the arrows will be invisible #not neccessary if the points were also scattered if margin_ratio is not None: x, y = concatenate((points_from, points_to)).T #all the points xmargin = x.ptp() * margin_ratio ymargin = y.ptp() * margin_ratio xlim(x.min() - xmargin, x.max() + xmargin) ylim(y.min() - ymargin, y.max() + xmargin) return
def scatter_particles(self, state): for particle in state["particles"]: x, y = particle["x"] vx, vy = particle["v"] if particle["id"] == state["best_id"]: pl.scatter(x, y, c='y', s=35) else: pl.scatter(particle["x"][0], particle["x"][1], c='k') pl.arrow(x, y, vx, vy, shape="full", head_width=0.03, width=0.00001, alpha=0.3)
def draw_edges(graph, arrow_width=.1, color=(.7, .7, .7)): """Draw the edges of a networkx graph""" for i in graph.edges(): pylab.arrow(i[0][1], i[0][0], .5 * (i[1][1] - i[0][1]), .5 * (i[1][0] - i[0][0]), width=arrow_width, color=color)
def Finish(self): import matplotlib matplotlib.use('agg') import pylab fig = pylab.figure(figsize=(10, 4)) fig.subplots_adjust(wspace=0.3, bottom=0.15) ax = pylab.subplot(1, 2, 1) for track in self.tracks[:50]: l = inner.intersection(track.pos, track.dir).first pylab.arrow(track.pos.x, track.pos.y, l * track.dir.x, l * track.dir.y, edgecolor='k', head_width=10, width=1e-2) pylab.scatter([track.pos.x], [track.pos.y]) ax.add_artist( self.cylinder_patch(outer, 'top', facecolor="None", edgecolor='r')) ax.add_artist( self.cylinder_patch(inner, 'top', facecolor="None", edgecolor='r')) ax.set_aspect('equal') ax.set_xlabel('x [m]') ax.set_ylabel('y [m]') ax.set_ylim((-1000, 1000)) ax.set_xlim((-1000, 1000)) ax = pylab.subplot(1, 2, 2) for track in self.tracks: if abs(track.pos.y) < 20: l = inner.intersection(track.pos, track.dir).first pylab.arrow(track.pos.x, track.pos.z, l * track.dir.x, l * track.dir.z, edgecolor='k', head_width=10, width=1e-2) pylab.scatter([track.pos.x], [track.pos.z]) ax.add_artist( self.cylinder_patch(outer, 'side', facecolor="None", edgecolor='r')) ax.add_artist( self.cylinder_patch(inner, 'side', facecolor="None", edgecolor='r')) ax.set_aspect('equal') ax.set_xlabel('x [m]') ax.set_ylabel('z [m]') ax.set_ylim((-1000, 1000)) ax.set_xlim((-1000, 1000)) pylab.savefig(args.outfile)
def test_optimal_angle_filter(): image = pylab.imread(sys.argv[1]) image = np.mean(image, axis=2) image = image[::-1] pylab.gray() f = AngleFilter((7, 7)) components = f.get_component_values(image, mode='same') angles = np.radians(range(0, 180, 1)) def best_angle_value(c): values = f.basis.response_at_angle(c, angles) return angles[np.argmax(values)], np.max(values) for y, x in np.ndindex(components.shape[:2]): if y%4 != 0: continue if x%4 != 0: continue maxval = f.basis.max_response_value(components[y,x]) if maxval < 2: continue maxang_an = f.basis.max_response_angle(components[y,x]) maxang, maxval = best_angle_value(components[y,x]) pylab.scatter(x, y) dy = -5.0 dx, dy = np.array((np.cos(maxang), np.sin(maxang)))*10 #dx = np.tan(maxang_an)*dy #d = d/np.linalg.norm(d)*3 pylab.arrow(x, y, dx, dy, color='blue') #d = np.array((-np.sin(maxang_an), -np.cos(maxang_an))) #d = d/np.linalg.norm(d)*3 #pylab.arrow(x, y, d[0], d[1], color='green') #pylab.plot(x, y, '.') pylab.imshow(image, origin="lower") #pylab.xlim(0, components.shape[1]) #pylab.ylim(components.shape[0], 0) pylab.show() return #pylab.subplot(1,2,1) #pylab.imshow(image) #pylab.subplot(1,2,2) filtered = np.zeros(image.shape) for y, x in np.ndindex(components.shape[:2]): maxval = f.basis.max_response_value(components[y,x]) minval = f.basis.min_response_value(components[y,x]) #print maxval, minval filtered[y,x] = maxval #filtered[y, x] = best_angle_value(components[y,x]) #pylab.hist(filtered.flatten()) pylab.imshow(filtered > 3) pylab.show()
def drawScaledEigenvectors(X,Y, eigVectors, eigVals, theColor='k'): """ Draw scaled eigenvectors starting at (X,Y)""" # For each eigenvector for col in xrange(eigVectors.shape[1]): # Draw it from (X,Y) to the eigenvector length # scaled by the respective eigenvalue pylab.arrow(X,Y,eigVectors[0,col]*eigVals[col], eigVectors[1,col]*eigVals[col], width=0.01, color=theColor)
def imshow_cube_image(image, header=None, compass=True, blackhole=True, cmap=None): """ Call imshow() to plot a cube image. Make sure it is already masked. Also pass in the header to do the compass rose calculations. """ # Setup axis info (x is the 2nd axis) xcube = (np.arange(image.shape[1]) - m31pos[0]) * 0.05 ycube = (np.arange(image.shape[0]) - m31pos[1]) * 0.05 xtickLoc = py.MultipleLocator(0.4) if cmap is None: cmap = py.cm.jet # Plot the image. py.imshow(image, extent=[xcube[0], xcube[-1], ycube[0], ycube[-1]], cmap=cmap) py.gca().get_xaxis().set_major_locator(xtickLoc) py.xlabel('X (arcsec)') py.ylabel('Y (arcsec)') # Get the spectrograph position angle for compass rose if compass is True: if header is None: pa = paSpec else: pa = header['PA_SPEC'] # Make a compass rose cosSin = np.array([ math.cos(math.radians(pa)), math.sin(math.radians(pa)) ]) arr_base = np.array([ xcube[-1]-0.5, ycube[-1]-0.6 ]) arr_n = cosSin * 0.2 arr_w = cosSin[::-1] * 0.2 py.arrow(arr_base[0], arr_base[1], arr_n[0], arr_n[1], edgecolor='w', facecolor='w', width=0.03, head_width=0.08) py.arrow(arr_base[0], arr_base[1], -arr_w[0], arr_w[1], edgecolor='w', facecolor='w', width=0.03, head_width=0.08) py.text(arr_base[0]+arr_n[0]+0.1, arr_base[1]+arr_n[1]+0.1, 'N', color='white', horizontalalignment='left', verticalalignment='bottom') py.text(arr_base[0]-arr_w[0]-0.15, arr_base[1]+arr_w[1]+0.1, 'E', color='white', horizontalalignment='right', verticalalignment='center') if blackhole is True: py.plot([0], [0], 'ko') py.xlim([-0.5, 0.6]) py.ylim([-2.0, 1.8])
def arrow(start=(0, 0), vel=(0, (0, 0)), color='b'): if vel == (0, (0, 0)): xr, yr = 0.1, 0.1 else: if vel[0] == 0: sp = 0.1 else: sp = vel[0] x = vel[1][0] y = vel[1][1] xr = sp * x * qq(x, y) yr = sp * y * qq(x, y) pylab.arrow(start[0], start[1], xr, yr, head_width=0.05, head_length=0.1, color=color)
def show_angle(angle,power): ARROW_STEP = 40 kernel = np.ones((ARROW_STEP,ARROW_STEP)) rowFilter = gaussian(ARROW_STEP,ARROW_STEP/5) colFilter = rowFilter gb180 = cmt.get_cmap('gb180') #X = np.arange(0,angle.shape(-1),ARROW_STEP) #Y = np.arange(0,angle.shape(-2),ARROW_STEP) x = np.matrix(np.arange(ARROW_STEP/2,angle.shape[-1],ARROW_STEP)) y = np.transpose(np.matrix(np.arange(ARROW_STEP/2,angle.shape[-2],ARROW_STEP))) X = np.array((0*y+1)*x) Y = np.array(y*(0*x+1)) #u = convolve2d(sin(angle),kernel,mode='same') #v = convolve2d(cos(angle),kernel,mode='same') #p = convolve2d(power,kernel,mode='same') u = sepfir2d(np.sin(angle),rowFilter,colFilter) v = sepfir2d(np.cos(angle),rowFilter,colFilter) p = sepfir2d(power,rowFilter,colFilter) U = u[ARROW_STEP/2::ARROW_STEP,ARROW_STEP/2::ARROW_STEP]*p[ARROW_STEP/2::ARROW_STEP,ARROW_STEP/2::ARROW_STEP] V = v[ARROW_STEP/2::ARROW_STEP,ARROW_STEP/2::ARROW_STEP]*p[ARROW_STEP/2::ARROW_STEP,ARROW_STEP/2::ARROW_STEP] #U = sin(angle[ARROW_STEP/2::ARROW_STEP,ARROW_STEP/2::ARROW_STEP])*(power[ARROW_STEP/2::ARROW_STEP,ARROW_STEP/2::ARROW_STEP]) #V = cos(angle[ARROW_STEP/2::ARROW_STEP,ARROW_STEP/2::ARROW_STEP])*(power[ARROW_STEP/2::ARROW_STEP,ARROW_STEP/2::ARROW_STEP]) #X = X[(power[::ARROW_STEP,::ARROW_STEP]>.016)] #Y = Y[(power[::ARROW_STEP,::ARROW_STEP]>.016)] #U = U[(power[::ARROW_STEP,::ARROW_STEP]>.016)] #V = V[(power[::ARROW_STEP,::ARROW_STEP]>.016)] ua = ARROW_STEP/1.5*np.nansum(np.sin(angle)*power)/np.nansum(power) va = -ARROW_STEP/1.5*np.nansum(np.cos(angle)*power)/np.nansum(power) xc, yc = angle.shape[-1]/2, angle.shape[-2]/2 pylab.imshow(angle,cmap=gb180) #pylab.imshow(angle,cmap='hsv') pylab.quiver(X,Y,U,V,pivot='middle',color='w',headwidth=1,headlength=0) pylab.arrow(xc,yc,ua,va,color='w',linewidth=2) pylab.arrow(xc,yc,-ua,-va,color='w',linewidth=2) ax=pylab.gca() ax.set_axis_off() pylab.show() A = np.arctan2(-ua,va) return A
def snapshot(t, pos, vel, colors, arrow_scale=.2): global img pylab.cla() pylab.axis([0, 1, 0, 1]) pylab.setp(pylab.gca(), xticks=[0, 1], yticks=[0, 1]) for (x, y), (dx, dy), c in zip(pos, vel, colors): dx *= arrow_scale dy *= arrow_scale circle = pylab.Circle((x, y), radius=sigma, fc=c) pylab.gca().add_patch(circle) pylab.arrow( x, y, dx, dy, fc="k", ec="k", head_width=0.05, head_length=0.05 ) pylab.text(.5, 1.03, 't = %.2f' % t, ha='center') pylab.savefig(os.path.join(output_dir, '%04i.png' % img)) img += 1
def snapshot(t, pos, vel, colors, arrow_scale=0.2): global img pylab.cla() pylab.axis([0, 1, 0, 1]) pylab.setp(pylab.gca(), xticks=[0, 1], yticks=[0, 1]) for (x, y), (dx, dy), c in zip(pos, vel, colors): dx *= arrow_scale dy *= arrow_scale circle = pylab.Circle((x, y), radius=sigma, fc=c) pylab.gca().add_patch(circle) pylab.arrow(x, y, dx, dy, fc="k", ec="k", head_width=0.05, head_length=0.05) pylab.text(0.5, 1.03, "t = %.2f" % t, ha="center") pylab.savefig(os.path.join(output_dir, "%d.png" % img)) img += 1
def riemann(): # grid info xmin = 0.0 xmax = 1.0 nzones = 1 ng = 0 gr = gpu.grid(nzones, xmin=xmin, xmax=xmax) #------------------------------------------------------------------------ # plot a domain without ghostcells gpu.drawGrid(gr) gpu.labelCenter(gr, 0, r"$i$") gpu.labelCellCenter(gr, 0, r"$q_i$") gpu.markCellLeftState(gr, 0, r"$q_{i-1/2,R}^{n+1/2}$", color="r") gpu.markCellRightState(gr, 0, r"$q_{i+1/2,L}^{n+1/2}$", color="r") pylab.arrow(gr.xc[0]-0.05*gr.dx, 0.5, -0.13*gr.dx, 0, shape='full', head_width=0.075, head_length=0.05, lw=1, width=0.01, edgecolor="none", facecolor="r", length_includes_head=True, zorder=100) pylab.arrow(gr.xc[0]+0.05*gr.dx, 0.5, 0.13*gr.dx, 0, shape='full', head_width=0.075, head_length=0.05, lw=1, width=0.01, edgecolor="none", facecolor="r", length_includes_head=True, zorder=100) pylab.xlim(gr.xl[0]-0.25*gr.dx,gr.xr[2*ng+nzones-1]+0.25*gr.dx) # pylab.ylim(-0.25, 0.75) pylab.axis("off") pylab.subplots_adjust(left=0.05,right=0.95,bottom=0.05,top=0.95) f = pylab.gcf() f.set_size_inches(4.0,2.5) pylab.savefig("states.png") pylab.savefig("states.eps")
def drawScaledEigenvectors(X, Y, eigVectors, eigVals, theColor='k'): """ Draw scaled eigenvectors starting at (X,Y)""" # For each eigenvector for col in xrange(eigVectors.shape[1]): # Draw it from (X,Y) to the eigenvector length # scaled by the respective eigenvalue pylab.arrow(X, Y, eigVectors[0, col] * eigVals[col], eigVectors[1, col] * eigVals[col], width=0.01, color=theColor)
def multiple_optima(gene_number=937,resolution=80, model_restarts=10, seed=10000): """Show an example of a multimodal error surface for Gaussian process regression. Gene 939 has bimodal behaviour where the noisey mode is higher.""" # Contour over a range of length scales and signal/noise ratios. length_scales = np.linspace(0.1, 60., resolution) log_SNRs = np.linspace(-3., 4., resolution) data = GPy.util.datasets.della_gatta_TRP63_gene_expression(gene_number) # Sub sample the data to ensure multiple optima #data['Y'] = data['Y'][0::2, :] #data['X'] = data['X'][0::2, :] # Remove the mean (no bias kernel to ensure signal/noise is in RBF/white) data['Y'] = data['Y'] - np.mean(data['Y']) lls = GPy.examples.regression._contour_data(data, length_scales, log_SNRs, GPy.kern.rbf) pb.contour(length_scales, log_SNRs, np.exp(lls), 20) ax = pb.gca() pb.xlabel('length scale') pb.ylabel('log_10 SNR') xlim = ax.get_xlim() ylim = ax.get_ylim() # Now run a few optimizations models = [] optim_point_x = np.empty(2) optim_point_y = np.empty(2) np.random.seed(seed=seed) for i in range(0, model_restarts): kern = GPy.kern.rbf(1, variance=np.random.exponential(1.), lengthscale=np.random.exponential(50.)) + GPy.kern.white(1,variance=np.random.exponential(1.)) m = GPy.models.GP_regression(data['X'],data['Y'], kernel=kern) optim_point_x[0] = m.get('rbf_lengthscale') optim_point_y[0] = np.log10(m.get('rbf_variance')) - np.log10(m.get('white_variance')); # optimize m.ensure_default_constraints() m.optimize(xtol=1e-6,ftol=1e-6) optim_point_x[1] = m.get('rbf_lengthscale') optim_point_y[1] = np.log10(m.get('rbf_variance')) - np.log10(m.get('white_variance')); pb.arrow(optim_point_x[0], optim_point_y[0], optim_point_x[1]-optim_point_x[0], optim_point_y[1]-optim_point_y[0], label=str(i), head_length=1, head_width=0.5, fc='k', ec='k') models.append(m) ax.set_xlim(xlim) ax.set_ylim(ylim) return (models, lls)
def snapshot(t, pos, vel, colors, arrow_scale=0.2): global img pylab.cla() pylab.axis([0, 1, 0, 1]) pylab.setp(pylab.gca(), xticks=[0, 1], yticks=[0, 1]) for (x, y), (dx, dy), c in zip(pos, vel, colors): # putting position, velocity, and colors arrays into 3D tuple. dx *= arrow_scale # rescale vel_x by multiplying w/ arrow_scale dy *= arrow_scale # rescale vel_y by multiplying w/ arrow_scale circle = pylab.Circle((x, y), radius=sigma, fc=c) # fc sets color of circle pylab.gca().add_patch(circle) pylab.arrow(x, y, dx, dy, fc="k", ec="k", head_width=0.05, head_length=0.05) pylab.text( 0.5, 1.03, "t = %.2f" % t, ha="center" ) # .5 for middle of box on x-axis, 1.03 is just above box on y-axis pylab.savefig(os.path.join(output_dir, "%d.png" % img)) img += 1
def plotSystem(boat, plot_time, r, line_th, u0): fig.canvas.restore_region(background_main) # gather the X and Y location boat_x = boat.state[0] boat_y = boat.state[1] boat_th = boat.state[4] axes = [-PLOT_SIZE, PLOT_SIZE, -PLOT_SIZE, PLOT_SIZE] ax_main.plot([-PLOT_SIZE, PLOT_SIZE], [-PLOT_SIZE, PLOT_SIZE], 'x', markersize=1, markerfacecolor='white', markeredgecolor='white') ax_main.axis(axes) # requires those invisible 4 corner white markers boat_arrow = pylab.arrow(boat_x, boat_y,0.05*np.cos(boat_th),0.05*np.sin(boat_th), fc="g", ec="g", head_width=0.5, head_length=1.0) ax_main.draw_artist(boat_arrow) style = 'b-' if boat.plotData is not None: ax_main.draw_artist(ax_main.plot(boat.plotData[:, 0], boat.plotData[:, 1], style, linewidth=0.25)[0]) ax_main.draw_artist(ax_main.plot([0, 50.*np.cos(line_th)], [0, 50.*np.sin(line_th)], 'k--', linewidth=0.25)[0]) # rectangle coords left, width = 0.01, 0.95 bottom, height = 0.0, 0.96 right = left + width top = bottom + height time_text = ax_main.text(right, top, "time = {:.2f} s".format(plot_time), horizontalalignment='right', verticalalignment='bottom', transform=ax_main.transAxes, size=20) surge_text = ax_main.text(left, top, "u = {:.2f} m/s".format(boat.state[2]), horizontalalignment='left', verticalalignment='bottom', transform=ax_main.transAxes, size=20) location_text = ax_main.text((left+right)/2., top, "r = {:.2f}, th = {:.2f}, u0 = {:.2f}".format(r, np.rad2deg(line_th), u0), horizontalalignment='center', verticalalignment='bottom', transform=ax_main.transAxes, size=20) ax_main.draw_artist(time_text) ax_main.draw_artist(surge_text) ax_main.draw_artist(location_text) fig.canvas.blit(ax_main.bbox)
def snapshot(self, title, pos, vel, sphere_ind, img_name): pylab.subplots_adjust(left=0.10, right=0.90, top=0.90, bottom=0.10) pylab.gcf().set_size_inches(6, 6) pylab.cla() pylab.axis([0, 1, 0, 1]) pylab.setp(pylab.gca(), xticks=[0, 1], yticks=[0, 1]) for (x, y), c in zip(pos, self.colors): circle = pylab.Circle((x, y), radius=self.sigma, fc=c) pylab.gca().add_patch(circle) (dx, dy) = vel dx *= self.arrow_scale dy *= self.arrow_scale pylab.arrow(pos[sphere_ind][0], pos[sphere_ind][1], dx, dy, fc="k", ec="k", head_width=0.1*np.linalg.norm(vel), head_length=0.1*np.linalg.norm(vel)) pylab.text(.5, 1.03, title, ha='center') pylab.savefig(os.path.join(self.output_dir, img_name+".png"))
def showCoulombDirection(ptx, ww, im=None, dd=None, fig=100): """ Show direction of Coulomb peak in an image """ if dd is None: pp = ptx ww = 10 * ww sigma = 5 else: ptx = ptx.reshape((1, 2)) ww = ww.reshape((1, 2)) tr = qtt.data.image_transform(dd) pp = tr.pixel2scan(ptx.T).T pp2 = tr.pixel2scan((ptx + ww).T).T ww = (pp2 - pp).flatten() ww = 40 * ww / np.linalg.norm(ww) sigma = 5 * 3 if fig is not None: if im is not None: plt.figure(fig) plt.clf() if dd is None: plt.imshow(im, interpolation='nearest') else: show2Dimage(im, dd, fig=fig) if fig is not None: plt.figure(fig) hh = pylab.arrow(pp[0, 0], pp[0, 1], ww[0], ww[ 1], linewidth=4, fc="k", ec="k", head_width=sigma / 2, head_length=sigma / 2) hh.set_alpha(0.8) plt.axis('image')
def plot_F(self, scale=1): for i, (X, dx, dy) in enumerate(zip(self.X, self.D['x'], self.D['y'])): j = i * self.ndof if self.frame == '1D': F = [0, self.Fo[j]] else: F = [self.Fo[j], self.Fo[j + 1]] nF = np.linalg.norm(F) if nF != 0: pl.arrow(X[0] + self.scale * dx, X[1] + self.scale * dy, scale * F[0], scale * F[1], head_width=scale * 0.2 * nF, head_length=scale * 0.3 * nF, color=color[1])
def arrows( points_from, points_to, color="k", width=None, width_ratio=0.002, label=None, label_kw={}, margin_ratio=None, **kw ): """draw arrows from each point_from to each point_to. - points_from, points_to: each is a seq of xy pairs. - color or c: arrow color(s). - width: arrow width(s), default to auto adjust with width_ratio. - width_ratio: set width to minimal_axisrange * width_ratio. - label=None: a list of strs to label the arrow heads. - label_kw: pass to pylab.text(x,y,txt,...) - margin_ratio: if provided as a number, canvas margins will be set to axisrange * margin_ratio. **kw: params pass to pylab.arrow(,...) """ # convert and valid check of the points points_from = asarray(points_from, float) points_to = asarray(points_to, float) num_points = len(points_from) if len(points_to) != num_points: raise ValueError("Length of two group of points unmatched") if not width: # auto adjust arrow widt min_range = min(asarray(xlim()).ptp(), asarray(ylim()).ptp()) width = min_range * width_ratio # vectorize colors and width if necessary color = kw.pop("c", color) if isscalar(color): color = [color] * num_points if isscalar(width): width = [width] * num_points # draw each arrow # ?? length_include_head=True will break?? default = {"length_includes_head": False, "alpha": 0.75} kw = dict(default, **kw) for (x0, y0), (x1, y1), w, c in zip(points_from, points_to, width, color): pylab.arrow(x0, y0, x1 - x0, y1 - y0, edgecolor=c, facecolor=c, width=w, **kw) if label: # label the arrow heads text_points(points_to, label, **label_kw) # hack fix of axis limits, otherwise some of the arrows will be invisible # not neccessary if the points were also scattered if margin_ratio is not None: x, y = concatenate((points_from, points_to)).T # all the points xmargin = x.ptp() * margin_ratio ymargin = y.ptp() * margin_ratio xlim(x.min() - xmargin, x.max() + xmargin) ylim(y.min() - ymargin, y.max() + xmargin) return
def plot_seeing_vs_ao(tint=1200, spec_res=100): ap_rad_see = 0.4 ap_rad_rao = 0.15 in_file_root = '{0:s}/roboAO_sensitivity_t{1:d}_R{2:d}'.format(work_dir, tint, spec_res) in_file_see = '{0:s}_ap{1:0.3f}_seeing'.format(in_file_root, ap_rad_see) in_file_rao = '{0:s}_ap{1:0.3f}'.format(in_file_root, ap_rad_rao) avg_tab_rao = Table.read(in_file_rao + '_avg_tab.fits') avg_tab_see = Table.read(in_file_see + '_avg_tab.fits') # Calculate the band-integrated SNR for each magnitude bin and filter. mag_rao = avg_tab_rao['mag'] mag_see = avg_tab_see['mag'] hdr1 = '# {0:3s} {1:15s} {2:15s} {3:15s}' hdr2 = '# {0:3s} {1:7s} {2:7s} {3:7s} {4:7s} {5:7s} {6:7s}' print hdr1.format('Mag', 'Y SNR (summed)', 'J SNR (summed)', 'H SNR (summed)') print hdr2.format('', 'Robo-AO', 'Seeing', 'Robo-AO', 'Seeing', 'Robo-AO', 'Seeing') print hdr2.format('---', '-------', '-------', '-------', '-------', '-------', '-------') for mm in range(len(mag_rao)): fmt = ' {0:3d} {1:7.1f} {2:7.1f} {3:7.1f} {4:7.1f} {5:7.1f} {6:7.1f}' print fmt.format(mag_rao[mm], avg_tab_rao['snr_sum_y'][mm], avg_tab_see['snr_sum_y'][mm], avg_tab_rao['snr_sum_j'][mm], avg_tab_see['snr_sum_j'][mm], avg_tab_rao['snr_sum_h'][mm], avg_tab_see['snr_sum_h'][mm]) py.clf() py.semilogy(avg_tab_rao['mag'], avg_tab_rao['snr_sum_j'], label='UH Robo-AO', linewidth=2) py.semilogy(avg_tab_rao['mag'], avg_tab_see['snr_sum_j'], label='Seeing-Limited', linewidth=2) py.xlabel('J-band Magnitude') py.ylabel('Signal-to-Noise in 1200 sec') py.xlim(13, 21) py.ylim(1, 1e4) py.arrow(16.1, 30, 4.05, 0, color='red', width=2, head_width=10, head_length=0.5, length_includes_head=True, fc='red', ec='red') py.text(17.3, 11, '250x More\nSupernovae Ia', color='red', horizontalalignment='left', fontweight='bold', fontsize=16) py.legend() # py.title('Tint={0:d} s, R={1:d}'.format(tint, spec_res)) py.savefig(in_file_rao + '_proposal.png') return
def plot_match_displacement(im1,locs1,locs2,matchscores, numMatches=-1): """ show a figure with lines where feats in im1 moved to in im2 input: im1 (image as array), locs1,locs2 (location of features), matchscores (as output from 'match'), numMatches (number of matches to plot) """ if numMatches == -1 : numMatches = len(matchscores) pylab.gray() pylab.imshow(im1) cols1 = im1.shape[1] for i in range(numMatches): if matchscores[i] > 0: pylab.arrow(locs1[i,1], locs1[i,0], locs2[int(matchscores[i]),1]-locs1[i,1], locs2[int(matchscores[i]),0]-locs1[i,0], head_width=1.0, head_length=2.0, linewidth=0.5, fc='r', ec='r') pylab.axis('off') pylab.show()
def showPerc(perc): CalSAT = ThreeFourSAT + FourFiveSAT h3 = sorted(CalSAT) fit3 = stats.norm.pdf(h3, avg(CalSAT), stanDev(CalSAT)) plt.plot(h3, fit3, '-go') plt.hist(h3, density=True) plt.title("California Math SAT Averages 2013-2015") #arrow from the right score = calScore(perc, CalSAT) minusScore = score - 1020 if perc > 0.5: plt.arrow(1020, 0, minusScore, 0.01 - perc / 100 + 0.0005, width=0.0006, head_width=0.0012, head_length=30, length_includes_head=True, color="blue") #This arrow was able to start from the right if the percentile was greater than 0.5. The parameter values #were experimented with for quite a bit, and it took perfecting to actually get the arrow to point exactly at #at the desired datapoint. "0.01 - perc/100 + 0.0005" represents the change in y from (1020, 0) on the graph. #The logic behind this is that 0.01 is the max height, and instead of increasing in height, the curve actually #decreases after the local max, as it's concave down. So it decreases in increments of the percentile as it moves #to the right. A similar process is completed upon approaching the maximum point, but it involves increasing the #change in y in increments of percentile instead. #arrow from the left else: plt.arrow(0, 0, calScore(perc, CalSAT), perc / 100 + 0.0013, width=0.0006, head_width=0.0012, head_length=30, length_includes_head=True, color="red") SATScore = calScore(perc, CalSAT) print("SAT Math Score: {}".format(SATScore)) plt.show()
def addArrows(aDict, aColor): for i in aDict: x, y = arrowDict[i] newx, newy = arrowDict[aDict[i]] dx, dy = newx - x, newy - y pylab.arrow( x, y, dx, dy, head_length=0.3, head_width=0.20, color=aColor, linestyle="dotted", length_includes_head=True, )
def plot_graph(classA, classB, wvector, title, b=2): #fig, axis = plt.sublplot(nrows=2, ncols=2) yA = [] xA = [] yB = [] xB = [] for instA, instB in zip(classA, classB): xA.append(instA[0]) yA.append(instA[1]) xB.append(instB[0]) yB.append(instB[1]) #ax = axis[0, 0] plt.plot(xA, yA, 'ro') plt.plot(xB, yB, 'bo') #plt.plot([0, 3], [0, 2], linestyle="dashed", marker="o", color="green") # plot weight vector xW = (0, wvector[1]) yW = (0, wvector[2]) # print wvector[1], wvector[2] # plt.plot(xW, yW, label="weight", linestyle="-", marker="o", color="green") pl.arrow(0, 0, wvector[1][0], wvector[2][0], fc="g", ec="g", head_width=0.15, head_length=0.2) # plot hyperplane #c, a, b = w[0][1], w[1][1], w[2][1] # find y which is X2, assuming X1=0, 10 y1 = -float((wvector[0][0])) / wvector[2][0] y2 = -float((wvector[1][0] * 10 + wvector[0][0])) / wvector[2][0] y1r = float((b - wvector[0][0])) / wvector[2][0] y2r = float(((b - wvector[0][0]) - wvector[1][0] * 10)) / wvector[2][0] # plt.plot((0, 10), (y1r, y2r), "c--") # Wtranspose.Y = b plt.plot((0, 10), (y1, y2), "m--") plt.axis([0, 15, 0, 15]) plt.title(title) plt.draw() plt.show()
def snapshot(t, pos, vel, colors, X, Y, arrow_scale=.2): """ La routine qui s'occupe des tracés graphiques.""" global img nbmax = 20 pylab.subplots_adjust(left=0.10, right=0.90, top=0.90, bottom=0.10) pylab.gcf().set_size_inches(12, 12 * 2 / 3) # Le premier sous-plot: carré de 2x2 ax1 = pylab.subplot2grid((2, 3), (0, 0), colspan=2, rowspan=2) pylab.setp(pylab.gca(), xticks=[0, 1], yticks=[0, 1]) pylab.plot(X, Y, 'k') # On y met le trajet de la dernière particule pylab.xlim((0, 1)) # On doit astreindre les côtés horizontaux pylab.ylim((0, 1)) # et verticaux # Boucle sur les points pour rajouter les cercles colorés for (x, y), c in zip(pos, colors): circle = pylab.Circle((x, y), radius=sigma, fc=c) pylab.gca().add_patch(circle) dx, dy = vel[ -1] * arrow_scale # La dernière particule a droit à son vecteur vitesse pylab.arrow(x, y, dx, dy, fc="k", ec="k", head_width=0.05, head_length=0.05) pylab.text(.5, 1.03, 't = %.2f' % t, ha='center') # Second sous-plot: histogramme de la projection suivant x des vitesses ax2 = pylab.subplot2grid((2, 3), (0, 2), colspan=1, rowspan=1) r = (-2, 2) # Intervalle de vitesses regardé pylab.hist(vel[:, 0], bins=20, range=r) pylab.xlim(r) pylab.ylim((0, nbmax)) pylab.ylabel("Nombre de particules") pylab.xlabel("$v_x$") # Troisième sous-plot: histogramme de la norme des vitesses ax3 = pylab.subplot2grid((2, 3), (1, 2), colspan=1, rowspan=1) r = (0, 2) # Intervalle de vitesses regardé pylab.hist(np.sqrt(np.sum(vel**2, axis=1)), bins=20, range=r) pylab.xlim(r) pylab.ylim((0, nbmax)) pylab.ylabel("Nombre de particules") pylab.xlabel("$||\\vec{v}||$") pylab.savefig(os.path.join(output_dir, '{:04d}.png'.format(img))) img += 1
def addArrows(k,arrowDeltaX,arrowDeltaY,direction,arrowScale=False): desiredSize = 0.5 * k.zoomedBoxHalfSize currentSize = math.sqrt(arrowDeltaX**2+arrowDeltaY**2) if arrowScale == False: arrowScale = desiredSize / currentSize originX1=k.zoomedBoxHalfSize+k.arrowOffsetX originY1=k.zoomedBoxHalfSize+k.arrowOffsetY deltaX1 =arrowDeltaX*arrowScale deltaY1 =arrowDeltaY*arrowScale labelX1 = k.zoomedBoxHalfSize+k.arrowOffsetX+arrowDeltaX*arrowScale*k.labelLengthScale - 10*k.lengthScale labelY1 = k.zoomedBoxHalfSize+k.arrowOffsetY+arrowDeltaY*arrowScale*k.labelLengthScale - 10*k.lengthScale # print "arrowScale", arrowScale, "origin", originX1+k.extraX, originY1+k.extraY, "delta", deltaX1, deltaY1 pylab.arrow(originX1+k.extraX, originY1+k.extraY, deltaX1, deltaY1, color="white",head_width=8*k.lengthScale,head_length=8*k.lengthScale) pylab.text(labelX1+k.extraX,labelY1+k.extraY,direction,color="white")
def plot_path(path): pylab.clf() pylab.xlim(-2, max_size + 1) pylab.ylim(-2, max_size + 1) pylab.axis('off') # Start. pylab.annotate('start', xy=(0, 0), xytext=(-1, -1), size=10, bbox=dict(boxstyle="round4,pad=.5", fc="0.8"), arrowprops=dict(arrowstyle="->")) pylab.annotate('stop', xy=(max_size-1, max_size-1), xytext=(max_size, max_size), size=10, bbox=dict(boxstyle="round4,pad=.5", fc="0.8"), arrowprops=dict(arrowstyle="->")) # Show the food. for f in food: pylab.annotate('food', xy=f, size=5, bbox=dict(boxstyle="round4,pad=.5", fc="0.8"), ha='center') for i in range(len(path) - 1): pylab.arrow(path[i][0], path[i][1], path[i+1][0] - path[i][0], path[i+1][1] - path[i][1])
def plot_displacements(tab): t = Table(np.loadtxt(tab), names=('THING_ID', 'PLATE', 'MJD', 'FIBERID', 'RA', 'DEC', 'Z', 'RA0', 'DEC0'), dtype=(int, int, int, int, float, float, float, float, float)) rand_ind = np.random.choice(np.arange(len(t)), \ replace=False, size=2000) P.figure() for i in rand_ind: x = t['RA0'][i] y = t['DEC0'][i] dx = t['RA'][i]-x dy = t['DEC'][i]-y P.arrow(x, y, dx, dy, color='k', width=0.0003) P.xlim(t['RA'][rand_ind].min(), t['RA'][rand_ind].max()) P.ylim(t['DEC'][rand_ind].min(), t['DEC'][rand_ind].max()) P.show()
def plot(A, title=""): color = ['g', 'c', 'm', 'y'] label = ['SSP', 'SSPM', 'MR'] x1 = [i[0] for i in w1] y1 = [i[1] for i in w1] x2 = [i[0] for i in w2] y2 = [i[1] for i in w2] plt.plot(x1, y1, 'ro') plt.plot(x2, y2, 'bo') for i, a in enumerate(A): x = [-3, 10] y = [-1. * (a[0] + a[1] * j) / a[2] for j in x] plt.plot(x, y, color[i] + '--', label=label[i]) # Plot Vector pl.arrow(0, 0, a[1], a[2], fc=color[i], ec=color[i], head_width=0.15, head_length=0.2) plt.legend(loc=4, borderaxespad=0.) plt.title(title) # plt.axis([-5, 15, -5, 15]) plt.show()
def snapshot(t, pos, vel, colors, arrow_scale=.2): global img ax = pylab.cla() pylab.axis([0, 1, 0, 1], aspect='equal') pylab.setp(pylab.gca(), xticks=[0, 1], yticks=[0, 1]) for (x, y), (dx, dy), c in zip(pos, vel, colors): dx *= arrow_scale dy *= arrow_scale circle = pylab.Circle((x, y), radius=sigma, fc=c) pylab.gca().add_patch(circle) pylab.arrow(x, y, dx, dy, fc="k", ec="k", head_width=0.05, head_length=0.05) pylab.text(.5, 1.03, 't = %.2f' % t, ha='center') img_str = str(img) pylab.show() pylab.pause(0.1) pylab.clf() img += 1
def fig_power(po, pos, sig_loc, start=400, stop = 405, Title = '', asteriks=[0,0]): global freq from mpl_toolkits.axes_grid.inset_locator import inset_axes ax1 = py.subplot(gs[pos[2]:pos[3], pos[0]:pos[1]]) py.title(Title, fontsize=15) set_axis(ax1, -0.1, 1.05, letter= po) labels= ['Olf. bulb', 'Thalamus', 'Visual ctrx'] for i in range(2,-1,-1): sig_loc[i] = notch_filter(sig_loc[i], Fs, np.arange(50, 450, 50)) freq, sp = welch(sig_loc[i], Fs, nperseg = 1*Fs) ax1.plot(freq, sp, lw=4, label=labels[i]) # ax1.text(asteriks[0], asteriks[1] , '*', fontsize=20) py.arrow(asteriks[0], asteriks[1], 0, -12, length_includes_head=True, clip_on = False, head_width=2, head_length=4) # py.ylim(.1, 10e4) py.ylim(0,220) py.xlim(0, 155) py.ylabel('power $mV^2$') ax1.spines['right'].set_visible(False) ax1.spines['top'].set_visible(False) py.xlabel('Frequency (Hz)') if po!='B1': inset_axes = inset_axes(ax1, width="23%", height=1.0, loc=1) for n in range(3,sig_loc.shape[0]): sig_loc[n] = notch_filter(sig_loc[n], Fs, np.arange(50, 450, 50)) freq, sp = welch(sig_loc[n], Fs, nperseg = 1*Fs) py.plot(freq, sp, lw=2, color='green') py.ylim(0,220) py.xlim(0,155) py.xticks(fontsize=11) py.yticks(fontsize=11) # py.ylim(.1, 10e4) # py.yscale('log') # py.text(200,100, 'Olf. bulb propofol') py.xlabel('Frequency (Hz)') if po=='B1': ket = mpatches.Patch(color='green', label='Olf. bulb') kx = mpatches.Patch(color='orange', label='Thalamus LGN') gam = mpatches.Patch(color='blue', label='Visual cortex') ax1.legend(loc='lower right', bbox_to_anchor=(1.2, .7), handles=[ket,kx,gam], ncol=1, frameon = True, fontsize = 15)
def draw_fragment(moves, width=.1): counter = 0 for fragment in moves: counter += 1 pylab.hold(True) def get_color(i): while i >= len(COLORS): i -= len(COLORS) return COLORS[i] coord1 = None if fragment['standard_1']: coord1 = fragment['coord_1'] else: coord1 = list(fragment['coord_1'][0]) coord2 = None if fragment['standard_2']: coord2 = fragment['coord_2'] else: coord2 = list(fragment['coord_2'][1]) coord2.extend(fragment['coord_2'][0][len(coord2):]) for i in range(len(fragment['rob_id'])): color = list(get_color(fragment['rob_id'][i])) if fragment['skipped']: pylab.plot([coord2[i][0]], [coord2[i][1]], marker='o', color=color) continue try: pylab.arrow(coord1[i][0], coord1[i][1], coord2[i][0] - coord1[i][0], coord2[i][1] - coord1[i][1], length_includes_head=True, width=width, head_width=width * 3, color=color) except AssertionError: pass pylab.hold(False)
def show(self): fig = pl.figure(figsize=(10,10)) coords = list() for ii in range(len(self.layers)): for ij in range(len(self.layers[ii].cells)): self.layers[ii].cells[ij].coords = (ii, ij) for ilayer in self.layers: for icell in ilayer.cells: pl.scatter(icell.coords[0], icell.coords[1], c='black') for i in range(len(icell.children)): pl.arrow(icell.coords[0], icell.coords[1], icell.children[i].coords[0] - icell.coords[0], icell.children[i].coords[1] - icell.coords[1], ec=matplotlib.cm.RdYlBu_r((icell.weights[i] + 1.)/2.)) pl.text(icell.coords[0] - 0.2, icell.coords[1] + 0.2, ' '.join(['{:.2f}'.format(w) for w in icell.weights]), c='red') #pl.text(icell.coords[0] - 0.05, icell.coords[1] + 0.2, '{:.2f}'.format(icell.get()), c='green') fig.colorbar(matplotlib.cm.ScalarMappable(norm=matplotlib.colors.Normalize(vmin=-1, vmax=1), cmap='RdYlBu_r'))
def plot_cdf_from_file(filename): """Open file, store cdf to .pdf and .png""" import numpy as np import matplotlib.pyplot as plt import pylab as P data = np.genfromtxt(filename, delimiter=',') # SINR data is best presented in dB from utils import utils data = utils.WTodB(data) import cdf_plot label = ["Iteration %d" % i for i in np.arange(data.shape[0]) + 1] cdf_plot.cdf_plot(data, '-', label=label) # plt.xlabel(xlabel) # plt.ylabel(ylabel) # plt.title(title) P.arrow(0, 50, 40, 0, fc="k", ec="k", head_width=3, head_length=5) plt.savefig(filename + '.pdf', format='pdf') plt.savefig(filename + '.png', format='png')
def test_disp(disp_x, disp_y, rangex=[np.pi / 2 - 1., np.pi / 2 + 1.], rangey=[0.5, np.pi / 2], ndots=1000, factor=1, seed=1): ''' Test displacements by plotting a set of random points in phi, theta''' np.random.seed(seed) nside = hp.npix2nside(disp_x.size) phi = np.random.uniform(rangex[0], rangex[1], ndots) theta = np.random.uniform(rangey[0], rangey[1], ndots) ipix = hp.ang2pix(nside, theta, phi) dphi = disp_x[ipix] dtheta = disp_y[ipix] ra = phi dec = np.pi / 2 - theta dd = np.sqrt(dphi**2 + dtheta**2) alpha = np.arctan2(dphi, dtheta) ## Equation A15 from 0502469 thetap = np.arccos( np.cos(dd) * np.cos(theta) - np.sin(dd) * np.sin(theta) * np.cos(alpha)) phip = phi + np.arcsin(np.sin(alpha) * np.sin(dd) / np.sin(thetap)) rap = phip decp = np.pi / 2 - thetap plt.figure() for t, p, t2, p2 in zip(dec, ra, decp, rap): plt.arrow(p, t, (p2 - p) * factor, (t2 - t) * factor, color='k', width=0.0003) plt.xlim(rangex[1], rangex[0]) plt.ylim(np.pi / 2 - rangey[1], np.pi / 2 - rangey[0])
def gui_repr(self): """Generate a GUI to represent the sentence alignments """ if __pylab_loaded__: fig_width = max(len(self.text_e), len(self.text_f)) + 1 fig_height = 3 pylab.figure(figsize=(fig_width*0.8, fig_height*0.8), facecolor='w') pylab.box(on=False) pylab.subplots_adjust(left=0, right=1, bottom=0, top=1) pylab.xlim(-1, fig_width - 1) pylab.ylim(0, fig_height) pylab.xticks([]) pylab.yticks([]) e = [0 for _ in xrange(len(self.text_e))] f = [0 for _ in xrange(len(self.text_f))] for (i, j) in self.align: e[i] = 1 f[j] = 1 # draw the middle line pylab.arrow(i, 2, j - i, -1, color='r') for i in xrange(len(e)): # draw e side line pylab.text(i, 2.5, self.text_e[i], ha = 'center', va = 'center', rotation=30) if e[i] == 1: pylab.arrow(i, 2.5, 0, -0.5, color='r', alpha=0.3, lw=2) for i in xrange(len(f)): # draw f side line pylab.text(i, 0.5, self.text_f[i], ha = 'center', va = 'center', rotation=30) if f[i] == 1: pylab.arrow(i, 0.5, 0, 0.5, color='r', alpha=0.3, lw=2) pylab.draw()
def coulomb_barrier(): ax = pylab.subplot(111) npts = 200 r = numpy.arange(npts, dtype=numpy.float64)/npts SMALL = 1.e-16 # Coulomb potential C = 1/(r + SMALL) # interior, strong potential V = numpy.zeros(npts) - 2.0 # merge the two U = numpy.where(C < 10.0, C, V) pylab.plot(r, U, 'r', linewidth=2) tlabels = [r"$\lambda_0$"] tpos = [0.1] # draw the axes manually pylab.axis("off") # y-axis pylab.arrow(0, 1.1*min(U), 0, 1.1*max(U) - 1.1*min(U), fc='k', head_width=0.015, head_length=0.18) pylab.text(-0.05*max(r), 1.1*max(U), r"$U$", color="k", size=15) # x-axis pylab.arrow(0, 0, 1.05*max(r), 0, fc='k', head_width=0.12, head_length=0.02) pylab.text(1.05*max(r), -0.025*max(U), r"$r$", color="k", size=15, verticalalignment="top") # draw a line representing a classical particle's energy E = 0.3*max(U) pylab.plot([0, max(r)], [E, E], 'b--') pylab.text(0.75*max(r), 1.05*E, "incoming proton KE", color='b', horizontalalignment="center") # find the x-coord of the classical turning point x = 1.0/E arrow_params = {'length_includes_head':True} pylab.arrow(x, 0, 0, E, fc='0.5', ec='0.5', head_width=0.015, head_length=0.25, **arrow_params) pylab.text(x, -0.025*max(U), r"$r_0$", color="0.5", size=15,horizontalalignment="center", verticalalignment="top") f = pylab.gcf() f.set_size_inches(6.0,6.0) pylab.savefig("coulomb_barrier.png")
def plot(self, scale=3): fs = matplotlib.rcParams['legend.fontsize'] if not hasattr(self, 'F'): self.set_force(self.I) Fmax = np.max(np.linalg.norm(self.F, axis=1)) index = np.append(self.index['PF']['index'], self.index['CS']['index']) names = np.append(self.index['PF']['name'], self.index['CS']['name']) for i, name in zip(index, names): r, z = self.pf_coil[name]['r'], self.pf_coil[name]['z'] F = self.F[i] zarrow = scale * F[1] / Fmax #pl.arrow(r,z,scale*F[0]/Fmax,0, # Fr # linewidth=2,head_width=0.3,head_length=0.4, # ec=0.4*np.ones(3),fc=0.7*np.ones(3)) pl.arrow( r, z, 0, zarrow, # Fz linewidth=2, head_width=0.12, head_length=0.1, ec=0.2 * np.ones(3), fc=0.2 * np.ones(3)) if name in self.index['PF']['name']: zarrow += np.sign(zarrow) * 0.5 if abs(zarrow) < self.pf_coil[name]['dz']: zarrow = np.sign(zarrow) * self.pf_coil[name]['dz'] if zarrow > 0: va = 'bottom' else: va = 'top' pl.text(r, z + zarrow, '{:1.2f}MN'.format(F[1]), ha='center', va=va, fontsize=1.1 * fs, color=0.1 * np.ones(3), backgroundcolor=0.9 * np.ones(3))
def main(): points = [(1,0), (0,1), (-1,0), (0,-1)] plot_shape(points) polar_points = order_points(points) # input in_1 = (1, 0) plt.plot([in_1[0]], [in_1[1]], marker='o', markersize=10, color="y") in_2 = (2, 1) plt.plot([in_2[0]], [in_2[1]], marker='o', markersize=10, color="b") p.arrow(in_1[0], in_1[1], in_2[0] - in_1[0] - 0.15, in_2[1] - in_1[1] - 0.15, fc="k", ec="k", head_width=0.1, head_length=0.15) # vec = Y-X vec = (in_2[0] - in_1[0], in_2[1] - in_1[1]) vec_polar = cartesian_to_polar(vec) plt.plot([vec[0]], [vec[1]], marker='o', markersize=10, color="g") p.arrow(0,0, vec[0] - 0.15, vec[1] - 0.15, fc="k", ec="k", head_width=0.1, head_length=0.15) plt.show() lamda=0 # extract all the angles of vertices res_list = [x[1] for x in polar_points] for idx in range(len(res_list)) : if vec_polar[1] < res_list[idx] : A = polar_to_cartesian(polar_points[idx-1]) B = polar_to_cartesian(polar_points[idx]) # the crossing point cross = cross_point(A, B, vec) # this is the final lamda lamda = vec[0]/cross[0] break #using for testing: lamda = 2 final_vtx=[] for pt in points : final_vtx.append((pt[0]*lamda, pt[1]*lamda)) plot_shape(final_vtx) plt.show()
def plot(self, plot_frame, **kwargs): import pylab as plb default_args = { 'draw_frame': True, 'frame_head_width': 20, 'contour_kwargs': { 'edgecolor': 'none', 'linewidth': 0.0, 'facecolor': 'none' } } from pylab import plot, arrow lines = self.model.coords_from_frame(plot_frame) self.curves = list() #plot_args = kwargs.pop('plot_args',default_args) for line_key in lines.keys(): try: element_args = kwargs['contour_kwargs'][line_key] except KeyError: element_args = default_args['contour_kwargs'] line = lines[line_key] from matplotlib.patches import Polygon poly = Polygon(zip(line[0, :], line[1, :]), **element_args) #plb.plot([1,2,3,4]) plb.gca().add_patch(poly, ) if 'draw_frame' in kwargs.keys(): if kwargs['draw_frame']: frame_args = dict() p = plot_frame['p'] a1 = plot_frame['a1'] a2 = plot_frame['a2'] frame_args['color'] = 'g' frame_args['head_width'] = kwargs['frame_head_width'] arrow(p[0], p[1], a1[0], a1[1], **frame_args) frame_args['color'] = 'b' frame_args['head_width'] = kwargs['frame_head_width'] arrow(p[0], p[1], a2[0], a2[1], **frame_args)