def _gaussian_test(): import matplotlib.pyplot as plt n = 10000 mu_x = 0.0 mu_y = 0.0 #sig_x, sig_y = 1.5, 1.5 tau = 0.0 seeing = 1.5 sigma = seeing / (2. * np.sqrt(2. * np.e)) slit_width = 0.2 slit_height = 10.0 slit_x = np.empty(n, dtype=np.float64) slit_y = np.empty(n, dtype=np.float64) slit_x, slit_y = slit_gaussian_psf(n, mu_x, mu_y, sigma, sigma, tau, slit_width, slit_height) log.info("x range: [%s, %s]", slit_x.min(), slit_x.max()) log.info("y range: [%s, %s]", slit_y.min(), slit_y.max()) plt.scatter(slit_x, slit_y, alpha=0.8) plt.fill([-slit_width/2, slit_width/2, slit_width/2, -slit_width/2], [-slit_height/2, -slit_height/2, slit_height/2, slit_height/2], 'r', alpha=0.10, edgecolor='k') plt.gca().set_aspect("equal") plt.title("Gaussian distribution") plt.xlim([-slit_height/2., slit_height/2]) plt.show()
def plot(self): '''Plot the Delaunay triangularization''' plt.figure() for edge in self.pslg_edges: x = [self.pts[v][0] for v in edge] y = [self.pts[v][1] for v in edge] plt.plot(x, y, 'b', linewidth=2) for key in self.tris: t = self.tris[key] t2 = [v for v in t] t2.append(t[0]) x = [self.pts[v][0] for v in t2] y = [self.pts[v][1] for v in t2] if hasattr(self, 'status'): if key in self.status.keys(): if self.status[key] == 'active': plt.fill(x, y, 'b', alpha=0.2, edgecolor='r') elif self.status[key] == 'done': plt.fill(x, y, 'r', alpha=0.2, edgecolor='r') elif self.status[key] == 'waiting': plt.fill(x, y, 'g', alpha=0.2, edgecolor='r') else: plt.fill(x, y, 'y', alpha=0.2, edgecolor='k') else: plt.fill(x, y, 'g', alpha=0.2, edgecolor='k') for pt in self.pts[4:]: plt.plot(pt[0], pt[1], 'ro') return
def add_region( xx, yy, delta=0, **style ): """ Wrapper around Chips' routine. Will try with all data points, and if it fails then will try to simplify the polygon. """ ###import pychips as chips global _UseLines from matplotlib import pylab as plt if delta > 4: raise RuntimeError("Problem plotting shape") try: if _UseLines: # TODO: append first point onto end to close shape ###chips.add_curve( xx, yy, style) plt.plot(xx,yy, **style) else: ###chips.add_region(xx,yy, style) plt.fill(xx,yy, **style) except Exception as e: delta = delta + 0.1 xp, yp = simplify_polygon( xx, yy, delta=delta) add_region( xp, yp, delta=delta, **style )
def wiggle(Data, SH, skipt=1, maxval=8, lwidth=.1): """ wiggle(Data,SH) """ import matplotlib.pylab as plt t = range(SH['ns']) # t = range(SH['ns'])*SH['dt']/1000000; for i in range(0, SH['ntraces'], skipt): # trace=zeros(SH['ns']+2) # dtrace=Data[:,i] # trace[1:SH['ns']]=Data[:,i] # trace[SH['ns']+1]=0 trace = Data[:, i] trace[0] = 0 trace[SH['ns'] - 1] = 0 plt.plot(i + trace / maxval, t, color='black', linewidth=lwidth) for a in range(len(trace)): if (trace[a] < 0): trace[a] = 0 # pylab.fill(i+Data[:,i]/maxval,t,color='k',facecolor='g') plt.fill(i + Data[:, i] / maxval, t, 'k', linewidth=0) plt.title(SH['filename']) plt.grid(True) plt.show()
def matrix_plot(self, matrix, figure_name='matrix_plot.pdf'): import numpy from matplotlib import pylab def _blob(x, y, area, colour): hs = numpy.sqrt(area) / 2 xcorners = numpy.array([x - hs, x + hs, x + hs, x - hs]) ycorners = numpy.array([y - hs, y - hs, y + hs, y + hs]) pylab.fill(xcorners, ycorners, colour, edgecolor=colour) reenable = False if pylab.isinteractive(): pylab.ioff() pylab.clf() maxWeight = 2**numpy.ceil( numpy.log(numpy.max(numpy.abs(matrix))) / numpy.log(2)) height, width = matrix.shape pylab.fill(numpy.array([0, width, width, 0]), numpy.array([0, 0, height, height]), 'white') pylab.axis('off') pylab.axis('equal') for x in xrange(width): for y in xrange(height): _x = x + 1 _y = y + 1 w = matrix[y, x] if w > 0: _blob(_x - 0.5, height - _y + 0.5, 0.2, '#0099CC') elif w < 0: _blob(_x - 0.5, height - _y + 0.5, 0.2, '#660000') if reenable: pylab.ion() pylab.savefig(figure_name)
def cistrans(args): cob = co.COB(args.cob) if args.out == None: args.out = '{}_cistrans'.format(cob.name) # np.newaxis adds an empty axis in that position of the slice # the sklearn module requires the values to be in the rows: # http://scikit-learn.org/stable/auto_examples/neighbors/plot_kde_1d.html cis = cob.coex \ .score[cob.coex.distance <= args.cis_distance]\ .values[:,np.newaxis] trans = cob.coex\ .score[np.isinf(cob.coex.distance)]\ .values[:,np.newaxis] X_plot = np.linspace(-10,10,1000)[:,np.newaxis] print( 'Found {:,} cis interactions and {:,} trans interactions'.format( cis.shape[0], trans.shape[0] )) # Fit the kernel kd=KernelDensity(bandwidth=0.2) kd.fit(cis) cis_kde = np.exp(kd.score_samples(X_plot)) plt.fill(X_plot,cis_kde,alpha=0.5,label='Cis Interactions') # Fit the trans kd.fit(trans[0:50000]) trans_kde = np.exp(kd.score_samples(X_plot)) plt.fill(X_plot,trans_kde,alpha=0.5,label='Trans Interactions') plt.legend() plt.title('Cis vs Trans Density: {}'.format(cob.name)) # Calculate the mann whitney U test u,pval = sp.stats.mannwhitneyu(cis[:,0],trans[:,0]) print('P-val: {}'.format(pval)) plt.savefig(args.out+'.png')
def add_additional_background(region: SpliceRegion): if region.sites is None: return _, _, y1, y2 = pylab.axis() for site, color in region.sites.items(): try: pylab.vlines(x=site, ymin=y1, ymax=y2, color=color, linestyles="dashed", lw=0.5) except IndexError as err: logger.warning("Indicator line is out of bound: " + str(err)) if region.focus is not None: for left, right in region.focus.items(): try: fill_x = [left, right, right, left] _, _, y1, y2 = pylab.axis() fill_y = [y1, y1, y2, y2] pylab.fill(fill_x, fill_y, alpha=0.1, color='grey') except IndexError as err: logger.warning("focus region is out of bound: " + str(err))
def show_interval(f, a, b, visborder=100, color='b', alpha=0.3, plot_function=True, border=False): """ Plot a timeseries together with a marked interval """ av = max(a - visborder, 0) bv = min(b + visborder, f.shape[1]) x = range(av, bv) minv = np.min(f[:, av:bv]) maxv = np.max(f[:, av:bv]) if plot_function: for i in range(f.shape[0]): plt.plot(x, f[i, av:bv], color='blue', linewidth=1) if border: plt.plot([a, a, b, b, a], [minv, maxv, maxv, minv, minv], color=color, alpha=alpha, linewidth=3) else: plt.fill([a, a, b, b], [minv, maxv, maxv, minv], color=color, alpha=alpha) yborder = abs(maxv - minv) * 0.05 plt.ylim([minv - yborder, maxv + yborder]) return x, av, bv
def gp_regression(x, y_ave, y_std, points): # Training set X = np.atleast_2d(x).T y = y_ave dy = y_std noise = np.random.normal(0, dy) y += noise # Test set x = np.atleast_2d(np.linspace(x[0], x[-1], points)).T kernel = C(1.0, (1e-3, 1e3)) * RBF(10, (1e-2, 1e2)) gp = GaussianProcessRegressor(kernel=kernel, alpha=(dy / y)**2, n_restarts_optimizer=10) gp.fit(X, y) y_pred, sigma = gp.predict(x, return_std=True) if 0: fig = plt.figure() plt.errorbar(X, y, dy, fmt='r.', markersize=10, label=u'Observations') plt.plot(x, y_pred, 'b-', label=u'Prediction') plt.fill(np.concatenate([x, x[::-1]]), np.concatenate([ y_pred - 1.9600 * sigma, (y_pred + 1.9600 * sigma)[::-1] ]), alpha=.5, fc='b', ec='None', label='95% confidence interval') plt.xlabel('$x$') plt.ylabel('$f(x)$') plt.ylim(-1, 1) plt.legend(loc='upper left') return y_pred, sigma
def cistrans(args): cob = co.COB(args.cob) if args.out == None: args.out = "{}_cistrans".format(cob.name) # open an output file out = open(args.out + ".summary.txt", "w") # np.newaxis adds an empty axis in that position of the slice # the sklearn module requires the values to be in the rows: # http://scikit-learn.org/stable/auto_examples/neighbors/plot_kde_1d.html coex = cob._coex_DataFrame(sig_only=False) cis = coex.score[coex.distance <= args.cis_distance].values[:, np.newaxis] trans = coex.score[np.isinf(coex.distance)].values[:, np.newaxis] X_plot = np.linspace(-10, 10, 1000)[:, np.newaxis] str = "Found {:,} cis interactions and {:,} trans interactions".format( cis.shape[0], trans.shape[0]) print(str) print(str, file=out) # Fit the kernel kd = KernelDensity(bandwidth=0.2) kd.fit(cis) cis_kde = np.exp(kd.score_samples(X_plot)) plt.fill(X_plot, cis_kde, alpha=0.5, label="Cis Interactions") # Fit the trans kd.fit(trans[0:50000]) trans_kde = np.exp(kd.score_samples(X_plot)) plt.fill(X_plot, trans_kde, alpha=0.5, label="Trans Interactions") plt.legend() plt.title("Cis vs Trans Density: {}".format(cob.name)) # Calculate the mann whitney U test u, pval = sp.stats.mannwhitneyu(cis[:, 0], trans[:, 0]) print("P-val: {}".format(pval)) print("P-val: {}".format(pval), file=out) print("Figure saved: {}".format(args.out + ".png")) plt.savefig(args.out + ".png")
def matrix_plot(self, matrix, figure_name='matrix_plot.pdf'): import numpy from matplotlib import pylab def _blob(x,y,area,colour): hs = numpy.sqrt(area) / 2 xcorners = numpy.array([x - hs, x + hs, x + hs, x - hs]) ycorners = numpy.array([y - hs, y - hs, y + hs, y + hs]) pylab.fill(xcorners, ycorners, colour, edgecolor=colour) reenable = False if pylab.isinteractive(): pylab.ioff() pylab.clf() maxWeight = 2**numpy.ceil(numpy.log(numpy.max(numpy.abs(matrix)))/numpy.log(2)) height, width = matrix.shape pylab.fill(numpy.array([0,width,width,0]),numpy.array([0,0,height,height]),'white') pylab.axis('off') pylab.axis('equal') for x in xrange(width): for y in xrange(height): _x = x+1 _y = y+1 w = matrix[y,x] if w > 0: _blob(_x - 0.5, height - _y + 0.5, 0.2,'#0099CC') elif w < 0: _blob(_x - 0.5, height - _y + 0.5, 0.2,'#660000') if reenable: pylab.ion() pylab.savefig(figure_name)
def gasket(pa, pb, pc, level, col): if level == 0: plt.fill([pa[0], pb[0], pc[0]], [pa[1], pb[1], pc[1]], col) plt.hold(True) else: gasket(pa, (pa + pb) / 2., (pa + pc) / 2., level - 1, col) gasket(pb, (pb + pa) / 2., (pb + pc) / 2., level - 1, col) gasket(pc, (pc + pa) / 2., (pc + pb) / 2., level - 1, col)
def draw_day_night(self): theta_half = np.radians(np.arange(90,271)) plt.fill(list(self.x0 + self.R*np.cos(theta_half)) + [self.x0 +self.R*np.cos(theta_half[0])], list(self.y0 + self.R*np.sin(theta_half)) + [self.y0 +self.R*np.sin(theta_half[0])], "0.75", zorder=-1)
def gasket(pa, pb, pc, level, color): if level == 0: plt.fill([pa[0], pb[0], pc[0]], [pa[1], pb[1], pc[1]], color) plt.hold(True) else: gasket(pa, (pa + pb) / 2., (pa + pc) / 2., level - 1, color) gasket(pb, (pb + pa) / 2., (pb + pc) / 2., level - 1, color) gasket(pc, (pc + pa) / 2., (pc + pb) / 2., level - 1, color)
def Sierpinski(a, b, c, k, iteration): if iteration == 0: plt.fill([a[0], b[0], c[0]], [a[1], b[1], c[1]], 'b') plt.hold(True) else: Sierpinski(a, bis(a, b, k), bis(a, c, k), k, iteration - 1) Sierpinski(b, bis(a, b, k), bis(b, c, k), k, iteration - 1) Sierpinski(c, bis(a, c, k), bis(b, c, k), k, iteration - 1) plt.hold(True)
def Sierpinski(a,b,c,k,iteration): if iteration==0: plt.fill([a[0], b[0], c[0]], [a[1], b[1], c[1]],'b') plt.hold(True) else: Sierpinski(a,bis(a,b,k),bis(a,c,k),k,iteration-1) Sierpinski(b,bis(a,b,k),bis(b,c,k),k,iteration-1) Sierpinski(c,bis(a,c,k),bis(b,c,k),k,iteration-1) plt.hold(True)
def plot(self, filename=None): import matplotlib.pylab as plt for polygon in self.polygons(): plt.fill([i[0] for i in polygon],[i[1] for i in polygon], polygon.color) plt.axis("equal") if filename is None: plt.show() else: plt.savefig(filename) plt.clf()
def sierpinski(a, b, c, iterations): x=(random.random(),random.random(),random.random()) if iterations == 0: plt.fill([a[0], b[0], c[0]], [a[1], b[1], c[1]], color=x,alpha=0.9) plt.hold(True) else: sierpinski(a, (a + b) / 2., (a + c) / 2., iterations - 1) sierpinski(b, (b + a) / 2., (b + c) / 2., iterations - 1) sierpinski(c, (c + a) / 2., (c + b) / 2., iterations - 1) plt.fill([(a[0] + b[0]) / 2., (a[0] + c[0]) / 2., (b[0] + c[0]) / 2.], [(a[1] + b[1]) / 2., (a[1] + c[1]) / 2., (b[1] + c[1]) / 2.], color=x,alpha=0.9)
def plot(self, filename='', title='', initSize=[]): '''Evolve a haploid population using a ``RandomSelection`` mating scheme using the demographic model. Print population size changes duringe evolution. An initial population size could be specified using parameter ``initSize`` for a demographic model with dynamic initial population size. If a filename is specified and if matplotlib is available, this function draws a figure to depict the demographic model and save it to ``filename``. An optional ``title`` could be specified to the figure. Note that this function can not be plot demographic models that works for particular mating schemes (e.g. genotype dependent).''' if not self.init_size: if initSize: self.init_size = initSize else: raise ValueError( 'Specific self does not have a valid initial population size' ) if filename and not has_plotter: raise RuntimeError( 'This function requires module numpy and matplotlib') self.draw_figure = filename and has_plotter self.pop_regions = OrderedDict() self.pop_base = OrderedDict() # self._reset() if title: print(title) pop = Population(self.init_size, infoFields=self.info_fields, ploidy=1) pop.evolve(matingScheme=RandomSelection(subPopSize=self), postOps=PyOperator(self._recordPopSize), gen=self.num_gens) self._recordPopSize(pop) # if self.draw_figure: fig = plt.figure() ax = fig.add_subplot(111) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') for name, region in self.pop_regions.items(): region = region.reshape(region.size / 4, 4) points = np.append(region[:, 0:2], region[::-1, 2:4], axis=0) plt.fill(points[:, 0], points[:, 1], label=name, linewidth=0, edgecolor='w') leg = plt.legend(loc=2) leg.draw_frame(False) if title: plt.title(title) plt.savefig(filename) plt.close()
def Sierpinski(a,b,c,k,iteration): x=(random.random(),random.random(),random.random()) if iteration==0: plt.fill([a[0], b[0], c[0]], [a[1], b[1], c[1]], color=x,alpha=0.9) plt.hold(True) else: Sierpinski(a,bis(a,b,k),bis(a,c,k),k,iteration-1) Sierpinski(b,bis(a,b,k),bis(b,c,k),k,iteration-1) Sierpinski(c,bis(a,c,k),bis(b,c,k),k,iteration-1) plt.hold(True) plt.fill([bis(a,b,k)[0], bis(a,c,k)[0], bis(b,c,k)[0]], [bis(a,b,k)[1], bis(a,c,k)[1], bis(b,c,k)[1]], color=x,alpha=0.9)
def plot_omega(self, p): omega_m = self.omega_m_field.subfields[0] xdata = omega_m.vtk_X[:, 0] ydata = omega_m.field_arr[:] idata = argsort(xdata) p.fill(xdata[idata], ydata[idata], facecolor='gray', alpha=0.2) print 'max omega', max(ydata[idata]) p.set_ylim(ymin=0, ymax=1.0) p.set_xlabel('bar axis [mm]') p.set_ylabel('omega [-]')
def plot_omega(self, p): omega_m = self.omega_m_field.subfields[0] xdata = omega_m.vtk_X[:, 0] ydata = omega_m.field_arr[:] idata = argsort(xdata) p.fill(xdata[idata], ydata[idata], facecolor="gray", alpha=0.2) print "max omega", max(ydata[idata]) p.set_ylim(ymin=0, ymax=1.0) p.set_xlabel("bar axis [mm]") p.set_ylabel("omega [-]")
def gasket(pa, pb, pc, level): x=(random.random(),random.random(),random.random()) if level == 0: plt.fill([pa[0], pb[0], pc[0]], [pa[1], pb[1], pc[1]], color=x,alpha=0.9) plt.hold(True) else: gasket(pa, (pa + pb) / 2., (pa + pc) / 2., level - 1) gasket(pb, (pb + pa) / 2., (pb + pc) / 2., level - 1) gasket(pc, (pc + pa) / 2., (pc + pb) / 2., level - 1) plt.hold(True) plt.fill([(pa[0] + pb[0]) / 2.,(pb[0] + pc[0]) / 2.,(pa[0] + pc[0]) / 2.], [(pa[1] + pb[1]) / 2.,(pb[1] + pc[1]) / 2.,(pa[1] + pc[1]) / 2.],color=x,alpha=0.9)
def sierpinski(a, b, c, iterations): x = (random.random(), random.random(), random.random()) if iterations == 0: plt.fill([a[0], b[0], c[0]], [a[1], b[1], c[1]], color=x, alpha=0.9) plt.hold(True) else: sierpinski(a, (a + b) / 2., (a + c) / 2., iterations - 1) sierpinski(b, (b + a) / 2., (b + c) / 2., iterations - 1) sierpinski(c, (c + a) / 2., (c + b) / 2., iterations - 1) plt.fill([(a[0] + b[0]) / 2., (a[0] + c[0]) / 2., (b[0] + c[0]) / 2.], [(a[1] + b[1]) / 2., (a[1] + c[1]) / 2., (b[1] + c[1]) / 2.], color=x, alpha=0.9)
def SierpinskiTriangle(a, b, c, iterations): ''' Recursively generated Sierpinski Triangle. ''' if iterations == 0: # Fill the triangle with vertices a, b, c. plt.fill([a[0], b[0], c[0]], [a[1], b[1], c[1]], 'g') plt.hold(True) else: # Recursive calls for the three subtriangles. SierpinskiTriangle(a, (a + b) / 2., (a + c) / 2., iterations - 1) SierpinskiTriangle(b, (b + a) / 2., (b + c) / 2., iterations - 1) SierpinskiTriangle(c, (c + a) / 2., (c + b) / 2., iterations - 1)
def SierpinskiTriangle(a, b, c, iterations): """ Recursively generated Sierpinski Triangle. """ if iterations == 0: # Fill the triangle with vertices a, b, c. plt.fill([a[0], b[0], c[0]], [a[1], b[1], c[1]], "g") plt.hold(True) else: # Recursive calls for the three subtriangles. SierpinskiTriangle(a, (a + b) / 2.0, (a + c) / 2.0, iterations - 1) SierpinskiTriangle(b, (b + a) / 2.0, (b + c) / 2.0, iterations - 1) SierpinskiTriangle(c, (c + a) / 2.0, (c + b) / 2.0, iterations - 1)
def plot(self, filename='', title='', initSize=[]): '''Evolve a haploid population using a ``RandomSelection`` mating scheme using the demographic model. Print population size changes duringe evolution. An initial population size could be specified using parameter ``initSize`` for a demographic model with dynamic initial population size. If a filename is specified and if matplotlib is available, this function draws a figure to depict the demographic model and save it to ``filename``. An optional ``title`` could be specified to the figure. Note that this function can not be plot demographic models that works for particular mating schemes (e.g. genotype dependent).''' if not self.init_size: if initSize: self.init_size = initSize else: raise ValueError('Specific self does not have a valid initial population size') if filename and not has_plotter: raise RuntimeError('This function requires module numpy and matplotlib') self.draw_figure = filename and has_plotter self.pop_regions = OrderedDict() self.pop_base = OrderedDict() # self._reset() if title: print(title) pop = Population(self.init_size, infoFields=self.info_fields, ploidy=1) pop.evolve( matingScheme=RandomSelection(subPopSize=self), postOps=PyOperator(self._recordPopSize), gen=self.num_gens ) self._recordPopSize(pop) # if self.draw_figure: fig = plt.figure() ax = fig.add_subplot(111) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') for name, region in self.pop_regions.items(): region = region.reshape(region.size / 4, 4) points = np.append(region[:, 0:2], region[::-1, 2:4], axis=0) plt.fill(points[:,0], points[:,1], label=name, linewidth=0, edgecolor='w') leg = plt.legend(loc=2) leg.draw_frame(False) if title: plt.title(title) plt.savefig(filename) plt.close()
def draw_person(center, L, rot, color="k"): """ draw a stick figure at the position given by center of height L and rotated by an angle (radians) rot """ # our person is 4 segments # head: upper L/4, so the center of the head is L/8 # above bottom head_center = (center[0], center[1]+0.375*L) head_radius = L/8.0 # arms start at the center left_arm_end = (center[0]-0.25*L, center[1]+0.25*L) right_arm_end = (center[0]+0.25*L, center[1]+0.25*L) # torso is the middle two segments torso_start = (center[0], center[1]-0.25*L) torso_end = (center[0], center[1]+0.25*L) # feet start at torso_star left_foot_end = (center[0]-0.2*L, center[1]-0.5*L) right_foot_end = (center[0]+0.2*L, center[1]-0.5*L) # draw our person theta = np.radians(np.arange(0,361)) hc = _rotate(head_center, center, rot) plt.fill(hc[0] + head_radius*np.cos(theta), hc[1] + head_radius*np.sin(theta), color=color) cc = _rotate(center, center, rot) lc = _rotate(left_arm_end, center, rot) rc = _rotate(right_arm_end, center, rot) plt.plot([cc[0], lc[0]], [cc[1], lc[1]], color=color) plt.plot([cc[0], rc[0]], [cc[1], rc[1]], color=color) ts = _rotate(torso_start, center, rot) te = _rotate(torso_end, center, rot) plt.plot([ts[0], te[0]], [ts[1], te[1]], color=color) lf = _rotate(left_foot_end, center, rot) rf = _rotate(right_foot_end, center, rot) plt.plot([ts[0], lf[0]], [ts[1], lf[1]], color=color) plt.plot([ts[0], rf[0]], [ts[1], rf[1]], color=color)
def draw_person(center, L, rot, color="k"): """ draw a stick figure at the position given by center of height L and rotated by an angle (radians) rot """ # our person is 4 segments # head: upper L/4, so the center of the head is L/8 # above bottom head_center = (center[0], center[1] + 0.375 * L) head_radius = L / 8.0 # arms start at the center left_arm_end = (center[0] - 0.25 * L, center[1] + 0.25 * L) right_arm_end = (center[0] + 0.25 * L, center[1] + 0.25 * L) # torso is the middle two segments torso_start = (center[0], center[1] - 0.25 * L) torso_end = (center[0], center[1] + 0.25 * L) # feet start at torso_star left_foot_end = (center[0] - 0.2 * L, center[1] - 0.5 * L) right_foot_end = (center[0] + 0.2 * L, center[1] - 0.5 * L) # draw our person theta = np.radians(np.arange(0, 361)) hc = _rotate(head_center, center, rot) plt.fill(hc[0] + head_radius * np.cos(theta), hc[1] + head_radius * np.sin(theta), color=color) cc = _rotate(center, center, rot) lc = _rotate(left_arm_end, center, rot) rc = _rotate(right_arm_end, center, rot) plt.plot([cc[0], lc[0]], [cc[1], lc[1]], color=color) plt.plot([cc[0], rc[0]], [cc[1], rc[1]], color=color) ts = _rotate(torso_start, center, rot) te = _rotate(torso_end, center, rot) plt.plot([ts[0], te[0]], [ts[1], te[1]], color=color) lf = _rotate(left_foot_end, center, rot) rf = _rotate(right_foot_end, center, rot) plt.plot([ts[0], lf[0]], [ts[1], lf[1]], color=color) plt.plot([ts[0], rf[0]], [ts[1], rf[1]], color=color)
def plot_np_fit_1D(x_t, y_t, x_data, y_data, y_star_mean, y_star_sigma, u_scale=1.0, ylim=None, lloc="lower right", fignum=101): fig = plt.figure(fignum) plt.plot(x_t, y_t, 'r:', label=u'$f(x) = \sin(x)$') plt.plot(x_data[0:-2], y_data[0:-2], 'r.', markersize=10, label=u'Observations') plt.plot(x_t, y_star_mean, 'b-') plt.fill(np.concatenate([x_t, x_t[::-1]]), np.concatenate([ y_star_mean - u_scale * 1.9600 * y_star_sigma, (y_star_mean + u_scale * 1.9600 * y_star_sigma)[::-1] ]), alpha=.5, fc='b', ec='None', label='Uncertainty') plt.plot(x_t[np.argmax(y_star_mean)], np.amax(y_star_mean), 'gx', markersize=20, label=u'Maximum') plt.plot(x_data[-2], y_data[-2], 'g.', markersize=20, label=u'Latest evaluation') plt.plot(x_data[-1], y_data[-1], 'k.', markersize=20, label=u'Next sample') plt.xlabel('$x$') plt.ylabel('$f(x)$') plt.ylim(ylim) plt.legend(loc=lloc) return fig
def gasket(pa, pb, pc, level): x = (random.random(), random.random(), random.random()) if level == 0: plt.fill([pa[0], pb[0], pc[0]], [pa[1], pb[1], pc[1]], color=x, alpha=0.9) plt.hold(True) else: gasket(pa, (pa + pb) / 2., (pa + pc) / 2., level - 1) gasket(pb, (pb + pa) / 2., (pb + pc) / 2., level - 1) gasket(pc, (pc + pa) / 2., (pc + pb) / 2., level - 1) plt.hold(True) plt.fill([(pa[0] + pb[0]) / 2., (pb[0] + pc[0]) / 2., (pa[0] + pc[0]) / 2.], [(pa[1] + pb[1]) / 2., (pb[1] + pc[1]) / 2., (pa[1] + pc[1]) / 2.], color=x, alpha=0.9)
def Sierpinski(a, b, c, k, iteration): x = (random.random(), random.random(), random.random()) if iteration == 0: plt.fill([a[0], b[0], c[0]], [a[1], b[1], c[1]], color=x, alpha=0.9) plt.hold(True) else: Sierpinski(a, bis(a, b, k), bis(a, c, k), k, iteration - 1) Sierpinski(b, bis(a, b, k), bis(b, c, k), k, iteration - 1) Sierpinski(c, bis(a, c, k), bis(b, c, k), k, iteration - 1) plt.hold(True) plt.fill([bis(a, b, k)[0], bis(a, c, k)[0], bis(b, c, k)[0]], [bis(a, b, k)[1], bis(a, c, k)[1], bis(b, c, k)[1]], color=x, alpha=0.9)
def plot_confidence(x, y_pred, sigma, confidence=1): procent_confidence = erf(confidence/sqrt(2)) return pl.fill( np.concatenate([x, x[::-1]]), np.concatenate([y_pred + confidence*sigma, (y_pred - confidence*sigma)[::-1]]), alpha=.1, fc='b', ec='None', )
def plot_confidence(x, y_mean, y_sigma, confidence=1): procent_confidence = erf(confidence/sqrt(2)) return plt.fill( np.concatenate([x, x[::-1]]), np.concatenate([y_mean + confidence * y_sigma, (y_mean - confidence * y_sigma)[::-1]]), alpha=.1, fc='b', ec='None', )
def wiggle(Data, SH={}, maxval=-1, skipt=1, lwidth=.1): """ wiggle(Data,SH) """ import matplotlib.pylab as plt import numpy as np if 'time' in SH: t = SH['time'] ntraces = SH['ntraces'] ns = SH['ns'] else: ns = Data.shape[0] t = np.arange(ns) ntraces = Data.shape[1] if (maxval <= 0): Dmax = np.max(Data) maxval = -1 * maxval * Dmax for i in range(0, ntraces, skipt): trace = Data[:, i] trace[0] = 0 trace[ns - 1] = 0 plt.plot(i + trace / maxval, t, color='black', linewidth=lwidth) for a in range(len(trace)): if (trace[a] < 0): trace[a] = 0 # pylab.fill(i+Data[:,i]/maxval,t,color='k',facecolor='g') plt.fill(i + Data[:, i] / maxval, t, 'k', linewidth=0) plt.grid(True) plt.gca().invert_yaxis() plt.xlabel('Trace number') if 'time' in SH: plt.ylabel('Time (ms)') else: plt.ylabel('Sample number') if 'filename' in SH: plt.title(SH['filename']) plt.axes().set_xlim(-1, ntraces) plt.show()
def addToPlot(exp, prior, color, cut=True): Nlist = Nlists[exp] Mstr = mstrings[exp] lim = lims[exp] f = [ np.loadtxt("data/posteriors_f/Posterior_f_" + exp + "_Prior_" + prior + "_M=" + Mstr + "_N=" + str(N) + ".txt", unpack=True)[0] for N in Nlist ] P = [ np.loadtxt("data/posteriors_f/Posterior_f_" + exp + "_Prior_" + prior + "_M=" + Mstr + "_N=" + str(N) + ".txt", unpack=True)[1] for N in Nlist ] if (exp == "SKA"): zo = 1.8 elif (exp == "O3"): zo = 1.8 elif (exp == "ET"): zo = 1.5 f_min, f_med, f_max = get_f_intervals(f, P) if (cut): X, Y = getPolygon(Nlist, f_min, f_max, lim) plt.fill(X, Y, color=color, alpha=0.5, lw=0.0, zorder=zo) N_new, f_new = getCutOff(Nlist, f_med, lim) else: plt.fill_between(Nlist, f_min, f_max, color=color, alpha=0.5, lw=0.0, zorder=zo) N_new = 1.0 * Nlist f_new = 1.0 * f_med plt.loglog(N_new, f_new, '-', color=color, zorder=(zo + 0.05)) return N_new[-1]
def plot_with_std(x, y, std, color="b", alpha=0.4, label=None, axes=None, rectify=False, *args, **kwargs): # ----------------------------------------------------------------------------- """ Plots the 2D function with the std area around. """ import matplotlib.pylab as pyl std = np.array(std); x = np.array(x); y = np.array(y) x_f = np.concatenate((x,x[::-1])) y_low = y - std y_high = y + std if not rectify == False: y[y<=rectify]=rectify y_low[y_low<=rectify]=rectify y_high[y_high<=rectify]=rectify y_f = np.concatenate((y_low, y_high[::-1])) if not axes == None: pyl=axes pyl.fill(x_f, y_f, color=color, alpha=alpha, *args, **kwargs) pyl.plot(x, y, color=color, linewidth=2, label=label, *args, **kwargs)
def stackareaplot(self): fig = pyplot.figure() lineas=[] stack = [] k=0 for i in self.yval: stack.append(i) m=0 for j in i: if k > 0: stack[k][m]=stack[k][m]+stack[k-1][m] m = m+1 k=k+1 j=0 xss=[] yss=[] used_colors=[] for i in stack: linea = pyplot.plot(self.xval,i,self.colors[j]) used_colors.append(self.colors[j]) lineas.append(linea[0]) xs,ys = pylab.poly_between(self.xval,0,i) xss.append(xs) yss.append(ys) j=j+1 if j>19: j = 0 j=0 k=-1 used_colors_inv = used_colors[::-1] for i in yss: pylab.fill(xss[0], yss[k], used_colors_inv[j]) j=j+1 k=k-1 pyplot.legend(lineas,self.tags,'best') pyplot.title(self.title) pyplot.xlabel('Time (s)') pyplot.ylabel('Airtime consumption (%)') pyplot.grid(True) pyplot.show()
def stackareaplot(self): fig = pyplot.figure() lineas = [] stack = [] k = 0 for i in self.yval: stack.append(i) m = 0 for j in i: if k > 0: stack[k][m] = stack[k][m] + stack[k - 1][m] m = m + 1 k = k + 1 j = 0 xss = [] yss = [] used_colors = [] for i in stack: linea = pyplot.plot(self.xval, i, self.colors[j]) used_colors.append(self.colors[j]) lineas.append(linea[0]) xs, ys = pylab.poly_between(self.xval, 0, i) xss.append(xs) yss.append(ys) j = j + 1 if j > 19: j = 0 j = 0 k = -1 used_colors_inv = used_colors[::-1] for i in yss: pylab.fill(xss[0], yss[k], used_colors_inv[j]) j = j + 1 k = k - 1 pyplot.legend(lineas, self.tags, 'best') pyplot.title(self.title) pyplot.xlabel('Time (s)') pyplot.ylabel('Airtime consumption (%)') pyplot.grid(True) pyplot.show()
def export(self, filename, limits=None): import matplotlib.pylab as plt plt.style.use('dark_background') if limits is None: xmin, xmax, ymin, ymax = self.get_limits() else: xmin, xmax, ymin, ymax = limits for x in range(xmin,xmax+1): plt.plot([x,x],[ymin,ymax],"w-") for y in range(ymin,ymax+1): plt.plot([xmin,xmax],[y,y],"w-") for x,y in self.alive: if xmin <= x < xmax and ymin <= y < ymax: plt.fill([x,x+1,x+1,x,x],[y,y,y+1,y+1,y],"w") plt.tick_params(axis='x',which='both',bottom='off',top='off',labelbottom='off') plt.tick_params(axis='y',which='both',left='off',right='off',labelleft='off') plt.axis("equal") plt.box("off") plt.savefig(filename) plt.clf()
def _uniform_test(): import matplotlib.pyplot as plt n = 10000 slit_x = np.empty(n, dtype=np.float64) slit_y = np.empty(n, dtype=np.float64) tau = 0.0 mu_x = 0.0 mu_y = 0.0 seeing = 1.5 slit_width = 0.2 slit_height = 10.0 slit_x, slit_y = slit_uniform_psf(n, seeing, mu_x, mu_y, tau, slit_width, slit_height) log.info("x range: [%s, %s]", slit_x.min(), slit_x.max()) log.info("y range: [%s, %s]", slit_y.min(), slit_y.max()) plt.scatter(slit_x, slit_y) plt.fill([-slit_width/2, slit_width/2, slit_width/2, -slit_width/2], [-slit_height/2, -slit_height/2, slit_height/2, slit_height/2], 'r', alpha=0.10, edgecolor='k') plt.title("Random uniform distribution") plt.show()
def homofire_dwind(): """Simulate fire on homogeneous field with constant wind which has a direction change with time.""" r_homo = [1] n = 1 r = 1 while r > .1: r = np.sqrt(n + 1) - np.sqrt(n) r_homo.append(r) n = n + 1 radius = np.array(r_homo).cumsum() pi = np.pi cos = np.cos sin = np.sin theta = np.linspace(0, 2 * pi, 100) a = 1.0 g = 1.0 f = 2.0 h = 1.0 t0 = 1.0 x0 = a * t0 * (f * cos(theta) + g) y0 = a * t0 * h * sin(theta) def xy(x0, y0, t): theta = np.linspace(0, 2 * pi, 100) beta = (pi / 6) * np.log(t) a = radius[t] / t g = 1.0 f = 2.0 h = 1.0 p = h * cos(beta) * cos(theta) + f * sin(beta) * sin(theta) q = h * sin(beta) * cos(theta) - f * cos(beta) * sin(theta) r = (p * p * f * f + q * q * h * h)**(-.5) x = x0 + a * t * (g * cos(beta) + r * (p * f * f * cos(beta) + q * h * h * sin(beta))) y = y0 + a * t * (g * sin(beta) + r * (p * f * f * sin(beta) - q * h * h * cos(beta))) return x, y for t in range(1, 20): if t == 1: plt.fill(x0, y0, 'r') plt.axis('square') plt.xlim(-8, 15) plt.ylim(-8, 15) else: x1, y1 = xy(x0, y0, t) x2, y2 = xy(x0, y0, t + 1) plt.fill(x2, y2, 'r') plt.fill(x1, y1, 'k') plt.axis('square') plt.xlim(-8, 15) plt.ylim(-8, 15) show_animation()
def hinton(W, maxWeight=None): reenable = False if P.isinteractive(): P.ioff() P.clf() height, width = W.shape if not maxWeight: maxWeight = 2**numpy.ceil(numpy.log(numpy.max(numpy.abs(W)))/numpy.log(2)) P.fill(numpy.array([0,width,width,0]),numpy.array([0,0,height,height]),'gray') P.axis('off') P.axis('equal') for x in xrange(width): for y in xrange(height): _x = x+1 _y = y+1 w = W[y,x] if w > maxWeight/2: _blob(_x - 0.5, height - _y + 0.5, min(1,w/maxWeight),'white') elif w <= maxWeight/2: _blob(_x - 0.5, height - _y + 0.5, min(1,w/maxWeight),'black') if reenable: P.ion() P.show()
def homofire_cwind(): """ Simulate fire on homogeneous field with constant wind. Black shows burned area, red shows burning area, and white shows unburned area. """ r_homo = [1] n = 1 r = 1 while r > .1: r = np.sqrt(n + 1) - np.sqrt(n) r_homo.append(r) n = n + 1 radius = np.array(r_homo).cumsum() def xy(t): theta = np.linspace(0, 2 * np.pi, 100) a = radius[t] / t g = 1.0 f = 2.0 h = 1.0 x = a * t * (f * np.cos(theta) + g) y = a * t * h * np.sin(theta) return x, y for t in range(1, 20): if t == 1: x1, y1 = xy(t) plt.fill(x1, y1, 'r') plt.axis('square') plt.xlim(-5, 15) plt.ylim(-5, 5) else: x1, y1 = xy(t) x2, y2 = xy(t + 1) plt.fill(x2, y2, 'r') plt.fill(x1, y1, 'k') plt.axis('square') plt.xlim(-5, 15) plt.ylim(-5, 5) show_animation()
# print len(points) vertices = range(len(points)) return points, vertices a = np.array([0, 0]) b = np.array([1, 0]) h = np.sqrt(3) / 2. c = np.array([0.5, h]) k = 2.5 #2.2 depth = 4 fig, ax = plt.subplots(1, figsize=(20, 20)) #40 # fig = plt.figure(figsize=(15,15)) plt.fill([-0.01, 0.42, 0.42, -0.01], [-0.01, -0.01, 0.38, 0.38], color='g', alpha=0.15) plt.plot([-0.01, 0.42], [-0.01, -0.01], color='g', lw=4) plt.plot([0.42, 0.42], [-0.01, 0.38], color='g', lw=4) plt.plot([0.42, -0.01], [0.38, 0.38], color='g', lw=4) plt.plot([-0.01, -0.01], [-0.01, 0.38], color='g', lw=4) plt.fill([0.58, 1.01, 1.01, 0.58], [-0.01, -0.01, 0.38, 0.38], color='b', alpha=0.15) plt.plot([0.58, 1.01], [-0.01, -0.01], color='b', lw=4) plt.plot([1.01, 1.01], [-0.01, 0.38], color='b', lw=4) plt.plot([1.01, 0.58], [0.38, 0.38], color='b', lw=4) plt.plot([0.58, 0.58], [-0.01, 0.38], color='b', lw=4) plt.fill([0.28, 0.72, 0.72, 0.28], [0.50, 0.50, 0.88, 0.88], color='r', alpha=0.15)
y_pred, 'r.', label=u'Prediction') plt.subplot(222) plt.plot(X_test[:, 1], y_test, 'b.', X_test[:, 1], y_pred, 'r.', label=u'Prediction') plt.fill(np.concatenate([X_test, X_test[::-1]]), np.concatenate( [y_pred - 1.9600 * sigma, (y_pred + 1.9600 * sigma)[::-1]]), alpha=.5, fc='grey', ec='None', label='95% confidence interval') plt.xlabel('$x$') plt.ylabel('$f(x)$') plt.ylim(-10, 20) plt.legend(loc='upper left') plt.show() plt.figure(1) plt.subplot(611) plt.plot(X[:, 0]) plt.subplot(612) plt.plot(X[:, 1]) plt.subplot(613)
def sidereal_solar(): # set the semi-major axis and eccentricity a = 1.0 e = 0.0 ss = ssi.SolarSystem() ss.add_planet(a, e, loc="perihelion") # compute the period of the orbit from Kepler's law and ... P_orbital = ss.period(0) # ... set the rotation period P_rotation = 0.5 * P_orbital omega = 2 * math.pi / P_rotation # integrate nsteps_per_year = 720 num_years = 2 sol = ss.integrate(nsteps_per_year, num_years) # ================================================================ # plotting # ================================================================ for n in range(len(sol[0].t)): plt.clf() # plot the foci plt.scatter([0], [0], s=250, marker=(5, 1), color="k") plt.scatter([0], [0], s=200, marker=(5, 1), color="y") # plot the orbit plt.plot(sol[0].x, sol[0].y, color="0.5", ls="--") # plot planet theta = np.radians(np.arange(360)) r = 0.05 # exaggerate the planet's size x_surface = sol[0].x[n] + r * np.cos(theta) y_surface = sol[0].y[n] + r * np.sin(theta) plt.fill(x_surface, y_surface, "c", edgecolor="c", zorder=100) # plot a point on the planet's surface xpt = sol[0].x[n] + r * np.cos(omega * sol[0].t[n] + math.pi / 2.0) ypt = sol[0].y[n] + r * np.sin(omega * sol[0].t[n] + math.pi / 2.0) plt.scatter([xpt], [ypt], s=25, color="k", zorder=100) plt.axis([-1.2, 1.2, -1.2, 1.2]) ax = plt.gca() ax.set_aspect("equal", "datalim") plt.subplots_adjust(left=0.05, right=0.98, bottom=0.05, top=0.98) f = plt.gcf() f.set_size_inches(7.2, 7.2) plt.axis("off") plt.savefig("sidereal_solar_{:04d}.png".format(n))
offset7 = offset + da carpet(da_m, dac_m, dc_m, d_m, iterations - 1, offset7) # 8 ad_m = np.array([0, 0]) abd_m = abd - ad dac_m = dac - ad da_m = da - ad offset8 = offset + ad carpet(ad_m, abd_m, dac_m, da_m, iterations - 1, offset8) a = np.array([0, 0]) b = np.array([3, 0]) c = np.array([3, 3]) d = np.array([0, 3]) iterations = 4 plt.figure(figsize=(20, 20)) plt.fill([a[0], b[0], c[0], d[0]], [a[1], b[1], c[1], d[1]], color="maroon", alpha=0.8) plt.hold(True) carpet(a, b, c, d, iterations) plt.title("Randomly Colored Sierpinski Carpet (iterations = 4)") plt.axis("equal") plt.axis("off") plt.show()
def carpet(a, b, c, d, iterations, offset=np.array([0, 0])): ab = (a + b) / 3.0 ba = 2 * (a + b) / 3.0 bc = (2 * b + c) / 3.0 cb = (b + 2 * c) / 3.0 dc = (c + 2 * d) / 3.0 cd = (2 * c + d) / 3.0 ad = (d + a) / 3.0 da = 2 * (d + a) / 3.0 abd = 2 * a / 3.0 + (b + d) / 3.0 bac = a + (2 * b + d) / 3.0 cbd = 4 * a / 3.0 + 2 * (b + d) / 3.0 dac = a + (b + 2 * d) / 3.0 x = (random.random(), random.random(), random.random()) plt.fill( [abd[0] + offset[0], bac[0] + offset[0], cbd[0] + offset[0], dac[0] + offset[0]], [abd[1] + offset[1], bac[1] + offset[1], cbd[1] + offset[1], dac[1] + offset[1]], color=x, alpha=0.9, ) plt.hold(True) if iterations == 0: plt.fill( [abd[0] + offset[0], bac[0] + offset[0], cbd[0] + offset[0], dac[0] + offset[0]], [abd[1] + offset[1], bac[1] + offset[1], cbd[1] + offset[1], dac[1] + offset[1]], color=x, alpha=0.9, ) plt.hold(True) else: # 1 a_m = np.array([0, 0]) ab_m = ab - a abd_m = abd - a ad_m = ad - a offset1 = offset + a carpet(a_m, ab_m, abd_m, ad_m, iterations - 1, offset1) # 2 ab_m = np.array([0, 0]) ba_m = ba - ab bac_m = bac - ab abd_m = abd - ab offset2 = offset + ab carpet(ab_m, ba_m, bac_m, abd_m, iterations - 1, offset2) # 3 ba_m = np.array([0, 0]) b_m = b - ba bc_m = bc - ba bac_m = bac - ba offset3 = offset + ba carpet(ba_m, b_m, bc_m, bac_m, iterations - 1, offset3) # 4 bac_m = np.array([0, 0]) bc_m = bc - bac cb_m = cb - bac cbd_m = cbd - bac offset4 = offset + bac carpet(bac_m, bc_m, cb_m, cbd_m, iterations - 1, offset4) # 5 cbd_m = np.array([0, 0]) cb_m = cb - cbd c_m = c - cbd cd_m = cd - cbd offset5 = offset + cbd carpet(cbd_m, cb_m, c_m, cd_m, iterations - 1, offset5) # 6 dac_m = np.array([0, 0]) cbd_m = cbd - dac cd_m = cd - dac dc_m = dc - dac offset6 = offset + dac carpet(dac_m, cbd_m, cd_m, dc_m, iterations - 1, offset6) # 7 da_m = np.array([0, 0]) dac_m = dac - da dc_m = dc - da d_m = d - da offset7 = offset + da carpet(da_m, dac_m, dc_m, d_m, iterations - 1, offset7) # 8 ad_m = np.array([0, 0]) abd_m = abd - ad dac_m = dac - ad da_m = da - ad offset8 = offset + ad carpet(ad_m, abd_m, dac_m, da_m, iterations - 1, offset8)
def domains(method="FTCS"): # grid info xl = 0.0 xc = 1.0 xr = 2.0 dx = xr - xc t0 = 0.0 t1 = 1.0 dt = t1 - t0 C = 0.6 xp = xc - C*dx plt.clf() # plot a square representing [x, x+dx] x [t, t+dt] # x-axis plt.arrow(0, 0, 2.5*dx, 0, shape="full", head_width=0.04, head_length=0.06, lw=1, width=0.005, facecolor="k", length_includes_head=True, zorder=100) plt.text(2.55*dx, 0, r"$x$", fontsize=16, verticalalignment="center") # x points labeled for p, l in [((xc, 0), r"$x_i$"), ((xl, 0), r"$x_{i-1}$"), ((xr, 0), r"$x_{i+1}$")]: plt.text(p[0], p[1]-0.07, l, fontsize=16, horizontalalignment="center", verticalalignment="top") plt.plot([p[0], p[0]], [p[1], p[1]-0.04], color="k") plt.text(xp, -0.07, r"$x_i - C \Delta x$", fontsize=16, horizontalalignment="center", verticalalignment="top") plt.plot([xp, xp], [0, -0.04], color="k") # points plt.scatter([xl, xc, xr, xc], [0, 0, 0, dt], color="C3", marker="o", s=40, zorder=1000, alpha=1.0) # data points eps = 0.02*dx for p, l in [((xl, 0), r"$a_{i-1}^n$"), ((xc, 0), r"$a_{i}^n$"), ((xr, 0), r"$a_{i+1}^n$"), ((xc, dt), r"$a_{i}^{n+1}$")]: plt.text(p[0]+eps, p[1]+eps, l, horizontalalignment="left", verticalalignment="bottom", fontsize=16, color="C3", zorder=1000) # time axis plt.arrow(0, 0, 0, 1.3*dt, shape="full", head_width=0.04, head_length=0.06, lw=1, width=0.005, facecolor="k", length_includes_head=True, zorder=100) plt.text(0, 1.35*dt, r"$t$", fontsize=16, horizontalalignment="center") plt.text(-0.25, dt, r"$t^{n+1}$", fontsize=16) plt.plot([-0.04, 0], [dt, dt], color="k") plt.text(-0.25, 0, r"$t^n$", fontsize=16) plt.plot([-0.04, 0], [0, 0], color="k") plt.plot([0, 2.0*dx], [dt, dt], ls=":", color="0.5") plt.plot([dx, dx], [0, dt], ls=":", color="0.5") plt.plot([2.0*dx, 2.0*dx], [0, dt], ls=":", color="0.5") # domain of dependence if method == "upwind": plt.fill([0, xc, xc, 0], [0, dt, 0, 0], color="C0", lw=2, alpha=0.5) elif method == "FTCS": plt.fill([0, xc, xr, 0], [0, dt, 0, 0], color="C0", lw=2, alpha=0.5) elif method == "downwind": plt.fill([xc, xc, xr, 0], [0, dt, 0, 0], color="C0", lw=2, alpha=0.5) # true domain of dependence plt.fill([xp, xc, xc, 0], [0, dt, 0, 0], color="C1", lw=2, alpha=0.5) # label plt.text(xr+0.1*dx, 0.5*dt, method, fontsize=16, horizontalalignment="left") plt.axis("off") plt.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95) plt.xlim(-0.4,2.8*dx) plt.ylim(-0.1,1.4*dx) f = plt.gcf() f.set_size_inches(9.0,5.0) plt.tight_layout() plt.savefig("domains_{}.pdf".format(method), bbox_inches="tight")
def doit(): # set the semi-major axis and eccentricity a = 1.0*d e = 0.0 # compute the period of the orbit from Kepler's law and make # the timestep by 1/720th of a period P_orbital = math.sqrt(4*math.pi*math.pi*a**3/(G*M_E)) # set the rotation period P_rotation = P_orbital omega = 2*math.pi/P_rotation # set the initial coordinates -- perihelion x_init = 0.0 y_init = -a*(1.0 - e) # set the initial velocity vx_init = math.sqrt( (G*M_E/a) * (1 + e) / (1 - e)) vy_init = 0.0 # the circular orbit will be our baseline orbit = trajectory() print "period = ", P_orbital/day dt = P_orbital/720.0 tmax = 2*P_orbital orbit.integrate(x_init, y_init, vx_init, vy_init, dt, tmax) # plotting for n in range(orbit.npts): plt.clf() # plot the Earth plt.scatter([0], [0], s=650, color="k") plt.scatter([0], [0], s=600, color="b") # plot the orbit plt.plot(orbit.x[0:orbit.npts], orbit.y[0:orbit.npts], color="0.5", ls=":", lw=2) # plot moon (use zorder to put this on top of the orbit line) theta = np.arange(180) r = 0.05*d # exaggerate the moon's size x_surface = orbit.x[n] + r*np.cos(theta) y_surface = orbit.y[n] + r*np.sin(theta) plt.fill(x_surface,y_surface,"0.75", edgecolor="0.75", alpha=1.0, zorder=1000) # plot a point on the moon's surface xpt = orbit.x[n] + r*np.cos(omega*orbit.t[n]+math.pi/2.0) ypt = orbit.y[n] + r*np.sin(omega*orbit.t[n]+math.pi/2.0) plt.scatter([xpt],[ypt],s=25,color="k") plt.axis([-1.1*d,1.1*d,-1.1*d,1.1*d]) plt.axis("off") plt.subplots_adjust(left=0.05,right=0.95,bottom=0.05,top=0.95) ax = plt.gca() ax.set_aspect("equal", "datalim") f = plt.gcf() f.set_size_inches(7.2,7.2) plt.savefig("moon_rotation_%04d.png" % n)
c = np.array([0.5, h]) iterations = 7 points1 = koch(a=np.array([0, 0]), b=np.array([1, 0]), iterations=iterations) points2 = koch(a=np.array([1, 0]), b=np.array([0.5, -h]), iterations=iterations) points3 = koch(a=np.array([0.5, -h]), b=np.array([0, 0]), iterations=iterations) points = [] for i in range(len(points1)): points.append(np.array(points1[i])) for i in range(len(points2)): points.append(np.array(points2[i])) for i in range(len(points3)): points.append(np.array(points3[i])) ptsx = [] ptsy = [] for i in range(len(points)): ptsx.append(points[i][0]) ptsy.append(points[i][1]) plt.figure(figsize=(25, 25)) plt.title("Koch Triangle (iterations = 7)") plt.plot(ptsx, ptsy, "-") plt.fill(ptsx, ptsy, color="lightcyan", alpha=0.7) plt.axis("equal") plt.axis("off") plt.show()
# Specify optimization method (single run "Minimize" by default) # @SEE doc_optimization for documentation of optimization methods model.setOptimizer("Minimize", num_restarts=nItr) # Instead of fit(), which only fits data using given hyperparameters, # optimize() will optimize hyperparamters based on marginal likelihood # the deafult mean will be adapted to the average value of the training labels.. # ..if you do not specify mean function by your own. model.optimize(x, y) model.plotData_1d() print 'Optimized negative log marginal likelihood:', round(model.nlZ,3) # Predict test data # output mean(ymu)/variance(ys2), latent mean(fmu)/variance(fs2), and log predictive probabilities(lp) ym, ys2, fmu, fs2, lp = model.predict(xt) # Plot the stuff plt.plot(x, y, 'b', label=u'Training Data') plt.plot(xt, yt, 'k', label=u'Test Data') plt.plot(xt, ym, 'r', label=u'SM Prediction') fillx = np.concatenate([np.array(xt.ravel()).ravel(), np.array(xt.ravel()).ravel()[::-1]]) filly = np.concatenate([(np.array(ym.ravel()).ravel() - 1.9600 * np.array(ys2.ravel()).ravel()), (np.array(ym.ravel()).ravel() + 1.9600 * np.array(ys2.ravel()).ravel())[::-1]]) plt.fill(fillx, filly, alpha=.5, fc='0.5', ec='None', label='95% confidence interval') plt.show()
def show_align(args): fname_corpus_f = args.fpath fname_corpus_e = args.epath fname_alignment = args.align sent_id = args.sent_id with open(fname_corpus_f) as fp_f, open(fname_corpus_e) as fp_e, open(fname_alignment) as fp_a: for _ in range(sent_id): toks_f = next(fp_f).decode('UTF-8') toks_e = next(fp_e).decode('UTF-8') alignment = next(fp_a) toks_f = toks_f.split() toks_e = toks_e.split() alignment = [tuple(int(aa) for aa in a.split('-')) for a in alignment.split()] trace('[f] = ' + ' '.join(toks_f)) trace('[e] = ' + ' '.join(toks_e)) trace('[a] = ' + ' '.join(str(x[0]) + '_' + str(x[1]) for x in alignment)) lf = len(toks_f) le = len(toks_e) mwf = max(len(w) for w in toks_f) mwe = max(len(w) for w in toks_e) UNIT = 0.3 # inch PADDING = 0.5 # coord COLOR_LINE1 = '#000000' COLOR_LINE2 = '#882222' COLOR_LINE3 = '#77aa88' COLOR_LINE4 = '#333333' COLOR_FILL = '#3355bb' fontsize = 72.0 * UNIT * 0.8 trace('fontsize = %f' % fontsize) WIDTH = max(6.4, UNIT * (lf+mwf+1)) HEIGHT = max(4.8, UNIT * (le+mwe+1)) plt.figure(figsize=(WIDTH, HEIGHT)) ax = plt.gca() plt.xticks([]) plt.yticks([]) ax.spines['left'].set_color('none') ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.spines['bottom'].set_color('none') plt.subplots_adjust(left=0.02, right=0.98, top=0.98, bottom=0.02) plt.axis([-mwf, lf, 0, le+mwe]) plt.axis('equal') plt.fill( \ [-mwf-PADDING, lf+PADDING, lf+PADDING, -mwf-PADDING], \ [-PADDING, -PADDING, le+mwe+PADDING, le+mwe+PADDING], \ facecolor='#ffffff', edgecolor='none', zorder=-1) def getstyle(x): if x % 5: return COLOR_LINE3, ':' else: return COLOR_LINE2, ':' # texts for x, wf in enumerate(toks_f): plt.text(x+0.5, le+0.5, wf, fontsize=fontsize, rotation='vertical', horizontalalignment='center', verticalalignment='bottom', zorder=0) for y, we in enumerate(toks_e): yy = le-y-1 plt.text(-0.5, yy+0.5, we, fontsize=fontsize, horizontalalignment='right', verticalalignment='center', zorder=0) # borders for x in range(1, lf): color, linestyle = getstyle(x) plt.plot([x, x], [0, le], color=color, linestyle=linestyle, zorder=1) for y in range(1, le): yy = le-y color, linestyle = getstyle(y) plt.plot([0, lf], [yy, yy], color=color, linestyle=linestyle, zorder=1) plt.plot([0, 0], [0, le], COLOR_LINE1, zorder=3) plt.plot([lf, lf], [0, le], COLOR_LINE1, zorder=3) plt.plot([0, lf], [0, 0], COLOR_LINE1, zorder=3) plt.plot([0, lf], [le, le], COLOR_LINE1, zorder=3) # boxes for af, ae in alignment: yy=le-ae-1 X = [af, af+1, af+1, af] Y = [yy, yy, yy+1, yy+1] plt.fill(X, Y, facecolor=COLOR_FILL, edgecolor=COLOR_LINE4, zorder=2) plt.show()
def draw_shapes(shape, c, **kwargs): if hasattr(shape, "exterior"): shape = shape.exterior a = plt.asarray(shape) return plt.fill(a[:, 0], a[:, 1], fc=c, **kwargs)[0]
def _blob(x,y,area,color): hs = numpy.sqrt(area) / 2 xcorners = numpy.array([x - hs, x + hs, x + hs, x - hs]) ycorners = numpy.array([y - hs, y - hs, y + hs, y + hs]) P.fill(xcorners, ycorners, color, edgecolor=color)
f_w = stddeverr(fs) s_w = stddeverr(ss) failure_lines[r] = failure_lines.get(r,[]) + [(n,f,f_w)] stretch_lines[r] = stretch_lines.get(r,[]) + [(n,s,s_w)] x = numpy.linspace(1,17000,200) y = numpy.log(x) pl.plot(x,y,color='black',label='ln(N)',linewidth=3) for r,line in sorted(stretch_lines.items()): line.sort() xs,ys,yws = zip(*line) xps,yps = pl.mlab.poly_between(xs, [y+yw for y,yw in zip(ys,yws)], [y-yw for y,yw in zip(ys,yws)]) pl.fill(xps, yps, alpha=0.4) pl.plot(xs, ys, '.-', label="%d"%r) print (xs) print (ys) print (yws) print () pl.xlim((10, 17000)) pl.title('Route stretch for different number of random remotes in Watts-Strogatz graphs.\n3 neighbors. Number ofhops used as routing metric.') pl.ylabel('Route stretch') pl.xlabel('Number of nodes') pl.legend() # pl.xscale('log',basex=2) pl.show()
points.extend(koch(c1,c2,m1,m2,iteration-1)) points.extend(koch(m1,m2,d1,d2,iteration-1)) points.extend(koch(d1,d2,b1,b2,iteration-1)) return points points = koch(a1=0,a2=0,b1=1,b2=0,iteration=5) points1 = koch(a1=1,a2=0,b1=0.5,b2=-np.sqrt(3)/2.,iteration=5) points2 = koch(a1=0.5,a2=-np.sqrt(3)/2.,b1=0,b2=0,iteration=5) Points = [] for i in range(len(points)): Points.append(np.array(points[i])) for i in range(len(points1)): Points.append(np.array(points1[i])) for i in range(len(points2)): Points.append(np.array(points2[i])) plt.plot([p[0] for p in Points], [p[1] for p in Points], 'purple') plt.fill([p[0] for p in Points], [p[1] for p in Points], 'purple') ####################################### points3 = koch(a1=2,a2=0,b1=3,b2=0,iteration=5) points4 = koch(a1=3,a2=0,b1=2.5,b2=-np.sqrt(3)/2.,iteration=5) points5 = koch(a1=2.5,a2=-np.sqrt(3)/2.,b1=2,b2=0,iteration=5) Points2 = [] for i in range(len(points3)): Points2.append(np.array(points3[i])) for i in range(len(points4)): Points2.append(np.array(points4[i])) for i in range(len(points5)): Points2.append(np.array(points5[i])) plt.plot([p[0] for p in Points2], [p[1] for p in Points2], 'blue') plt.fill([p[0] for p in Points2], [p[1] for p in Points2], 'blue')
points.extend(SierpinskiCantorGraph(c,ca,cb,k, depth-1)) plt.plot([ab[0],ba[0]], [ab[1],ba[1]], '-', color='k') plt.plot([bc[0],cb[0]], [bc[1],cb[1]], '-', color='k') plt.plot([ac[0],ca[0]], [ac[1],ca[1]], '-', color='k') vertices = range(len(points)) return points, vertices a = np.array([0, 0]) b = np.array([1, 0]) h = np.sqrt(3)/2. c = np.array([0.5, h]) k=2.5 #k should be between 2 and 2.5 depth=4 fig, ax = plt.subplots(1,figsize=(40,40)) plt.fill([-0.01,0.42,0.42,-0.01],[-0.01,-0.01,0.38,0.38],color='g',alpha=0.15) plt.plot([-0.01,0.42],[-0.01,-0.01],color='g',lw=4) plt.plot([0.42,0.42],[-0.01,0.38],color='g',lw=4) plt.plot([0.42,-0.01],[0.38,0.38],color='g',lw=4) plt.plot([-0.01,-0.01],[-0.01,0.38],color='g',lw=4) plt.fill([0.58,1.01,1.01,0.58],[-0.01,-0.01,0.38,0.38],color='b',alpha=0.15) plt.plot([0.58,1.01],[-0.01,-0.01],color='b',lw=4) plt.plot([1.01,1.01],[-0.01,0.38],color='b',lw=4) plt.plot([1.01,0.58],[0.38,0.38],color='b',lw=4) plt.plot([0.58,0.58],[-0.01,0.38],color='b',lw=4) plt.fill([0.28,0.72,0.72,0.28],[0.50,0.50,0.88,0.88],color='r',alpha=0.15) plt.plot([0.28,0.72],[0.50,0.50],color='r',lw=4) plt.plot([0.72,0.72],[0.50,0.88],color='r',lw=4) plt.plot([0.72,0.28],[0.88,0.88],color='r',lw=4) plt.plot([0.28,0.28],[0.88,0.50],color='r',lw=4) points,vertices=SierpinskiCantorGraph(a,b,c,k,depth)