def kplot(kdata, new=True, axes=None, colorup='r', colordown='g', width=0.6, alpha=1.0): """绘制K线图 :param KData kdata: K线数据 :param bool new: 是否在新窗口中显示,只在没有指定axes时生效 :param axes: 指定的坐标轴 :param colorup: the color of the rectangle where close >= open :param colordown: the color of the rectangle where close < open :param width: fraction of a day for the rectangle width :param alpha: the rectangle alpha level, 透明度(0.0~1.0) 1.0为不透明 """ if not kdata: print("kdata is None") return if not axes: axes = create_figure() if new else gca() OFFSET = width/2.0 rfcolor = matplotlib.rcParams['axes.facecolor'] for i in range(len(kdata)): record = kdata[i] open, high, low, close = record.openPrice, record.highPrice, record.lowPrice, record.closePrice if close>=open: color = colorup lower = open height = close-open rect = Rectangle(xy=(i-OFFSET, lower), width=width, height=height, facecolor=rfcolor, edgecolor=color) else: color = colordown lower = close height = open-close rect = Rectangle(xy=(i-OFFSET, lower), width=width, height=height, facecolor=color, edgecolor=color) vline1 = Line2D(xdata=(i, i), ydata=(low, lower), color=color, linewidth=0.5, antialiased=True) vline2 = Line2D(xdata=(i, i), ydata=(lower+height, high), color=color, linewidth=0.5, antialiased=True) rect.set_alpha(alpha) axes.add_line(vline1) axes.add_line(vline2) axes.add_patch(rect) title = get_draw_title(kdata) axes.set_title(title) last_record = kdata[-1] color = 'r' if last_record.closePrice>kdata[-2].closePrice else 'g' text = u'%s 开:%.2f 高:%.2f 低:%.2f 收:%.2f 涨幅:%.2f%%' % ( last_record.datetime.number/10000, last_record.openPrice, last_record.highPrice, last_record.lowPrice, last_record.closePrice, 100*(last_record.closePrice-kdata[-2].closePrice)/kdata[-2].closePrice) axes.text(0.99,0.97, text, horizontalalignment='right', verticalalignment='top', transform=axes.transAxes, color=color) axes.autoscale_view() axes.set_xlim(-1, len(kdata)+1) ax_set_locator_formatter(axes, kdata.getDatetimeList(), kdata.getQuery().kType)
def outline(ax, **kw): a = ax.axis() rec = Rectangle((a[0] - 0.7, a[2] - 0.2), (a[1] - a[0]) + 1, (a[3] - a[2]) + 0.4, fill=False, lw=2, **kw) rec = ax.add_patch(rec) rec.set_clip_on(False)
def __call__(self, inputs): from pylab import Rectangle c = Rectangle((self.get_input('x'), self.get_input('y')), self.get_input('width'), self.get_input('height'), **self.get_input('patch')) return c
def drawPlot(self): ion() fig = figure(1) # draw cart axes = fig.add_subplot(111, aspect='equal') self.box = Rectangle(xy=(self.pos - self.cartwidth / 2.0, -self.cartheight), width=self.cartwidth, height=self.cartheight) axes.add_artist(self.box) self.box.set_clip_box(axes.bbox) # draw pole self.pole = Line2D([self.pos, self.pos + sin(self.angle)], [0, cos(self.angle)], linewidth=3, color='black') axes.add_artist(self.pole) self.pole.set_clip_box(axes.bbox) # set axes limits axes.set_xlim(-2.5, 2.5) axes.set_ylim(-0.5, 2)
def pca_stages(channel): fig, axes = plt.subplots() fig.suptitle(channel, fontweight='bold') spectra, frequency = load_spectrum(channel) flat = np.concatenate( [spectra['N1'], spectra['N2'], spectra['N3'], spectra['rem']], axis=0) n1 = ['royalblue' for i in spectra['N1'][:, 0]] n2 = ['forestgreen' for i in spectra['N2'][:, 0]] n3 = ['coral' for i in spectra['N3'][:, 0]] rem = ['plum' for i in spectra['rem'][:, 0]] color = list(itertools.chain.from_iterable([n1, n2, n3, rem])) sklearn_pca = sklearnPCA(n_components=2) pcs = sklearn_pca.fit_transform(flat) y = axes.scatter(pcs[:, 0], pcs[:, 1], c=color, alpha=0.7, s=40, edgecolors='w') axes.annotate(sklearn_pca.explained_variance_ratio_, xy=(1.0, 1.0), xycoords='axes fraction', horizontalalignment='right', verticalalignment='top') raise_window() axes.set_xlabel('1st component') axes.set_ylabel('2nd component') # plt.legend() # make the legend p1 = Rectangle((0, 0), 1, 1, fc="royalblue") p2 = Rectangle((0, 0), 1, 1, fc="forestgreen") p3 = Rectangle((0, 0), 1, 1, fc="coral") p4 = Rectangle((0, 0), 1, 1, fc="plum") plt.legend((p1, p2, p3, p4), ('N1', 'N2', 'N3', 'rem')) fig.savefig('figures/pca/' + channel + '_pca.pdf')
def print_mediatrix_Object_circle_graph_old(mediatrix_data,image_dir='', keydots=False, colors= {'object': "g", 'vector': "b", 'keydots': "k"}, mediatrix_vectors=False, save=True, save_dir=''): """ Make a plot presenting the object, keydots and mediatrix vectors. Input: - mediatrix_data <list> : the output from mediatrix_decomposition. - image_dir <str> : the image directory. If it is on the same directory directory=''. - keydots <bool> : 'True' if you want to display the keydots and 'False' if you do not. - colors <dic> : set the plot colors. The possible keys are 'object', 'vector' and 'keydots'. Output: <bool> """ image_name=mediatrix_data['id'] image,hdr = getdata(image_dir+image_name, header = True ) pixels=where(image>0) A = subplot(111) for i in range (0,len(pixels[0])): xy=[pixels[1][i]-0.5,pixels[0][i]-0.5] rec=Rectangle(xy, 1, 1, ec=colors['object'], fc=colors['object'], zorder=100) A.add_patch(rec) #A.scatter(pixels[1], pixels[0], s=200, c='b', marker='s', edgecolors='none') #A.plot(pixels[1],pixels[0],colors['object']) Length=0 for i in range(0,len(mediatrix_data['origin'])): origin_x=mediatrix_data['origin'][i][0] origin_y=mediatrix_data['origin'][i][1] end_x=mediatrix_data['end'][i][0] end_y=mediatrix_data['end'][i][1] Length_aux=(origin_x - end_x)**2 + (origin_y - end_y)**2 Length=Length+ sqrt(Length_aux) if mediatrix_vectors==True: d_x= end_x - origin_x d_y= mediatrix_data['end'][i][1] - mediatrix_data['origin'][i][1] arr = Arrow(origin_y, origin_x, d_y, d_x, width=0.05*Length, fc=colors['vector'], ec='none',zorder=1000) A.add_patch(arr) if keydots==True: E1,E2=get_extrema_2loops(pixels[0], pixels[1], 0 ) Area=len(pixels[1]) p1=[pixels[0][E1],pixels[1][E1]] # the extreme points p_1 and p_2 p2=[pixels[0][E2],pixels[1][E2]] keydots=[p1,p2] keydots=find_keydots(p1,p2,pixels,image,keydots,Area, method="brightest",alpha=1) keyX=[] keyY=[] for j in range(0,len(keydots)): keyX.append(keydots[j][0]) keyY.append(keydots[j][1]) A.plot(keyY,keyX,colors['keydots']+'.',zorder=500)
def drawPlot(self): ion() self.fig = plt.figure() # draw cart self.axes = self.fig.add_subplot(111, aspect='equal') self.box = Rectangle(xy=(self.cart_location - self.cartwidth / 2.0, -self.cartheight), width=self.cartwidth, height=self.cartheight) self.axes.add_artist(self.box) self.box.set_clip_box(self.axes.bbox) # draw pole self.pole = Line2D( [self.cart_location, self.cart_location + np.sin(self.pole_angle)], [0, np.cos(self.pole_angle)], linewidth=3, color='black') self.axes.add_artist(self.pole) self.pole.set_clip_box(self.axes.bbox) # set axes limits self.axes.set_xlim(-10, 10) self.axes.set_ylim(-0.5, 2)
def draw_rectangle(self, x, y, width, height, fg_color="CornflowerBlue", edge_color="gray"): self.axes.add_patch( Rectangle((x, y), width, height, ec=edge_color, fc=fg_color, alpha=0.5, zorder=10)) self.update_figure()
def drawPlot(self): ion() fig = figure(1) # draw cart axes = fig.add_subplot(111, aspect='equal') self.box = Rectangle(xy=(self.pos-self.cartwidth/2.0, -self.cartheight), width=self.cartwidth, height=self.cartheight) axes.add_artist(self.box) self.box.set_clip_box(axes.bbox) # draw pole self.pole = Line2D([self.pos, self.pos + sin(self.angle)], [0, cos(self.angle)], linewidth=3, color='black') axes.add_artist(self.pole) self.pole.set_clip_box(axes.bbox) # set axes limits axes.set_xlim(-2.5, 2.5) axes.set_ylim(-0.5, 2)
result = model.run_point(points=points, force_no_debug=True) model.writepoint(result) elif case == 3: model = model_puff_corea(testsrc, met) result = model.run_point(points=[(500,20.0,1.0)], force_no_debug=True) model1 = model_puff_core(ReleaseQ1, MetField, MetSeq) result1 = model1.run_point(points=[(500,20.0,1.0)], force_no_debug=True) from pylab import plot, xlabel, ylabel, grid, show, Rectangle, legend x = result.values()[0].keys() y1 = result.values()[0].values() y2 = result1.values()[0].values() plot(x,y1,'go-') plot(x,y2,'bo--') xlabel(u"时间刻度(10s)") ylabel(u"浓度(mg/m3)") p1 = Rectangle((0, 0), 1, 1, fc="g") p2 = Rectangle((0, 0), 1, 1, fc="b") legend([p1, p2], [u"真实源", u"反算源"]) show() logger.info("endtime=%s" % str(datetime.now())) print "duration=%s" % str(datetime.now() - starttime) print "Program End Normally" import logging logger = logging.getLogger('Main') logger.setLevel(global_settings.LOGLEVEL) ch = logging.StreamHandler(sys.stderr) ch.setFormatter(logging.Formatter(global_settings.LOGFORMAT)) logger.addHandler(ch)
def kplot(kdata, new=True, axes=None, colorup='r', colordown='g', width=0.6, alpha=1.0): """绘制K线图 :param KData kdata: K线数据 :param bool new: 是否在新窗口中显示,只在没有指定axes时生效 :param axes: 指定的坐标轴 :param colorup: the color of the rectangle where close >= open :param colordown: the color of the rectangle where close < open :param width: fraction of a day for the rectangle width :param alpha: the rectangle alpha level, 透明度(0.0~1.0) 1.0为不透明 """ if not kdata: print("kdata is None") return if not axes: axes = create_figure() if new else gca() OFFSET = width / 2.0 rfcolor = matplotlib.rcParams['axes.facecolor'] for i in range(len(kdata)): record = kdata[i] open, high, low, close = record.open, record.high, record.low, record.close if close >= open: color = colorup lower = open height = close - open rect = Rectangle( xy=(i - OFFSET, lower), width=width, height=height, facecolor=rfcolor, edgecolor=color ) else: color = colordown lower = close height = open - close rect = Rectangle( xy=(i - OFFSET, lower), width=width, height=height, facecolor=color, edgecolor=color ) vline1 = Line2D( xdata=(i, i), ydata=(low, lower), color=color, linewidth=0.5, antialiased=True ) vline2 = Line2D( xdata=(i, i), ydata=(lower + height, high), color=color, linewidth=0.5, antialiased=True ) rect.set_alpha(alpha) axes.add_line(vline1) axes.add_line(vline2) axes.add_patch(rect) title = get_draw_title(kdata) axes.set_title(title) last_record = kdata[-1] color = 'r' if last_record.close > kdata[-2].close else 'g' text = u'%s 开:%.2f 高:%.2f 低:%.2f 收:%.2f 涨幅:%.2f%%' % ( last_record.date.number / 10000, last_record.open, last_record.high, last_record.low, last_record.close, 100 * (last_record.close - kdata[-2].close) / kdata[-2].close ) axes.text( 0.99, 0.97, text, horizontalalignment='right', verticalalignment='top', transform=axes.transAxes, color=color ) axes.autoscale_view() axes.set_xlim(-1, len(kdata) + 1) ax_set_locator_formatter(axes, kdata.get_date_list(), kdata.get_query().ktype)
class CartPoleRenderer(Renderer): def __init__(self): Renderer.__init__(self) self.dataLock = threading.Lock() self.angle = 0.0 self.angle_vel = 0.0 self.pos = 0.0 self.pos_vel = 0.0 self.stopRequest = False # some drawing constants self.cartheight = 0.2 self.cartwidth = 1.0 self.polelength = 0.5 self.plotlimits = [-4, 4, -0.5, 3] self.box = None self.pole = None def updateData(self, data): self.dataLock.acquire() (self.angle, self.angle_vel, self.pos, self.pos_vel) = data self.dataLock.release() def stop(self): self.stopRequest = True def start(self): self.drawPlot() Renderer.start(self) def drawPlot(self): ion() fig = figure(1) # draw cart axes = fig.add_subplot(111, aspect='equal') self.box = Rectangle(xy=(self.pos-self.cartwidth/2.0, -self.cartheight), width=self.cartwidth, height=self.cartheight) axes.add_artist(self.box) self.box.set_clip_box(axes.bbox) # draw pole self.pole = Line2D([self.pos, self.pos + sin(self.angle)], [0, cos(self.angle)], linewidth=3, color='black') axes.add_artist(self.pole) self.pole.set_clip_box(axes.bbox) # set axes limits axes.set_xlim(-2.5, 2.5) axes.set_ylim(-0.5, 2) def _render(self): while not self.stopRequest: if self.angle < 0.05 and abs(self.pos) < 0.05: self.box.set_facecolor('green') else: self.box.set_facecolor('blue') self.box.set_x(self.pos - self.cartwidth/2.0) self.pole.set_xdata([self.pos, self.pos + self.polelength * sin(self.angle)]) self.pole.set_ydata([0, self.polelength * cos(self.angle)]) draw() time.sleep(0.05) self.stopRequest = False
pylab.xlabel('x position (um)') pylab.ylabel('y position (um)') pylab.grid(False) # Draw pixels # NOTE: Rectangle((x,y), width, height, angle=0.0, **kwargs); where (x,y) is lower left corner currentAxis = pylab.gca() for i in range(0, NCOLUMNS): for j in range(0, NROWS): xEdge = -NROWS * PIXELWIDTH / 2 + j * PIXELWIDTH yEdge = -NCOLUMNS * PIXELWIDTH / 2 + i * PIXELWIDTH currentAxis.add_patch( Rectangle((xEdge, yEdge), PIXELWIDTH, PIXELWIDTH, facecolor='blue', alpha=0.10)) currentAxis.annotate( str(int(pixelCountArray[i * NCOLUMNS + j])), (xEdge + PIXELWIDTH / 2, yEdge + PIXELWIDTH / 2), color='black', weight='normal', fontsize=12, ha='center', va='center') # Set the Display Region pylab.xlim([-NROWS * PIXELWIDTH / 2, NROWS * PIXELWIDTH / 2]) pylab.ylim([-NCOLUMNS * PIXELWIDTH / 2, NCOLUMNS * PIXELWIDTH / 2]) pylab.show()
def plot_mediatrix_circle(mediatrix_data,ps_name, keydots=False, colors= {'object': "g", 'vector': "b", 'keydots': "k"}, mediatrix_vectors=False, save=True, plot_title="Mediatrix Plot", out_image=""): """ Make a plot presenting the object, keydots and mediatrix vectors. Input: - mediatrix_data <list> : the output from mediatrix_decomposition. - image_dir <str> : the image directory. If it is on the same directory directory=''. - keydots <bool> : 'True' if you want to display the keydots and 'False' if you do not. - colors <dic> : set the plot colors. The possible keys are 'object', 'vector' and 'keydots'. Output: <bool> """ if out_image=='': out_image=ps_name.replace(".fits","")+"_mediatrix_circle.png" image,hdr = getdata(ps_name, header = True ) pixels=where(image>0) A = subplot(111) for i in range (0,len(pixels[0])): xy=[pixels[1][i]-0.5,pixels[0][i]-0.5] rec=Rectangle(xy, 1, 1, ec=colors['object'], fc=colors['object'], zorder=100) A.add_patch(rec) #A.scatter(pixels[1], pixels[0], s=200, c='b', marker='s', edgecolors='none') #A.plot(pixels[1],pixels[0],colors['object']) Length=0 for i in range(0,len(mediatrix_data['origin'])): origin_x=mediatrix_data['origin'][i].real origin_y=mediatrix_data['origin'][i].imag end_x=mediatrix_data['end'][i].real end_y=mediatrix_data['end'][i].imag Length_aux=(origin_x - end_x)**2 + (origin_y - end_y)**2 Length=Length+ sqrt(Length_aux) if mediatrix_vectors==True: d_x= end_x - origin_x d_y= mediatrix_data['end'][i].imag - mediatrix_data['origin'][i].imag arr = Arrow(origin_y, origin_x, d_y, d_x, width=0.05*Length, fc=colors['vector'], ec='none',zorder=1000) A.add_patch(arr) if keydots==True: E1,E2=get_extrema_2loops(pixels[0], pixels[1], 0 ) Area=len(pixels[1]) p1=pixels[0][E1]+ pixels[1][E1]*1j # the extreme points p_1 and p_2 p2=pixels[0][E2]+ pixels[1][E2]*1j keydots=[p1,p2] keydots=find_keydots_c(p1,p2,pixels,image,keydots,Area, method="brightest",alpha=1) keyX=[] keyY=[] for j in range(0,len(keydots)): keyX.append(keydots[j].real) keyY.append(keydots[j].imag) A.plot(keyY,keyX,colors['keydots']+'.',zorder=500) #A.scatter(keyY, keyX, s=20, c='b', marker='s') last=len(mediatrix_data['origin'])-1 x=[pixels[0][E1],mediatrix_data['center'].real,pixels[0][E2]] y=[pixels[1][E1],mediatrix_data['center'].imag,pixels[1][E2]] p1_vec=[pixels[0][E1],pixels[1][E1]] # the extreme points p_1 and p_2 p2_vec=[pixels[0][E2],pixels[1][E2]] p3_vec=[mediatrix_vectors['center'].real,mediatrix_vectors['center'].imag] x_c,y_c,r=three_points_to_circle(p1_vec,p3_vec,p2_vec) if r>0: xy=[y_c,x_c] cir=Circle(xy,r,fc='none',ec='m', zorder=501) A.add_patch(cir) else: print "impossible to define a circle " xmin, xmax = xlim() ymin, ymax = ylim() min_inc_axis=40 #x_axis_length=(xmax+1*Length)-(xmin-1*Length) #y_axis_length=(ymax+1*Length)-(ymin-1*Length) #if x_axis_length<min_inc_axis A.axis("equal") A.set_xlim(xmin-1*Length,xmax+1*Length) A.set_ylim(ymin-1*Length,ymax+1*Length) ylabel("Y") xlabel("X") #A.axis("equal") title(plot_title) if save==True and r>0: savefig(out_image) A.clear() return True else: return A
def print_mediatrix_Object_graph_old(mediatrix_data,image_dir='', keydots=False, colors= {'object': "g", 'vector': "b", 'keydots': "k"}, save=True, save_dir=''): """ Make a plot presenting the object, keydots and mediatrix vectors. Input: - mediatrix_data <list> : the output from mediatrix_decomposition. - image_dir <str> : the image directory. If it is on the same directory, directory=''. - keydots <bool> : 'True' if you want to display the keydots and 'False' if you do not. - colors <dic> : set the plot colors. The possible keys are 'object', 'vector' and 'keydots'. Output: <bool> """ image_name=mediatrix_data['id'] image,hdr = getdata(image_dir+image_name, header = True ) pixels=where(image>0) A = subplot(111) for i in range (0,len(pixels[0])): xy=[pixels[1][i]-0.5,pixels[0][i]-0.5] rec=Rectangle(xy, 1, 1, ec=colors['object'], fc=colors['object'], zorder=100) A.add_patch(rec) #A.scatter(pixels[1], pixels[0], s=200, c='b', marker='s', edgecolors='none') #A.plot(pixels[1],pixels[0],colors['object']) Length=0 if keydots==True: E1,E2=get_extrema_2loops(pixels[0], pixels[1], 0 ) Area=len(pixels[1]) p1=[pixels[0][E1],pixels[1][E1]] # the extreme points p_1 and p_2 p2=[pixels[0][E2],pixels[1][E2]] keydots=[p1,p2] keydots=find_keydots(p1,p2,pixels,image,keydots,Area, method="brightest",alpha=1) keyX=[] keyY=[] for j in range(0,len(keydots)): keyX.append(keydots[j][0]) keyY.append(keydots[j][1]) A.plot(keyY,keyX,colors['keydots']+'.',zorder=500) #A.scatter(keyY, keyX, s=20, c='b', marker='s') for i in range(0,len(mediatrix_data['origin'])): origin_x=mediatrix_data['origin'][i][0] origin_y=mediatrix_data['origin'][i][1] end_x=mediatrix_data['end'][i][0] end_y=mediatrix_data['end'][i][1] Length_aux=(origin_x - end_x)**2 + (origin_y - end_y)**2 Length=Length+ sqrt(Length_aux) d_x= end_x - origin_x d_y= mediatrix_data['end'][i][1] - mediatrix_data['origin'][i][1] arr = Arrow(origin_y, origin_x, d_y, d_x, width=0.05*Length, fc=colors['vector'], ec='none',zorder=1000) A.add_patch(arr) xmin, xmax = xlim() ymin, ymax = ylim() min_inc_axis=40 #x_axis_length=(xmax+1*Length)-(xmin-1*Length) #y_axis_length=(ymax+1*Length)-(ymin-1*Length) #if x_axis_length<min_inc_axis A.axis("equal") A.set_xlim(xmin-1*Length,xmax+1*Length) A.set_ylim(ymin-1*Length,ymax+1*Length) ylabel("Y") xlabel("X") #A.axis("equal") title("Mediatrix Decomposition applied") if save==True: savefig(save_dir+image_name+"_mediatrixGraph.png") A.clear() return True else: return A
#plt.plot(time[870*sampling_rate:1100*sampling_rate], AC[0].data[870*sampling_rate:1100*sampling_rate], 'k',label='transverse acceleration', linewidth=3) for ii in range(3,39): # center the baz values around the estimated best value of 104 deg actf = AC_original.copy() act = actf.rotate(method='NE->RT',back_azimuth=ii*5)[0].data if np.abs(ii*5-baz[2])<2: tra.plot(time[500*sampling_rate:1100*sampling_rate], -0.1*ii+act[500*sampling_rate:1100*sampling_rate], c='k', linewidth=2.5) elif ii%2==0: tra.plot(time[500*sampling_rate:1100*sampling_rate], -0.1*ii+act[500*sampling_rate:1100*sampling_rate], c=colors[ii-3]) tra.plot(time[500*sampling_rate:1100*sampling_rate], -5+RLAS[0][500*sampling_rate:1100*sampling_rate], c='r', linewidth=1) tra.set_xlim(900,1100) tra.set_yticks([]) ## Frame autoAxis = tra.axis() rec = Rectangle((autoAxis[0],autoAxis[2]),(autoAxis[1]-autoAxis[0]),(autoAxis[3]-autoAxis[2]),fill=False,lw=4,color='k') rec = tra.add_patch(rec) rec.set_clip_on(False) #plt.xticks() #plt.ylabel('norm. transv. acc. \n') #plt.ticklabel_format(axis='y', style='sci', scilimits=(-2,2)) tra.legend() tra.axvline(930,c='k',linewidth=2) tra.axvline(1015,c='k',linewidth=2) #plt.plot([884,889],[-4,.05], linewidth=2, c='k') #plt.axvline(arriv_p) #plt.axvline(arriv_s) #print len(time), len(RLAS), len(AC[0]) wav=plt.subplot2grid((4, 30), (2, 0), colspan=29)
def plot_mediatrix(mediatrix_data,image_name,_id, keydots=False, colors= {'object': "g", 'vector': "b", 'keydots': "k"}, out_title="Mediatrix Decompostion", save=True, out_image=''): """ Make a plot presenting the object, keydots and mediatrix vectors. Input: - mediatrix_data <list> : the output from mediatrix_decomposition_on_matrix. - image_dir <str> : the image directory. If it is on the same directory, directory=''. - keydots <bool> : 'True' if you want to display the keydots and 'False' if you do not. - colors <dic> : set the plot colors. The possible keys are 'object', 'vector' and 'keydots'. Output: <bool> """ if out_image=='': out_image=image_name.replace(".fits","")+"_mediatrix_plot.png" image_segname=image_name.replace(".fits","")+"_seg.fits" image_objname=image_name.replace(".fits","")+"_obj.fits" image_seg,hdr = getdata(image_segname, header = True ) image_obj,hdr = getdata(image_objname, header = True ) image_ps,hdr=imcp.segstamp(segimg=image_seg, objID=_id, objimg=image_obj, hdr=hdr, increase=2, relative_increase=True, connected=False) pixels=where(image_ps>0) A = subplot(111) for i in range (0,len(pixels[0])): xy=[pixels[1][i]-0.5,pixels[0][i]-0.5] rec=Rectangle(xy, 1, 1, ec=colors['object'], fc=colors['object'], zorder=100) A.add_patch(rec) #A.scatter(pixels[1], pixels[0], s=200, c='b', marker='s', edgecolors='none') #A.plot(pixels[1],pixels[0],colors['object']) Length=0 if keydots==True: E1,E2=get_extrema_2loops(pixels[0], pixels[1], 0 ) Area=len(pixels[1]) p1=pixels[0][E1]+ pixels[1][E1]*1j # the extreme points p_1 and p_2 p2=pixels[0][E2]+ pixels[1][E2]*1j keydots=[p1,p2] keydots=find_keydots_c(p1,p2,pixels,image_ps,keydots,Area, method="brightest",alpha=1) keyX=[] keyY=[] for j in range(0,len(keydots)): keyX.append(keydots[j].real) keyY.append(keydots[j].imag) A.plot(keyY,keyX,colors['keydots']+'.',zorder=500) #A.scatter(keyY, keyX, s=20, c='b', marker='s') for i in range(0,len(mediatrix_data['origin'])): origin_x=mediatrix_data['origin'][i].real origin_y=mediatrix_data['origin'][i].imag end_x=mediatrix_data['end'][i].real end_y=mediatrix_data['end'][i].imag Length_aux=(origin_x - end_x)**2 + (origin_y - end_y)**2 Length=Length+ sqrt(Length_aux) d_x= end_x - origin_x d_y= mediatrix_data['end'][i].imag - mediatrix_data['origin'][i].imag arr = Arrow(origin_y, origin_x, d_y, d_x, width=0.05*Length, fc=colors['vector'], ec='none',zorder=1000) A.add_patch(arr) xmin, xmax = xlim() ymin, ymax = ylim() min_inc_axis=40 #x_axis_length=(xmax+1*Length)-(xmin-1*Length) #y_axis_length=(ymax+1*Length)-(ymin-1*Length) #if x_axis_length<min_inc_axis A.axis("equal") A.set_xlim(xmin-1*Length,xmax+1*Length) A.set_ylim(ymin-1*Length,ymax+1*Length) ylabel("Y") xlabel("X") #A.axis("equal") title(out_title) if save==True: savefig(out_image) A.clear() return True else: return A
def plotFrame(i, t, data, geometry): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) for line in data: p1x = line[0] p1y = line[1] p2x = line[2] p2y = line[3] connected = line[4] id0 = line[5] id1 = line[6] ms = 10 r = 2.2 ped = 8 #10 if id0 == ped: # print "t=%f p1 %d p2 %d. connet %d"%(t, id0, id1, connected) circ = plt.Circle((p1x, p1y), radius=r, alpha=.2, fc='grey') rect = Rectangle((p1x - r, p1y - r), 2 * r, 2 * r, alpha=.1, fc='grey') rect0 = Rectangle((p1x - 3 * r, p1y - 3 * r), 6 * r, 6 * r, alpha=.1, fc='grey') rect1 = Rectangle((p1x + r, p1y - r), 2 * r, 2 * r, alpha=.1, fc='grey') rect2 = Rectangle((p1x - 3 * r, p1y - r), 2 * r, 2 * r, alpha=.1, fc='grey') rect3 = Rectangle((p1x - r, p1y + r), 2 * r, 2 * r, alpha=.1, fc='grey') rect4 = Rectangle((p1x - r, p1y - 3 * r), 2 * r, 2 * r, alpha=.1, fc='grey') ax.add_patch(rect) ax.add_patch(rect1) ax.add_patch(rect0) ax.add_patch(rect2) ax.add_patch(rect3) ax.add_patch(rect4) ax.add_patch(circ) dx = 0.5 annotate = 1 if connected == 1: plt.plot((p2x), (p2y), 'or') if annotate: plt.annotate('%d' % id1, xy=(p2x, p2y), xytext=(p2x - dx, p2y - dx)) plt.plot((p1x), (p1y), 'ok') #plt.annotate('%d'%id0, xy=(p1x, p1y), xytext=(p1x-dx, p1y-dx)) plt.plot((p1x, p2x), (p1y, p2y), '-g', lw=1) # elif connected == -1: # same peds # #plt.plot((p2x), (p2y), 'or') # #plt.plot((p1x), (p1y), 'ok', ms=ms) # plt.plot((p1x), (p1y), 'ob', alpha=0.7) # # plt.annotate('%d'%id1, xy=(p2x, p2y), xytext=(p2x-0.3, p2y-0.3)) # # plt.annotate('%d'%id0, xy=(p1x, p1y), xytext=(p1x-0.3, p1y-0.3)) else: plt.plot((p2x), (p2y), 'or') #plt.plot((p1x), (p1y), 'ok', ms=ms) if connected == 0: plt.plot((p1x, p2x), (p1y, p2y), '--k', alpha=0.5) plt.annotate('%d' % id1, xy=(p2x, p2y), xytext=(p2x - dx, p2y - dx)) #plt.annotate('%d'%id0, xy=(p1x, p1y), xytext=(p1x-dx, p1y-dx)) # plot dummy peds # plt.plot((45), (108), '.k') # plt.plot((45), (94), '.k') # plt.plot((75), (94), '.k') # plt.plot((75), (108), '.k') #geometry # plt.plot([50, 65, 62, 62, 60, 60, 56], [104, 104, 104, 102.45, 102.45, 104, 104], 'k', lw=2) # plt.plot([50, 65, 62, 62, 60, 60, 56], [100, 100, 100, 101.4, 101.4, 100, 100], 'k', lw=2) # plt.plot([56,56], [100,104], "--b", alpha=0.3) # # plt.plot([54,54], [100,104], "--b", alpha=0.3) # plt.plot([62,62], [101.4,102.45], "--b", alpha=0.3) plot_geometry(geometry) # plt.xlim((48,66)) # plt.ylim((99,105)) #plt.xlim((-30,50)) #plt.ylim((126,140)) plt.axis('scaled') plt.title("t=%.3f" % t) fig.savefig("figs_bot/%.4d.png" % i) plt.clf() print("---> figs_bot/%.4d.png" % i)
class CartPole: """Cart Pole environment. This implementation allows multiple poles, noisy action, and random starts. It has been checked repeatedly for 'correctness', specifically the direction of gravity. Some implementations of cart pole on the internet have the gravity constant inverted. The way to check is to limit the force to be zero, start from a valid random start state and watch how long it takes for the pole to fall. If the pole falls almost immediately, you're all set. If it takes tens or hundreds of steps then you have gravity inverted. It will tend to still fall because of round off errors that cause the oscillations to grow until it eventually falls. """ def __init__(self, visual=False): self.cart_location = 0.0 self.cart_velocity = 0.0 self.pole_angle = np.pi # angle is defined to be zero when the pole is upright, pi when hanging vertically down self.pole_velocity = 0.0 self.visual = visual # Setup pole lengths and masses based on scale of each pole # (Papers using multi-poles tend to have them either same lengths/masses # or they vary by some scalar from the other poles) self.pole_length = 0.5 self.pole_mass = 0.5 self.mu_c = 0.1 # 0.005 # friction coefficient of the cart self.mu_p = 0.0000 # 0.000002 # friction coefficient of the pole self.sim_steps = 200 # number of Euler steps to perform in one go self.delta_time = 0.1 # time step of the Euler integrator self.max_force = 10. self.gravity = 9.8 self.cart_mass = 0.5 # for plotting self.cartwidth = 1.0 self.cartheight = 0.2 if self.visual: self.drawPlot() def setState(self, state): self.cart_location = state[0] self.cart_velocity = state[1] self.pole_angle = state[2] self.pole_velocity = state[3] def getState(self): return np.array([ self.cart_location, self.cart_velocity, self.pole_angle, self.pole_velocity ]) def reset(self): self.cart_location = 0.0 self.cart_velocity = 0.0 self.pole_angle = np.pi self.pole_velocity = 0.0 def drawPlot(self): ion() self.fig = plt.figure() # draw cart self.axes = self.fig.add_subplot(111, aspect='equal') self.box = Rectangle(xy=(self.cart_location - self.cartwidth / 2.0, -self.cartheight), width=self.cartwidth, height=self.cartheight) self.axes.add_artist(self.box) self.box.set_clip_box(self.axes.bbox) # draw pole self.pole = Line2D( [self.cart_location, self.cart_location + np.sin(self.pole_angle)], [0, np.cos(self.pole_angle)], linewidth=3, color='black') self.axes.add_artist(self.pole) self.pole.set_clip_box(self.axes.bbox) # set axes limits self.axes.set_xlim(-10, 10) self.axes.set_ylim(-0.5, 2) def _render(self): self.box.set_x(self.cart_location - self.cartwidth / 2.0) self.pole.set_xdata( [self.cart_location, self.cart_location + np.sin(self.pole_angle)]) self.pole.set_ydata([0, np.cos(self.pole_angle)]) draw() plt.pause(0.015) def performAction(self, action): force = self.max_force * np.tanh(action / self.max_force) for step in range(self.sim_steps): s = np.sin(self.pole_angle) c = np.cos(self.pole_angle) m = 4.0 * (self.cart_mass + self.pole_mass) - 3.0 * self.pole_mass * (c**2) cart_accel = (-2.0 * self.pole_length * self.pole_mass * (self.pole_velocity**2) * s + 3.0 * self.pole_mass * self.gravity * c * s + 4.0 * (force - self.mu_c * self.cart_velocity)) / m pole_accel = ( -3.0 * self.pole_length * self.pole_mass * (self.pole_velocity**2) * s * c + 6.0 * (self.cart_mass + self.pole_mass) * self.gravity * s + 6.0 * (force - self.mu_c * self.cart_velocity) * c) / ( m * self.pole_length) # Update state variables df = (self.delta_time / float(self.sim_steps)) self.cart_location += df * self.cart_velocity self.cart_velocity += df * cart_accel self.pole_angle += df * self.pole_velocity self.pole_velocity += df * pole_accel if self.visual: self._render() def remap_angle(self): # If theta has gone past our conceptual limits of [-pi,pi] # map it onto the equivalent angle that is in the accepted range (by adding or subtracting 2pi) while self.pole_angle < -np.pi: self.pole_angle += 2. * np.pi while self.pole_angle > np.pi: self.pole_angle -= 2. * np.pi # the loss function that the policy will try to optimise (lower) def loss(self): # first of all, we want the pole to be upright (theta = 0), so we penalise theta away from that loss_angle_scale = np.pi / 2.0 loss_angle = 1.0 - np.exp( -0.5 * self.pole_angle**2 / loss_angle_scale**2) # but also, we want to HOLD it upright, so we also penalise large angular velocities, but only near # the upright position loss_velocity_scale = 0.1 loss_velocity = (1.0 - loss_angle) * (self.pole_velocity** 2) * loss_velocity_scale return loss_angle + loss_velocity def terminate(self): """Indicates whether or not the episode should terminate. Returns: A boolean, true indicating the end of an episode and false indicating the episode should continue. False is returned if either the cart location or the pole angle is beyond the allowed range. """ return np.abs(self.cart_location) > self.state_range[0, 1] or \ (np.abs(self.pole_angle) > self.state_range[2, 1]).any()
class CartPoleRenderer(Renderer): def __init__(self): Renderer.__init__(self) self.dataLock = threading.Lock() self.angle = 0.0 self.angle_vel = 0.0 self.pos = 0.0 self.pos_vel = 0.0 self.stopRequest = False # some drawing constants self.cartheight = 0.2 self.cartwidth = 1.0 self.polelength = 0.5 self.plotlimits = [-4, 4, -0.5, 3] self.box = None self.pole = None def updateData(self, data): self.dataLock.acquire() (self.angle, self.angle_vel, self.pos, self.pos_vel) = data self.dataLock.release() def stop(self): self.stopRequest = True def start(self): self.drawPlot() Renderer.start(self) def drawPlot(self): ion() fig = figure(1) # draw cart axes = fig.add_subplot(111, aspect='equal') self.box = Rectangle(xy=(self.pos - self.cartwidth / 2.0, -self.cartheight), width=self.cartwidth, height=self.cartheight) axes.add_artist(self.box) self.box.set_clip_box(axes.bbox) # draw pole self.pole = Line2D([self.pos, self.pos + sin(self.angle)], [0, cos(self.angle)], linewidth=3, color='black') axes.add_artist(self.pole) self.pole.set_clip_box(axes.bbox) # set axes limits axes.set_xlim(-2.5, 2.5) axes.set_ylim(-0.5, 2) def _render(self): while not self.stopRequest: if self.angle < 0.05 and abs(self.pos) < 0.05: self.box.set_facecolor('green') else: self.box.set_facecolor('blue') self.box.set_x(self.pos - self.cartwidth / 2.0) self.pole.set_xdata( [self.pos, self.pos + self.polelength * sin(self.angle)]) self.pole.set_ydata([0, self.polelength * cos(self.angle)]) draw() time.sleep(0.05) self.stopRequest = False
def mosaic(data, index=None, ax=None, horizontal=True, gap=0.005, properties=lambda key: None, labelizer=None, title='', statistic=False, axes_label=True, label_rotation=0.0): """Create a mosaic plot from a contingency table. It allows to visualize multivariate categorical data in a rigorous and informative way. Parameters ---------- data : dict, pandas.Series, np.ndarray, pandas.DataFrame The contingency table that contains the data. Each category should contain a non-negative number with a tuple as index. It expects that all the combination of keys to be representes; if that is not true, will automatically consider the missing values as 0. The order of the keys will be the same as the one of insertion. If a dict of a Series (or any other dict like object) is used, it will take the keys as labels. If a np.ndarray is provided, it will generate a simple numerical labels. index: list, optional Gives the preferred order for the category ordering. If not specified will default to the given order. It doesn't support named indexes for hierarchical Series. If a DataFrame is provided, it expects a list with the name of the columns. ax : matplotlib.Axes, optional The graph where display the mosaic. If not given, will create a new figure horizontal : bool, optional (default True) The starting direction of the split (by default along the horizontal axis) gap : float or array of floats The list of gaps to be applied on each subdivision. If the lenght of the given array is less of the number of subcategories (or if it's a single number) it will extend it with exponentially decreasing gaps labelizer : function (key) -> string, optional A function that generate the text to display at the center of each tile base on the key of that tile properties : function (key) -> dict, optional A function that for each tile in the mosaic take the key of the tile and returns the dictionary of properties of the generated Rectangle, like color, hatch or similar. A default properties set will be provided fot the keys whose color has not been defined, and will use color variation to help visually separates the various categories. It should return None to indicate that it should use the default property for the tile. A dictionary of the properties for each key can be passed, and it will be internally converted to the correct function statistic: bool, optional (default False) if true will use a crude statistical model to give colors to the plot. If the tile has a containt that is more than 2 standard deviation from the expected value under independence hipotesys, it will go from green to red (for positive deviations, blue otherwise) and will acquire an hatching when crosses the 3 sigma. title: string, optional The title of the axis axes_label: boolean, optional Show the name of each value of each category on the axis (default) or hide them. label_rotation: float or list of float the rotation of the axis label (if present). If a list is given each axis can have a different rotation Returns ---------- fig : matplotlib.Figure The generate figure rects : dict A dictionary that has the same keys of the original dataset, that holds a reference to the coordinates of the tile and the Rectangle that represent it See Also ---------- A Brief History of the Mosaic Display Michael Friendly, York University, Psychology Department Journal of Computational and Graphical Statistics, 2001 Mosaic Displays for Loglinear Models. Michael Friendly, York University, Psychology Department Proceedings of the Statistical Graphics Section, 1992, 61-68. Mosaic displays for multi-way contingecy tables. Michael Friendly, York University, Psychology Department Journal of the american statistical association March 1994, Vol. 89, No. 425, Theory and Methods Examples ---------- The most simple use case is to take a dictionary and plot the result >>> data = {'a': 10, 'b': 15, 'c': 16} >>> mosaic(data, title='basic dictionary') >>> pylab.show() A more useful example is given by a dictionary with multiple indices. In this case we use a wider gap to a better visual separation of the resulting plot >>> data = {('a', 'b'): 1, ('a', 'c'): 2, ('d', 'b'): 3, ('d', 'c'): 4} >>> mosaic(data, gap=0.05, title='complete dictionary') >>> pylab.show() The same data can be given as a simple or hierarchical indexed Series >>> rand = np.random.random >>> from itertools import product >>> >>> tuples = list(product(['bar', 'baz', 'foo', 'qux'], ['one', 'two'])) >>> index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) >>> data = pd.Series(rand(8), index=index) >>> mosaic(data, title='hierarchical index series') >>> pylab.show() The third accepted data structureis the np array, for which a very simple index will be created. >>> rand = np.random.random >>> data = 1+rand((2,2)) >>> mosaic(data, title='random non-labeled array') >>> pylab.show() If you need to modify the labeling and the coloring you can give a function tocreate the labels and one with the graphical properties starting from the key tuple >>> data = {'a': 10, 'b': 15, 'c': 16} >>> props = lambda key: {'color': 'r' if 'a' in key else 'gray'} >>> labelizer = lambda k: {('a',): 'first', ('b',): 'second', ('c',): 'third'}[k] >>> mosaic(data, title='colored dictionary', properties=props, labelizer=labelizer) >>> pylab.show() Using a DataFrame as source, specifying the name of the columns of interest >>> gender = ['male', 'male', 'male', 'female', 'female', 'female'] >>> pet = ['cat', 'dog', 'dog', 'cat', 'dog', 'cat'] >>> data = pandas.DataFrame({'gender': gender, 'pet': pet}) >>> mosaic(data, ['pet', 'gender']) >>> pylab.show() """ if isinstance(data, DataFrame) and index is None: raise ValueError("You must pass an index if data is a DataFrame." " See examples.") from pylab import Rectangle fig, ax = utils.create_mpl_ax(ax) # normalize the data to a dict with tuple of strings as keys data = _normalize_data(data, index) # split the graph into different areas rects = _hierarchical_split(data, horizontal=horizontal, gap=gap) # if there is no specified way to create the labels # create a default one if labelizer is None: labelizer = lambda k: "\n".join(k) if statistic: default_props = _statistical_coloring(data) else: default_props = _create_default_properties(data) if isinstance(properties, dict): color_dict = properties properties = lambda key: color_dict.get(key, None) for k, v in iteritems(rects): # create each rectangle and put a label on it x, y, w, h = v conf = properties(k) props = conf if conf else default_props[k] text = labelizer(k) Rect = Rectangle((x, y), w, h, label=text, **props) ax.add_patch(Rect) ax.text(x + w / 2, y + h / 2, text, ha='center', va='center', size='smaller') #creating the labels on the axis #o clearing it if axes_label: if np.iterable(label_rotation): rotation = label_rotation else: rotation = [label_rotation] * 4 labels = _create_labels(rects, horizontal, ax, rotation) else: ax.set_xticks([]) ax.set_xticklabels([]) ax.set_yticks([]) ax.set_yticklabels([]) ax.set_title(title) return fig, rects
positionArrayY, s=5, facecolor='blue', alpha=0.15) # s=size, alpha=Transparency pylab.title('Hole Cloud Projection on Readout Plane, ' + str(ENERGY) + ' keV') pylab.xlabel('x position (um)') pylab.ylabel('y position (um)') pylab.grid(True) # Draw strips, gaps, and proximity regions currentAxis = pylab.gca() currentAxis.add_patch( Rectangle((-3 * STRIPWIDTH / 2 - GAP, -2500), STRIPWIDTH, 5000, facecolor='blue', alpha=0.10)) currentAxis.add_patch( Rectangle((-STRIPWIDTH / 2 - GAP, -2500), GAP, 5000, facecolor='yellow', alpha=0.10)) currentAxis.add_patch( Rectangle((-STRIPWIDTH / 2, -2500), STRIPWIDTH, 5000, facecolor='blue', alpha=0.10)) currentAxis.add_patch(