def test_plot_dep_contour(self): plot = MapPlotSlab() plot.plot_dep_contour(-20, color='red') plot.plot_dep_contour(-40, color='blue') plot.plot_dep_contour(-60, color='black') plt.savefig(join(this_test_path, '~outs/plot_dep_contour.png')) plt.close()
def serve_css(name, length, keys, values): from pylab import plt, mpl mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['axes.unicode_minus'] = False from matplotlib.font_manager import FontProperties # font = FontProperties(fname="d:\Users\ll.tong\Desktop\msyh.ttf", size=12) font = FontProperties(fname="/usr/share/fonts/msyh.ttf", size=11) plt.xlabel(u'') plt.ylabel(u'出现次数',fontproperties=font) plt.title(u'词频统计',fontproperties=font) plt.grid() keys = keys.decode("utf-8").split(' ') values = values.split(' ') valuesInt = [] for value in values: valuesInt.append(int(value)) plt.xticks(range(int(length)), keys) plt.plot(range(int(length)), valuesInt) plt.xticks(rotation=defaultrotation, fontsize=9,fontproperties=font) plt.yticks(fontsize=10,fontproperties=font) name = name + str(datetime.now().date()).replace(':', '') + '.png' imgUrl = 'static/temp/' + name fig = matplotlib.pyplot.gcf() fig.set_size_inches(12.2, 2) plt.savefig(imgUrl, bbox_inches='tight', figsize=(20,4), dpi=100) plt.close() tempfile = static_file(name, root='./static/temp/') #os.remove(imgUrl) return tempfile
def render_confusion(file_name, queue, vmin, vmax, divergent, array_shape): from pylab import plt import matplotlib.animation as animation plt.close() fig = plt.figure() def update_img((expected, output)): plt.cla() plt.ylim((vmin, vmin+vmax)) plt.xlim((vmin, vmin+vmax)) ax = fig.add_subplot(111) plt.plot([vmin, vmin+vmax], [vmin, vmin+vmax]) ax.grid(True) plt.xlabel("expected output") plt.ylabel("network output") plt.legend() expected = expected*vmax + vmin output = output*vmax + vmin #scat.set_offsets((expected, output)) scat = ax.scatter(expected, output) return scat ani = animation.FuncAnimation(fig, update_img, frames=IterableQueue(queue)) ani.save(file_name, fps=30, extra_args=['-vcodec', 'libvpx', '-threads', '4', '-b:v', '1M'])
def plot(cls, data, figure_folder, msg="", suffix=""): fig, ax = plt.subplots() plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.2) x = np.arange(len(data[:])) ax.plot(x, data[:, 0], c="red", linewidth=2, label="agent 01") ax.plot(x, data[:, 1], c="blue", linewidth=2, label="agent 12") ax.plot(x, data[:, 2], c="green", linewidth=2, label="agent 20") plt.ylim([-0.01, 1.01]) plt.text(0, -0.23, "PARAMETERS. {}".format(msg)) ax.legend(fontsize=12, bbox_to_anchor=(1.1, 1.05)) # loc='upper center' ax.set_xlabel("$t$") ax.set_ylabel("Proportion of agents proceeding to indirect exchange") ax.set_title("Money emergence with a basal ganglia model") # Save fig if not exists(figure_folder): mkdir(figure_folder) fig_name = "{}/figure_{}.pdf".format(figure_folder, suffix.split(".p")[0]) plt.savefig(fig_name) plt.close()
def link_level_bars(levels, usages, quantiles, scheme, direction, color, nnames, lnames, admat=None): """ Bar plots of nodes' link usage of links at different levels. """ if not admat: admat = np.genfromtxt('./settings/eadmat.txt') if color == 'solar': cmap = Oranges_cmap elif color == 'wind': cmap = Blues_cmap elif color == 'backup': cmap = 'Greys' nodes, links = usages.shape usageLevels = np.zeros((nodes, levels)) usageLevelsNorm = np.zeros((nodes, levels)) for node in range(nodes): nl = neighbor_levels(node, levels, admat) for lvl in range(levels): ll = link_level(nl, lvl, nnames, lnames) ll = np.array(ll, dtype='int') usageSum = sum(usages[node, ll]) linkSum = sum(quantiles[ll]) usageLevels[node, lvl] = usageSum / linkSum if lvl == 0: usageLevelsNorm[node, lvl] = usageSum else: usageLevelsNorm[node, lvl] = usageSum / usageLevelsNorm[node, 0] usageLevelsNorm[:, 0] = 1 # plot all nodes usages = usageLevels.transpose() plt.figure(figsize=(11, 3)) ax = plt.subplot() plt.pcolormesh(usages[:, loadOrder], cmap=cmap) plt.colorbar().set_label(label=r'$U_n^{(l)}$', size=11) ax.set_yticks(np.linspace(.5, levels - .5, levels)) ax.set_yticklabels(range(1, levels + 1)) ax.yaxis.set_tick_params(width=0) ax.xaxis.set_tick_params(width=0) ax.set_xticks(np.linspace(1, nodes, nodes)) ax.set_xticklabels(loadNames, rotation=60, ha="right", va="top", fontsize=10) plt.ylabel('Link level') plt.savefig(figPath + '/levels/' + str(scheme) + '/' + 'total' + '_' + str(direction) + '_' + color + '.pdf', bbox_inches='tight') plt.close() # plot all nodes normalised to usage of first level usages = usageLevelsNorm.transpose() plt.figure(figsize=(11, 3)) ax = plt.subplot() plt.pcolormesh(usages[:, loadOrder], cmap=cmap) plt.colorbar().set_label(label=r'$U_n^{(l)}$', size=11) ax.set_yticks(np.linspace(.5, levels - .5, levels)) ax.set_yticklabels(range(1, levels + 1)) ax.yaxis.set_tick_params(width=0) ax.xaxis.set_tick_params(width=0) ax.set_xticks(np.linspace(1, nodes, nodes)) ax.set_xticklabels(loadNames, rotation=60, ha="right", va="top", fontsize=10) plt.ylabel('Link level') plt.savefig(figPath + '/levels/' + str(scheme) + '/' + 'total_norm_cont_' + str(direction) + '_' + color + '.pdf', bbox_inches='tight') plt.close()
def pure_data_plot(self,connect=False,suffix='',cmap=cm.jet,bg=cm.bone(0.3)): #fig=plt.figure() ax=plt.axes() plt.axhline(y=0,color='grey', zorder=-1) plt.axvline(x=0,color='grey', zorder=-2) if cmap is None: if connect: ax.plot(self.x,self.y, 'b-',lw=2,alpha=0.5) ax.scatter(self.x,self.y, marker='o', c='b', s=40) else: if connect: if cmap in [cm.jet,cm.brg]: ax.plot(self.x,self.y, 'c-',lw=2,alpha=0.5,zorder=-1) else: ax.plot(self.x,self.y, 'b-',lw=2,alpha=0.5) c=[cmap((f-self.f[0])/(self.f[-1]-self.f[0])) for f in self.f] #c=self.f ax.scatter(self.x, self.y, marker='o', c=c, edgecolors=c, zorder=True, s=40) #, cmap=cmap) #plt.axis('equal') ax.set_xlim(xmin=-0.2*amax(self.x), xmax=1.2*amax(self.x)) ax.set_aspect('equal') #, 'datalim') if cmap in [cm.jet,cm.brg]: ax.set_axis_bgcolor(bg) if self.ZorY == 'Z': plt.xlabel(r'resistance $R$ in Ohm'); plt.ylabel(r'reactance $X$ in Ohm') if self.ZorY == 'Y': plt.xlabel(r'conductance $G$ in Siemens'); plt.ylabel(r'susceptance $B$ in Siemens') if self.show: plt.show() else: plt.savefig(join(self.sdc.plotpath,'c{}_{}_circle_data'.format(self.sdc.case,self.ZorY)+self.sdc.suffix+self.sdc.outsuffix+suffix+'.png'), dpi=240) plt.close()
def plot_stat(rows, cache): "Use matplotlib to plot DAS statistics" if not PLOT_ALLOWED: raise Exception('Matplotlib is not available on the system') if cache in ['cache', 'merge']: # cachein, cacheout, mergein, mergeout name_in = '%sin' % cache name_out = '%sout' % cache else: # webip, webq, cliip, cliq name_in = '%sip' % cache name_out = '%sq' % cache def format_date(date): "Format given date" val = str(date) return '%s-%s-%s' % (val[:4], val[4:6], val[6:8]) date_range = [r['date'] for r in rows] formated_dates = [format_date(str(r['date'])) for r in rows] req_in = [r[name_in] for r in rows] req_out = [r[name_out] for r in rows] plt.plot(date_range, req_in , 'ro-', date_range, req_out, 'gv-', ) plt.grid(True) plt.axis([min(date_range), max(date_range), \ 0, max([max(req_in), max(req_out)])]) plt.xticks(date_range, tuple(formated_dates), rotation=17) # plt.xlabel('dates [%s, %s]' % (date_range[0], date_range[-1])) plt.ylabel('DAS %s behavior' % cache) plt.savefig('das_%s.pdf' % cache, format='pdf', transparent=True) plt.close()
def test1(self): partition_file = '/home/zy/workspace/viscojapan/tests/share/deformation_partition.h5' res_file = '/home/zy/workspace/viscojapan/tests/share/nrough_05_naslip_11.h5' plotter = vj.inv.PredictedTimeSeriesPlotter( partition_file = partition_file, #result_file = res_file, ) site = 'J550' cmpt = 'e' #plotter.plot_cumu_disp_pred(site, cmpt) #plotter.plot_cumu_disp_pred_added(site, cmpt, color='blue') # plotter.plot_post_disp_pred_added(site, cmpt) #plotter.plot_cumu_obs_linres(site, cmpt) #plotter.plot_R_co(site, cmpt) # plotter.plot_post_disp_pred(site, cmpt) # plotter.plot_post_obs_linres(site, cmpt) #plotter.plot_E_cumu_slip(site, cmpt) # plotter.plot_E_aslip(site, cmpt) #plotter.plot_R_aslip(site, cmpt) #plt.show() #plt.close() # plotter.plot_cumu_disp_decomposition(site, cmpt) plt.show() plt.close() plotter.plot_post_disp_decomposition(site, cmpt) plt.show() plt.close()
def test_plot_slip(self): ep = EpochalIncrSlip(self.file_incr_slip) plot = MapPlotFault(self.file_fault) plot.plot_slip(ep(0)) plt.savefig(join(self.outs_dir, 'plot_slip.png')) plt.close()
def plot_data(self): for i,dat in enumerate(self.data): plt.imshow(dat, cmap=cm.jet, interpolation=None, extent=[11,22,-3,2]) txt='plot '.format(self.n[i]) txt+='\nmin {0:.2f} und max {1:.2f}'.format(self.min[i],self.max[i]) txt+='\navg. min {0:.2f} und avg. max {1:.2f}'.format(mean(self.min),mean(self.max)) plt.suptitle(txt,x=0.5,y=0.98,ha='center',va='top',fontsize=10) plt.savefig(join(self.plotpath,'pic_oo_'+str(self.n[i])+'.png')) plt.close() # wichtig, sonst wird in den selben Plot immer mehr reingepackt
def test_dip(self): xf = arange(0, 425) dips = self.fm.get_dip(xf) plt.plot(xf,dips) plt.grid('on') plt.gca().set_xticks(self.fm.Y_PC) plt.ylim([0, 30]) plt.gca().invert_yaxis() plt.savefig(join(self.outs_dir, '~y_fc_dips.png')) plt.close()
def plot_mat(self, mat, fn): plt.matshow(asarray(mat.todense())) plt.axis('equal') sh = mat.shape plt.gca().set_yticks(range(0,sh[0])) plt.gca().set_xticks(range(0,sh[1])) plt.grid('on') plt.colorbar() plt.savefig(join(self.outs_dir, fn)) plt.close()
def plot_post(cfs,ifshow=False,loc=2, save_fig_path = None, file_type='png'): for cf in cfs: plot_cf(cf, color='blue') plt.legend(loc=loc) if ifshow: plt.show() if save_fig_path is not None: plt.savefig(join(save_fig_path, '%s_%s.%s'%(cf.SITE, cf.CMPT, file_type))) plt.close()
def test_pcolor_on_fault(self): ep = EpochalIncrSlip(self.file_incr_slip) fio = FaultFileIO(self.file_fault) slip = ep(0).reshape([fio.num_subflt_along_dip, fio.num_subflt_along_strike]) plot = MapPlotFault(self.file_fault) plot.pcolor_on_fault(slip) plt.savefig(join(self.outs_dir, 'pcolor_on_fault.png')) plt.close()
def test_share_basemap(self): bm = MyBasemap(x_interval = 1) p1 = MapPlotSlab(basemap = bm) p1.plot_top() p2 = MapPlotFault(fault_file=join(this_script_dir, 'share/fault.h5'), basemap = bm) p2.plot_fault() plt.savefig(join(this_script_dir, '~outs/share_basemap.png')) plt.close()
def test1(self): file_G = join(self.share_dir,'G0_He50km_VisM6.3E18_Rake83.h5') G = vj.inv.ep.EpochGNoRaslip(file_G, mask_sites= ['J550'] ) out = G.get_data_at_epoch(0) stacked = G.stack([0,60,120]) plt.matshow(abs(stacked)*100, aspect=5) # plt.show() plt.close()
def plot_smoothed_alpha_comparison(self,rmsval,suffix=''): plt.plot(self.f,self.alpha,'ko',label='data set') plt.plot(self.f,self.salpha,'c-',lw=2,label='smoothed angle $\phi$') plt.xlabel('frequency in Hz') plt.ylabel('angle $\phi$ in coordinates of circle') plt.legend() ylims=plt.axes().get_ylim() plt.yticks((arange(9)-4)*0.5*pi, ['$-2\pi$','$-3\pi/2$','$-\pi$','$-\pi/2$','$0$','$\pi/2$','$\pi$','$3\pi/2$','$2\pi$']) plt.ylim(ylims) plt.title('RMS offset from smooth curve: {:.4f}'.format(rmsval)) if self.show: plt.show() else: plt.savefig(join(self.sdc.plotpath,'salpha','c{}_salpha_on_{}_circle'.format(self.sdc.case,self.ZorY)+self.sdc.suffix+self.sdc.outsuffix+suffix+'.png'), dpi=240) plt.close()
def test_fault2geo(self): xf = linspace(0., 700, 25) yf = linspace(0, 425, 30) xxf, yyf = meshgrid(xf, yf) LLons, LLats = self.fm.fault2geo(xxf, yyf) self.plt_map.basemap.plot(LLons,LLats,color='gray',latlon=True) self.plt_map.basemap.plot(ascontiguousarray(LLons.T), ascontiguousarray(LLats.T), color='gray',latlon=True) plt.savefig('~test_fault2geo.png') plt.close()
def test_ground2geo(self): xp = linspace(0, 700, 25) yp = linspace(0, 425, 30) xxp, yyp = meshgrid(xp, yp) LLons, LLats = self.fm.ground2geo(xxp, yyp) self.plt_map.basemap.plot(LLons,LLats,color='gray',latlon=True) self.plt_map.basemap.plot(ascontiguousarray(LLons.T), ascontiguousarray(LLats.T), color='gray',latlon=True) plt.savefig('~test_ground2geo.png') plt.close()
def test1(self): partition_file = '/home/zy/workspace/viscojapan/tests/share/deformation_partition.h5' plotter = vj.inv.PredictedVelocityTimeSeriesPlotter( partition_file = partition_file ) site = 'J550' cmpt = 'e' plotter.plot_vel_decomposition(site, cmpt) plt.show() plt.close()
def convert_all_to_png(vis_path, out_dir = "maps_png", size = None) : units = { 'gas_density' : 'Gas Density [g/cm$^3$]', 'Tm' : 'Temperature [K]', 'Tew' : 'Temperature [K]', 'S' : 'Entropy []', 'dm' : 'DM Density [g/cm$^3$]', 'v' : 'Velocity [km/s]' } log_list = ['gas_density'] for vis_file in os.listdir(vis_path) : if ".dat" not in vis_file : continue print "converting %s" % vis_file map_type = re.search('sigma_(.*)_[xyz]', vis_file).group(1) (image, pixel_size, axis_values) = read_visualization_data(vis_path+"/"+vis_file, size) print "image width in Mpc/h: ", axis_values[-1]*2.0 x, y = np.meshgrid( axis_values, axis_values ) cmap_max = image.max() cmap_min = image.min() ''' plotting ''' plt.figure(figsize=(5,4)) if map_type in log_list: plt.pcolor(x,y,image, norm=LogNorm(vmax=cmap_max, vmin=cmap_min)) else : plt.pcolor(x,y,image, vmax=cmap_max, vmin=cmap_min) cbar = plt.colorbar() if map_type in units.keys() : cbar.ax.set_ylabel(units[map_type]) plt.axis([axis_values[0], axis_values[-1],axis_values[0], axis_values[-1]]) del image plt.xlabel(r"$Mpc/h$", fontsize=18) plt.ylabel(r"$Mpc/h$", fontsize=18) out_file = vis_file.replace("dat", "png") plt.savefig(out_dir+"/"+out_file, dpi=150 ) plt.close() plt.clf()
def plot_overview_B(self,suffix='',ansize=8,anspread=0.15,anmode='quarters',datbg=True,datbgsource=None,checkring=False): self.start_plot() if datbg: # data background desired self.plot_bg_data(datbgsource=datbgsource) #self.plot_data() self.plot_fitcircle() if checkring: self.plot_checkring() idxlist=self.to_be_annotated(anmode) self.annotate_data_points(idxlist,ansize,anspread) self.plot_characteristic_freqs(annotate=True,size=ansize,spread=anspread) if self.show: plt.show() else: plt.savefig(join(self.sdc.plotpath,'c{}_fitted_{}_circle'.format(self.sdc.case,self.ZorY)+self.sdc.suffix+self.sdc.outsuffix+suffix+'.png'), dpi=240) plt.close()
def main(args=sys.argv[1:]): # there are some cases when this script is run on systems without DISPLAY variable being set # in such case matplotlib backend has to be explicitly specified # we do it here and not in the top of the file, as inteleaving imports with code lines is discouraged import matplotlib matplotlib.use('Agg') from pylab import plt, ylabel, grid, xlabel, array parser = argparse.ArgumentParser() parser.add_argument("rst_file", help="location of rst file in TRiP98 format", type=str) parser.add_argument("output_file", help="location of PNG file to save", type=str) parser.add_argument("-s", "--submachine", help="Select submachine to plot.", type=int, default=1) parser.add_argument("-f", "--factor", help="Factor for scaling the blobs. Default is 1000.", type=int, default=1000) parser.add_argument("-v", "--verbosity", action='count', help="increase output verbosity", default=0) parser.add_argument('-V', '--version', action='version', version=pt.__version__) args = parser.parse_args(args) file = args.rst_file sm = args.submachine fac = args.factor a = pt.Rst() a.read(file) # convert data in submachine to a nice array b = a.machines[sm] x = [] y = [] z = [] for _x, _y, _z in b.raster_points: x.append(_x) y.append(_y) z.append(_z) title = "Submachine: {:d} / {:d} - Energy: {:.3f} MeV/u".format(sm, len(a.machines), b.energy) print(title) cc = array(z) cc = cc / cc.max() * fac fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(x, y, c=cc, s=cc, alpha=0.75) ylabel("mm") xlabel("mm") grid(True) plt.title(title) plt.savefig(args.output_file) plt.close()
def plot_overview(self,suffix=''): x=self.x; y=self.y; r=self.radius; cx,cy=self.center.real,self.center.imag ax=plt.axes() plt.scatter(x,y, marker='o', c='b', s=40) plt.axhline(y=0,color='grey', zorder=-1) plt.axvline(x=0,color='grey', zorder=-2) t=linspace(0,2*pi,201) circx=r*cos(t) + cx circy=r*sin(t) + cy plt.plot(circx,circy,'g-') plt.plot([cx],[cy],'gx',ms=12) if self.ZorY == 'Z': philist,flist=[self.phi_a,self.phi_p,self.phi_n],[self.fa,self.fp,self.fn] elif self.ZorY == 'Y': philist,flist=[self.phi_m,self.phi_s,self.phi_r],[self.fm,self.fs,self.fr] for p,f in zip(philist,flist): if f is not None: xpos=cx+r*cos(p); ypos=cy+r*sin(p); xos=0.2*(xpos-cx); yos=0.2*(ypos-cy) plt.plot([0,xpos],[0,ypos],'co-') ax.annotate('{:.3f} Hz'.format(f), xy=(xpos,ypos), xycoords='data', xytext=(xpos+xos,ypos+yos), textcoords='data', #textcoords='offset points', arrowprops=dict(arrowstyle="->", shrinkA=0, shrinkB=10) ) #plt.xlim(0,0.16) #plt.ylim(-0.1,0.1) plt.axis('equal') if self.ZorY == 'Z': plt.xlabel(r'resistance $R$ in Ohm'); plt.ylabel(r'reactance $X$ in Ohm') if self.ZorY == 'Y': plt.xlabel(r'conductance $G$ in Siemens'); plt.ylabel(r'susceptance $B$ in Siemens') plt.title("fitting the admittance circle with Powell's method") tx1='best fit (fmin_powell):\n' tx1+='center at G+iB = {:.5f} + i*{:.8f}\n'.format(cx,cy) tx1+='radius = {:.5f}; '.format(r) tx1+='residue: {:.2e}'.format(self.resid) txt1=plt.text(-r,cy-1.1*r,tx1,fontsize=8,ha='left',va='top') txt1.set_bbox(dict(facecolor='gray', alpha=0.25)) idxlist=self.to_be_annotated('triple') ofs=self.annotation_offsets(idxlist,factor=0.1,xshift=0.15) for i,j in enumerate(idxlist): xpos,ypos = x[j],y[j]; xos,yos = ofs[i].real,ofs[i].imag ax.annotate('{:.1f} Hz'.format(self.f[j]), xy=(xpos,ypos), xycoords='data', xytext=(xpos+xos,ypos+yos), textcoords='data', #textcoords='offset points', arrowprops=dict(arrowstyle="->", shrinkA=0, shrinkB=10) ) if self.show: plt.show() else: plt.savefig(join(self.sdc.plotpath,'c{}_fitted_{}_circle'.format(self.sdc.case,self.ZorY)+suffix+'.png'), dpi=240) plt.close()
def test_dep(self): xf = arange(0, 425) deps = self.fm.get_dep(xf) plt.plot(xf,deps) plt.gca().set_yticks(self.fm.DEP) plt.gca().set_xticks(self.fm.Y_PC) plt.grid('on') plt.title('Ground x versus depth') plt.xlabel('Ground X (km)') plt.ylabel('depth (km)') plt.axis('equal') plt.gca().invert_yaxis() plt.savefig(join(self.outs_dir, '~Y_PC_vs_deps.png')) plt.close()
def plot(site): tp = np.loadtxt('../post_offsets/%s.post'%site) t = dc.asmjd([ii[0] for ii in tp]) + dc.adjust_mjd_for_plot_date e = [ii[1] for ii in tp] n = [ii[2] for ii in tp] u = [ii[3] for ii in tp] plt.plot_date(t,e,'x-', label = 'eastings') plt.plot(t,n,'x-', label = 'northings') plt.plot(t,u,'x-', label = 'upings') plt.gcf().autofmt_xdate() plt.legend(loc=0) plt.title(site) plt.savefig('%s.png'%site) #plt.show() plt.close()
def plot_earth_model_file_depth_change( earth_model_file, ofig_prefix, ofig_type, if_show = False): em = EarthModelFileReader(earth_model_file) den = em.density dep = em.dep_top _plot_base(dep, den,[300,0],[2.5, 3.6], r'density ($g/cm^3$)') plt.savefig('%s_density.%s'%(ofig_prefix, ofig_type)) if if_show: plt.show() plt.close() shear = em.shear/10**9 _plot_base(dep, shear,[300,0],[15, 110], r'shear modulus ($GPa$)') plt.savefig('%s_shear.%s'%(ofig_prefix, ofig_type)) if if_show: plt.show() plt.close() bulk = em.bulk/10**9 _plot_base(dep, bulk,[300,0],[40, 200], r'bulk modulus ($GPa$)') plt.savefig('%s_bulk.%s'%(ofig_prefix, ofig_type)) if if_show: plt.show() plt.close()
def plot(self): fig = plt.figure(figsize=self.figsize) fig.patch.set_facecolor('white') fig.patch.set_alpha(0) ax = plt.gca() ax.set_title("Consumption\n", fontsize=self.title_size) ax.plot(self.X, self.Y, linewidth=self.line_width, color="black") ax.tick_params(axis='both', which='major', labelsize=self.label_value_size) ax.set_xlabel("t", fontsize=self.label_font_size) ax.set_ylabel("n", fontsize=self.label_font_size) ax.spines['right'].set_color('none') ax.yaxis.set_ticks_position('left') ax.xaxis.set_ticks_position('bottom') ax.spines['top'].set_color('none') plt.savefig(self.fig_name) plt.close()
def short_analysis(data, analysis_file_path, fig_root_name): # Suppose there are two idx for rt for rt_idx in [1, 2]: # Convert your data in array for easier manipulation rt_column_name = "RT {}".format(rt_idx) rt = np.asarray(data[rt_column_name]) rt_mt_column_name = "RT-MT {}".format(rt_idx) rt_mt = np.asarray(data[rt_mt_column_name]) # Look where 'rt' and 'rt_mt' are different to zero cond0 = rt[:] != 0 cond1 = rt_mt[:] != 0 # Combine the two conditions idx = cond0 * cond1 # Use the booleans as index and make a cut in your data rt = rt[idx] rt_mt = rt_mt[idx] # Compute 'mt' mt = rt_mt - rt print("Short analysis.") print("'mt {}' is: \n".format(rt_idx), mt) # Save this in a new 'xlsx' file new_data = dict() new_data["RT{}".format(rt_idx)] = rt new_data["MT{}".format(rt_idx)] = mt write_a_new_file(file_path=analysis_file_path, data=new_data) # Do some plots plt.scatter(mt, rt) plt.xlabel("mt") plt.ylabel("rt") plt.savefig("{}_scatter_rt{}.pdf".format(fig_root_name, rt_idx)) plt.close() plt.hist(mt) plt.xlabel("mt") plt.savefig("{}_hist_mt{}.pdf".format(fig_root_name, rt_idx)) plt.close() plt.hist(rt) plt.xlabel("rt") plt.savefig("{}_hist_rt{}.pdf".format(fig_root_name, rt_idx)) plt.close()
def run(*args): import pkg_resources if args[0] == 'test': TEST_PATH = pkg_resources.resource_filename('confine', 'TEST/') dir_in = TEST_PATH + 'test.csv' f = 'test' lcc_min = 50 lcc_max = 350 else: f = args[0] dir_in = str(raw_input("Where the file is located in? ")) print "You entered: ------", str(f), ' ------' lcc_min = int( raw_input( "Enter the minimum size of LCC, we recommend a number between 30 and 50: " )) lcc_max = int( raw_input( "Enter the maximum size of LCC, we recommend a number between 300 and 500: " )) print '.....loading data.....' import os import pickle import time start_time = time.time() NET_PATH = pkg_resources.resource_filename('confine', 'NET/') id_to_sym = pickle.load(open(NET_PATH + 'id_to_sym_human.p', 'r')) G = pickle.load(open(NET_PATH + 'PPI_2015_raw.p', 'r')) file = open(dir_in, "r") initial_data = file.read().splitlines() file.close() threshold = 0.05 gene = [] pval = [] for row in initial_data: n = row.strip().split(',') p = float(n[1].strip()) g = int(n[0].strip()) if p <= threshold: gene.append(g) pval.append(p) print 'Number of genes with P.val<0.05: ', len(gene) print '.....Identifying disease module.....' data = zip(gene, pval) #--------------------- from func import CONFINE as conf result = conf(data, G, lcc_min, lcc_max) z_list = result[0] pval_cut_list = result[1] sig_Cluster_LCC = result[2] z_score = z_list[result[3]] p_val_cut = pval_cut_list[result[3]] print '--------------------' print 'LCC size: ', len(sig_Cluster_LCC.nodes()) print 'Z-score: ', z_score print 'P.val cut-off: ', p_val_cut print '--------------------' directory_name = f + '_' + str(time.time()) if not os.path.exists(directory_name): os.makedirs(directory_name) b = open(directory_name + '/LCC_' + f + '.txt', "w") for node in sig_Cluster_LCC.nodes(): try: print >> b, str(id_to_sym[int(node)]) + ',' + str(int(node)) except KeyError: print >> b, ' ' + ',' + str(int(node)) b.close() from pylab import plt, matplotlib fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111) #----------------------------------------------------plotting-------- ax.plot(pval_cut_list, z_list, 'o', color='saddlebrown', markersize=4) plt.axvline(x=p_val_cut, color='r', linestyle='--') ax.set_xlabel('P.value cut-off', fontsize=25, fontweight='bold', labelpad=18) ax.set_ylabel('Z-Score', fontsize=25, fontweight='bold', labelpad=18) ax.set_title('LCC' + ' = ' + str(len(sig_Cluster_LCC.nodes())) + ' ,' + ' Z-Score' + ' = ' + str("{0:.3f}".format(round(z_score, 4))), fontsize=20, fontweight='bold') ax.grid(True) plt.ylim(min(z_list) - min(z_list) / 5, max(z_list) + max(z_list) / 3) plt.savefig(directory_name + '/' + f + '.png', dpi=150, bbox_inches='tight') plt.close() print("--- %s seconds ---" % (time.time() - start_time))
def plot_variable(u, name, direc, cmap='gist_yarg', scale='lin', numLvls=12, umin=None, umax=None, tp=False, tpAlpha=0.5, show=True, hide_ax_tick_labels=False, label_axes=True, title='', use_colorbar=True, hide_axis=False, colorbar_loc='right'): """ """ mesh = u.function_space().mesh() v = u.compute_vertex_values(mesh) x = mesh.coordinates()[:, 0] y = mesh.coordinates()[:, 1] t = mesh.cells() d = os.path.dirname(direc) if not os.path.exists(d): os.makedirs(d) if umin != None: vmin = umin else: vmin = v.min() if umax != None: vmax = umax else: vmax = v.max() # countour levels : if scale == 'log': v[v < vmin] = vmin + 1e-12 v[v > vmax] = vmax - 1e-12 from matplotlib.ticker import LogFormatter levels = np.logspace(np.log10(vmin), np.log10(vmax), numLvls) formatter = LogFormatter(10, labelOnlyBase=False) norm = colors.LogNorm() elif scale == 'lin': v[v < vmin] = vmin + 1e-12 v[v > vmax] = vmax - 1e-12 from matplotlib.ticker import ScalarFormatter levels = np.linspace(vmin, vmax, numLvls) formatter = ScalarFormatter() norm = None elif scale == 'bool': from matplotlib.ticker import ScalarFormatter levels = [0, 1, 2] formatter = ScalarFormatter() norm = None fig = plt.figure(figsize=(8, 7)) ax = fig.add_subplot(111) c = ax.tricontourf(x, y, t, v, levels=levels, norm=norm, cmap=pl.get_cmap(cmap)) plt.axis('equal') if tp == True: p = ax.triplot(x, y, t, 'k-', lw=0.25, alpha=tpAlpha) ax.set_xlim([x.min(), x.max()]) ax.set_ylim([y.min(), y.max()]) if label_axes: ax.set_xlabel(r'$x$') ax.set_ylabel(r'$y$') if hide_ax_tick_labels: ax.set_xticklabels([]) ax.set_yticklabels([]) if hide_axis: plt.axis('off') # include colorbar : if scale != 'bool' and use_colorbar: divider = make_axes_locatable(plt.gca()) cax = divider.append_axes(colorbar_loc, "5%", pad="3%") cbar = plt.colorbar(c, cax=cax, format=formatter, ticks=levels) pl.mpl.rcParams['axes.titlesize'] = 'small' tit = plt.title(title) plt.tight_layout() d = os.path.dirname(direc) if not os.path.exists(d): os.makedirs(d) plt.savefig(direc + name + '.pdf') if show: plt.show() plt.close(fig)
Author: Oren Freifeld Email: [email protected] """ import numpy as np import pylab from pylab import plt from of.utils import * import of.plt from of.gpu import CpuGpuArray from pyimg import * from cpab.cpa3d.TransformWrapper import TransformWrapper from of.gpu import GpuTimer plt.close('all') if not inside_spyder(): pylab.ion() def example(tess='I', base=[2, 2, 2], nLevels=1, zero_v_across_bdry=[True] * 3, vol_preserve=False, nRows=100, nCols=100, nSlices=100, use_mayavi=False, eval_v=False, eval_cell_idx=False):
def main(args=sys.argv[1:]): # there are some cases when this script is run on systems without DISPLAY variable being set # in such case matplotlib backend has to be explicitly specified # we do it here and not in the top of the file, as inteleaving imports with code lines is discouraged import matplotlib matplotlib.use('Agg') from pylab import plt, ylabel, grid, xlabel, array parser = argparse.ArgumentParser() parser.add_argument("rst_file", help="location of rst file in TRiP98 format", type=str) parser.add_argument("output_file", help="location of PNG file to save", type=str) parser.add_argument("-s", "--submachine", help="Select submachine to plot.", type=int, default=1) parser.add_argument("-f", "--factor", help="Factor for scaling the blobs. Default is 1000.", type=int, default=1000) parser.add_argument("-v", "--verbosity", action='count', help="increase output verbosity", default=0) parser.add_argument('-V', '--version', action='version', version=pt.__version__) args = parser.parse_args(args) file = args.rst_file sm = args.submachine fac = args.factor a = pt.Rst() a.read(file) # convert data in submachine to a nice array b = a.machines[sm] x = [] y = [] z = [] for _x, _y, _z in b.raster_points: x.append(_x) y.append(_y) z.append(_z) title = "Submachine: {:d} / {:d} - Energy: {:.3f} MeV/u".format( sm, len(a.machines), b.energy) print(title) cc = array(z) cc = cc / cc.max() * fac fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(x, y, c=cc, s=cc, alpha=0.75) ylabel("mm") xlabel("mm") grid(True) plt.title(title) plt.savefig(args.output_file) plt.close()
def plot_variable(u, name, direc, cmap=cmaps.parula, scale='lin', numLvls=100, umin=None, umax=None, \ tp=False, \ tpAlpha=1.0, show=False, hide_ax_tick_labels=False, label_axes=True, title='', use_colorbar=True, hide_axis=False, colorbar_loc='right'): """ show -- whether to show the plot on the screen tp -- show triangle cmap -- colors: gist_yarg - grey gnuplot, hsv, gist_ncar jet - typical colors """ mesh = u.function_space().mesh() v = u.compute_vertex_values(mesh) x = mesh.coordinates()[:,0] y = mesh.coordinates()[:,1] t = mesh.cells() if not os.path.isdir( direc ): os.makedirs(direc) full_path = os.path.join(direc, name) if umin != None: vmin = umin else: vmin = v.min() if umax != None: vmax = umax else: vmax = v.max() # countour levels : if scale == 'log': v[v < vmin] = vmin + 1e-12 v[v > vmax] = vmax - 1e-12 from matplotlib.ticker import LogFormatter levels = np.logspace(np.log10(vmin), np.log10(vmax), numLvls) tick_numLvls = min( numLvls, 8 ) tick_levels = np.logspace(np.log10(vmin), np.log10(vmax), tick_numLvls) formatter = LogFormatter(10, labelOnlyBase=False) norm = colors.LogNorm() elif scale == 'lin': v[v < vmin] = vmin + 1e-12 v[v > vmax] = vmax - 1e-12 from matplotlib.ticker import ScalarFormatter levels = np.linspace(vmin, vmax, numLvls) tick_numLvls = min( numLvls, 8 ) tick_levels = np.linspace(vmin, vmax, tick_numLvls) formatter = ScalarFormatter() norm = None elif scale == 'bool': from matplotlib.ticker import ScalarFormatter levels = [0, 1, 2] formatter = ScalarFormatter() norm = None fig = plt.figure(figsize=(5,5)) ax = fig.add_subplot(111) c = ax.tricontourf(x, y, t, v, levels=levels, norm=norm, cmap=plt.get_cmap(cmap)) plt.axis('equal') if tp == True: p = ax.triplot(x, y, t, '-', lw=0.2, alpha=tpAlpha) ax.set_xlim([x.min(), x.max()]) ax.set_ylim([y.min(), y.max()]) if label_axes: ax.set_xlabel(r'$x$') ax.set_ylabel(r'$y$') if hide_ax_tick_labels: ax.set_xticklabels([]) ax.set_yticklabels([]) if hide_axis: plt.axis('off') # include colorbar : if scale != 'bool' and use_colorbar: divider = make_axes_locatable(plt.gca()) cax = divider.append_axes(colorbar_loc, "5%", pad="3%") cbar = plt.colorbar(c, cax=cax, format=formatter, ticks=tick_levels) tit = plt.title(title) if use_colorbar: plt.tight_layout(rect=[.03,.03,0.97,0.97]) else: plt.tight_layout() plt.savefig( full_path + '.eps', dpi=300) if show: plt.show() plt.close(fig)
def train(n_epochs, _batch_size, start_epoch=0): """ train with fixed batch_size for given epochs make some example plots and save model after each epoch """ global batch_size batch_size = _batch_size # create a dataqueue with the keras facilities. this allows # to prepare the data in parallel to the training sample_dataqueue = GeneratorEnqueuer(generate_real_samples(batch_size), use_multiprocessing=True) sample_dataqueue.start(workers=2, max_queue_size=10) sample_gen = sample_dataqueue.get() # targets for loss function gan_sample_dataqueue = GeneratorEnqueuer( generate_latent_points_as_generator(batch_size), use_multiprocessing=True) gan_sample_dataqueue.start(workers=2, max_queue_size=10) gan_sample_gen = gan_sample_dataqueue.get() # targets for loss function valid = -np.ones((batch_size, 1)) fake = np.ones((batch_size, 1)) dummy = np.zeros((batch_size, 1)) # Dummy gt for gradient penalty bat_per_epo = int(n_samples / batch_size) # we need to call the discriminator once in order # to initialize the input shapes [X_real, cond_real] = next(sample_gen) latent = np.random.normal(size=(batch_size, latent_dim)) critic_model.predict([X_real, cond_real, latent]) for i in trange(n_epochs): epoch = 1 + i + start_epoch # enumerate batches over the training set for j in trange(bat_per_epo): for _ in range(n_disc): # fetch a batch from the queue [X_real, cond_real] = next(sample_gen) latent = np.random.normal(size=(batch_size, latent_dim)) d_loss = critic_model.train_on_batch( [X_real, cond_real, latent], [valid, fake, dummy]) # we get for losses back here. average, valid, fake, and gradient_penalty # we want the average of valid and fake d_loss = np.mean([d_loss[1], d_loss[2]]) # train generator # prepare points in latent space as input for the generator [latent, cond] = next(gan_sample_gen) # update the generator via the discriminator's error g_loss = generator_model.train_on_batch([latent, cond], valid) # summarize loss on this batch print(f'{epoch}, {j + 1}/{bat_per_epo}, d_loss {d_loss}' + \ f' g:{g_loss} ') # , d_fake:{d_loss_fake} d_real:{d_loss_real}') if np.isnan(g_loss) or np.isnan(d_loss): raise ValueError('encountered nan in g_loss and/or d_loss') hist['d_loss'].append(d_loss) hist['g_loss'].append(g_loss) # plot generated examples plt.figure(figsize=(25, 25)) n_plot = 30 X_fake, cond_fake = generate_fake_samples(n_plot) for iplot in range(n_plot): plt.subplot(n_plot, 25, iplot * 25 + 1) plt.imshow(cond_fake[iplot, :, :].squeeze(), cmap=plt.cm.gist_earth_r, norm=LogNorm(vmin=0.01, vmax=1)) plt.axis('off') for jplot in range(1, 24): plt.subplot(n_plot, 25, iplot * 25 + jplot + 1) plt.imshow(X_fake[iplot, jplot, :, :].squeeze(), vmin=0, vmax=1, cmap=plt.cm.hot_r) plt.axis('off') plt.colorbar() plt.suptitle(f'epoch {epoch:04d}') plt.savefig( f'{plotdir}/fake_samples_{params}_{epoch:04d}_{j:06d}.{plot_format}' ) # plot loss plt.figure() plt.plot(hist['d_loss'], label='d_loss') plt.plot(hist['g_loss'], label='g_loss') plt.ylabel('batch') plt.legend() plt.savefig(f'{plotdir}/training_loss_{params}.{plot_format}') pd.DataFrame(hist).to_csv('hist.csv') plt.close('all') generator.save(f'{outdir}/gen_{params}_{epoch:04d}.h5') critic.save(f'{outdir}/disc_{params}_{epoch:04d}.h5')
def represent_results(backup, parameters, display=True, fig_name=None): from pylab import plt exchanges_list = backup["exchanges"] mean_utility_list = backup["utility"] n_exchanges_list = backup["n_exchanges"] accept_third_object = backup["third_good_acceptance"] # What is common to all subplots fig = plt.figure(figsize=(25, 12)) fig.patch.set_facecolor('white') x = np.arange(len(exchanges_list)) n_lines = 2 n_columns = 3 # First subplot ax = plt.subplot(n_lines, n_columns, 1) ax.set_title("Proportion of each type of exchange according to time \n") y0 = [] y1 = [] y2 = [] for exchanges in exchanges_list: y0.append(exchanges[0]) y1.append(exchanges[1]) y2.append(exchanges[2]) ax.plot(x, y0, label="Exchange (1, 2)", linewidth=2) ax.plot(x, y1, label="Exchange (1, 3)", linewidth=2) ax.plot(x, y2, label="Exchange (2, 3)", linewidth=2) ax.legend() # Second subplot ax = plt.subplot(n_lines, n_columns, 2) ax.set_title("Utility average according to time \n") ax.plot(x, mean_utility_list, linewidth=2) # Third subplot ax = plt.subplot(n_lines, n_columns, 3) ax.set_title("Total number of exchanges according to time \n") ax.plot(x, n_exchanges_list, linewidth=2) # Fourth subplot ax = plt.subplot(n_lines, n_columns, 4) ax.set_title( "Frequency of acceptance of the third good according to time \n") ax.plot(x, [i[0] for i in accept_third_object], label="Agent I ({}, {})".format( parameters["model"].roles[0, 0] + 1, parameters["model"].roles[0, 1] + 1), linewidth=2) ax.plot(x, [i[1] for i in accept_third_object], label="Agent II ({}, {})".format( parameters["model"].roles[1, 0] + 1, parameters["model"].roles[1, 1] + 1), linewidth=2) ax.plot(x, [i[2] for i in accept_third_object], label="Agent III ({}, {})".format( parameters["model"].roles[2, 0] + 1, parameters["model"].roles[2, 1] + 1), linewidth=2) ax.legend() # Fifth subplot ind = np.arange(3) width = 0.5 ax = plt.subplot(n_lines, n_columns, 5) ax.set_title("Storing costs \n") if parameters["storing_costs"].shape == (3, ): ax.bar(ind, parameters["storing_costs"], width) else: ax.bar(ind, parameters["storing_costs"][0], width / 3, label="Agent I") ax.bar(ind + width * (1 / 3), parameters["storing_costs"][1], width / 3, label="Agent II", color="green") ax.bar(ind + width * (2 / 3), parameters["storing_costs"][2], width / 3, label="Agent III", color="red") ax.legend() # Hide the right and top spines ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) # Only show ticks on the left and bottom spines ax.yaxis.set_ticks_position('left') ax.xaxis.set_ticks_position('none') ax.set_xticks(ind + width / 2) ax.set_xticklabels(('$c_1$', '$c_2$', '$c_3$'), fontsize=16) # Sixth subplot ax = plt.subplot(n_lines, n_columns, 6) ax.set_title("Parameters") ax.axis('off') # ax.set_xticks([]), ax.set_yticks([]) msg = \ "Model: {}; \n \n" \ "Role repartition: {}; \n \n " \ "Learning rate: {}; \n \n" \ "Softmax temp: {}; \n \n" \ "Trials: {}. \n \n" \ .format( parameters["model"], parameters["role_repartition"], parameters["alpha"], parameters["temp"], parameters["t_max"] ) ax.text(0.5, 0.5, msg, ha='center', va='center', size=12) # Saving if fig_name: plt.savefig(fig_name) # Display if display: plt.show() plt.close()
def test_plot_fault(self): plot = MapPlotFault(self.file_fault) plot.plot_fault() plt.savefig(join(self.outs_dir, 'plot_fault.png')) plt.close()
def plot_main_fig(self): # What is common to all subplots fig = plt.figure(figsize=(25, 12)) fig.patch.set_facecolor('white') n_lines = 2 n_columns = 3 x = np.arange(self.parameters["t_max"]) # First subplot ax = plt.subplot(n_lines, n_columns, 1) ax.set_title( "Proportion of each type of exchange according to time \n") type_of_exchanges = sorted([i for i in self.exchanges_list[0].keys()]) y = [] for i in range(len(type_of_exchanges)): y.append([]) for t in range(self.parameters["t_max"]): for exchange_idx in range(len(type_of_exchanges)): y[exchange_idx].append( self.exchanges_list[t][type_of_exchanges[exchange_idx]]) ax.set_ylim([-0.02, 1.02]) for exchange_idx in range(len(type_of_exchanges)): ax.plot(x, y[exchange_idx], label="Exchange {}".format( type_of_exchanges[exchange_idx]), linewidth=2) ax.legend() # Second subplot ax = plt.subplot(n_lines, n_columns, 2) ax.set_title("Consumption average according to time \n") ax.plot(x, self.mean_utility_list, linewidth=2) # Third subplot ax = plt.subplot(n_lines, n_columns, 3) ax.set_title("Total number of exchanges according to time \n") ax.plot(x, self.n_exchanges_list, linewidth=2) # Fourth subplot ax = plt.subplot(n_lines, n_columns, 4) ax.set_title( "Frequency at which a good is accepted as a mean of exchange \n") ax.set_ylim([-0.02, 1.02]) for i in range(self.n_goods): ax.plot(x, [j[i] for j in self.good_accepted_as_medium], label="Good {}".format(i), linewidth=2) ax.legend() # Fifth subplot ind = np.arange(self.n_goods) width = 0.5 ax = plt.subplot(n_lines, n_columns, 5) ax.set_title("Storing costs \n") ax.bar(ind, self.parameters["storing_costs"], width) # Hide the right and top spines ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) # Only show ticks on the left and bottom spines ax.yaxis.set_ticks_position('left') ax.xaxis.set_ticks_position('none') ax.set_xticks(ind + width / 2) x_labels = [] for i in range(self.n_goods): x_labels.append('$c_{}$'.format(i)) ax.set_xticklabels(x_labels, fontsize=16) # Sixth subplot ax = plt.subplot(n_lines, n_columns, 6) ax.set_title("Parameters") ax.axis('off') if "agent_parameters" not in self.parameters: self.parameters["agent_parameters"] = None msg = \ "Agent model: {}; \n \n" \ "Agent parameters: \n {}; \n \n" \ "Repartition of roles: {}; \n \n " \ "Trials: {}. \n \n".format( self.parameters["agent_model"].name, self.parameters["agent_parameters"], self.parameters["repartition_of_roles"], self.parameters["t_max"] ) ax.text(0.5, 0.5, msg, ha='center', va='center', size=12) plt.savefig(self.main_figure_name) plt.close()
def plot_customer_firm_choices(self, period=50): # Data positions = self.results["positions"][-period:] prices = self.results["prices"][-period:] n_firms = len(self.results["positions"][0]) customer_firm_choices = self.results["customer_firm_choices"][-period:] t_max, n_positions = customer_firm_choices.shape # Create fig and axes fig = plt.figure(figsize=(t_max, n_positions)) gs = gridspec.GridSpec(24, 20) ax = fig.add_subplot(gs[:20, :20]) ax2 = fig.add_subplot(gs[-1, 8:12]) # Prepare normalization for 'imshow' mapping = dict([(x, y) for x, y in zip(np.arange(-1, n_firms), np.linspace(0, 1, n_firms + 1))]) f_mapping = lambda x: mapping[x] # Function adapted for numpy array v_func = np.vectorize(f_mapping) # Format customer choices (reordering + normalization) formatted_customer_firm_choices = v_func(customer_firm_choices.T[::-1]) # Colors for different firms firm_colors = cm.ScalarMappable(norm=None, cmap="gist_rainbow").to_rgba( np.linspace(0, 1, n_firms)) # Prepare customized colormap colors = np.zeros((n_firms + 1, 4)) colors[0] = 1, 1, 1, 1 # White colors[1:] = firm_colors cmap_name = "manual_colormap" n_bins = n_firms + 1 manual_cm = LinearSegmentedColormap.from_list(cmap_name, colors, N=n_bins) # Plot customer choices ax.imshow(formatted_customer_firm_choices, interpolation='nearest', origin="lower", norm=NoNorm(), alpha=0.5, cmap=manual_cm) # Offsets for positions plot and prices plot offsets = np.linspace(-0.25, 0.25, n_firms) # Plot positions for i in range(n_firms): ax.plot(np.arange(t_max) + offsets[i], n_positions - positions[:, i], "o", color=firm_colors[i], markersize=10) # Plot prices for t in range(t_max): for i in range(n_firms): ax.text(t + offsets[i] - 0.1, n_positions - positions[t, i] + 0.2, prices[t, i]) # Customize axes ax.set_xlim(-0.5, t_max - 0.5) ax.set_ylim(-0.5, n_positions - 0.5) # Add grid (requires to customize axes) ax.set_yticks(np.arange(0.5, n_positions - 0.5, 1), minor=True) ax.set_xticks(np.arange(0.5, t_max - 0.5, 1), minor=True) ax.grid(which='minor', axis='y', linewidth=2, linestyle=':', color='0.75') ax.grid(which='minor', axis='x', linewidth=2, linestyle='-', color='0.25') # After positioning grid, replace ticks for placing labels ax.set_xticks(range(t_max)) ax.set_yticks(range(n_positions)) # Top is position 1. ax.set_yticklabels(np.arange(1, n_positions + 1)[::-1]) # Set axes labels ax.set_xlabel('t', fontsize=14) ax.set_ylabel('Position', fontsize=14) # Remove ticks ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') # Legend possibilities = v_func(np.arange(-1, n_firms)) ax2.imshow(np.atleast_2d(possibilities), interpolation='nearest', origin="lower", norm=NoNorm(), cmap=manual_cm) # Customize ticks ax2.xaxis.set_ticks_position('none') ax2.yaxis.set_ticks_position('none') ax2.set_yticks([]) lab = [str(i) for i in np.arange(-1, n_firms)] ax2.set_xticks(np.arange(n_firms + 1)) ax2.set_xticklabels(lab) plt.savefig(self.format_fig_name("customers_choices")) plt.close()
def test_plot_incr_slip_file(self): plot = MapPlotFault(self.file_fault) plot.plot_incr_slip_file(self.file_incr_slip, 0) plt.savefig(join(self.outs_dir, 'plot_incr_slip_file.png')) plt.close()
def test_plot_slip_contours(self): ep = EpochalIncrSlip(self.file_incr_slip) plot = MapPlotFault(self.file_fault) plot.plot_slip_contours(ep(0), colors='k') plt.savefig(join(self.outs_dir, 'plot_slip_contours.png')) plt.close()
def calculate(self): s_corr = [] l2_norms = [] s_binary = [] self.emitters_set = [] self.em_nr = [] imdata = Simulate.open_image(input_file) imshape = imdata.shape print imshape self.xsize = basic_resolution * imshape[0] self.ysize = basic_resolution * imshape[1] self.area = self.xsize * self.ysize self.maxfreq = 0.5 * math.sqrt(2) / basic_resolution im_out = numpy.zeros([imshape[0], imshape[1]]) xmax = imshape[0] - 1 ymax = imshape[1] - 1 while len(self.emitters_set) < max_emitters_nr: x_em = random.uniform(0, xmax) y_em = random.uniform(0, ymax) x_coord = int(round(x_em, 0)) y_coord = int(round(y_em, 0)) prob = random.uniform(0, 1) if imdata[x_coord, y_coord] > prob: self.emitters_set.append( self.emitter(x_em, y_em, self.accuracy)) lem = len(self.emitters_set) if (lem % 10000 == 0): print "Emitters added:", lem pt = max_emitters_nr / frame_nr for current_frame in range(frame_nr): maxem = self.frame_to_emm_nr[current_frame] im_out = numpy.zeros([imshape[0], imshape[1]]) print maxem for em in self.emitters_set[:maxem]: for dx in self.em_range: for dy in self.em_range: xi = em.xr + dx yi = em.yr + dy try: #print dx,dy,gauss(dx,dy) im_out[xi, yi] = im_out[xi, yi] + self.funct(dx, dy) except (IndexError): pass coeff = numpy.corrcoef(imdata.flatten(), im_out.flatten())[0][1] print "Correlation coeff.:", coeff threshold_global_otsu = threshold_otsu(imdata) global_otsu = numpy.array(imdata >= threshold_global_otsu, dtype=numpy.int) threshold_global_otsu_out = threshold_otsu(im_out) global_otsu_out = numpy.array(im_out >= threshold_global_otsu_out, dtype=numpy.int) diff = numpy.abs(numpy.subtract(global_otsu, global_otsu_out)) binary = 1.0 - numpy.mean(diff) print "Binary agreement:", binary imdata_std = numpy.std(imdata) imout_std = numpy.std(im_out) imdata_normed = numpy.multiply( 1.0 / imdata_std, numpy.subtract(imdata, -numpy.mean(imdata))) imout_normed = numpy.multiply( 1.0 / imout_std, numpy.subtract(im_out, -numpy.mean(im_out))) l2norm = numpy.sqrt( numpy.mean( numpy.power(numpy.subtract(imdata_normed, imout_normed), 2))) print "L2norm:", l2norm if runs_nr == 1: self.ft_data.append( numpy.abs(phase_agreement(imdata_normed, imout_normed))) l2_norms.append(l2norm) s_corr.append(coeff) s_binary.append(binary) self.em_nr.append(maxem) if dump_plots: fig2 = plt.figure(figsize=[20, 20]) ax2 = fig2.add_subplot(111) ax2.imshow(im_out) ax2.xaxis.set_major_formatter( mpl.ticker.FuncFormatter(self.mjrFormatter)) ax2.yaxis.set_major_formatter( mpl.ticker.FuncFormatter(self.mjrFormatter)) fig2.savefig( os.path.join(self.subdir, "figure" + str(maxem) + ".tif")) scipy.misc.imsave( os.path.join(self.subdir, "output" + str(maxem) + ".tif"), im_out) plt.close(fig2) fig5 = plt.figure(figsize=[20, 20]) ax5 = fig5.add_subplot(111) ax5.imshow(global_otsu_out, cmap=self.cmapr, alpha=0.5) ax5.imshow(global_otsu, cmap=self.cmapb, alpha=0.7) ax5.yaxis.set_major_formatter( mpl.ticker.FuncFormatter(self.mjrFormatter)) ax5.xaxis.set_major_formatter( mpl.ticker.FuncFormatter(self.mjrFormatter)) fig5.savefig( os.path.join(self.subdir, "binary" + str(maxem) + ".tif")) plt.close(fig5) self.corr.append(s_corr) self.binary.append(s_binary) self.l2_norms.append(l2_norms) self.imdata = imdata self.im_out = im_out self.diff = [global_otsu, global_otsu_out]
def display_animation(anim, fps=20): plt.close(anim._fig) return HTML(anim_to_html(anim, fps=fps))
def plot(results, parameters, fig_name): # What is common to all subplots fig = plt.figure(figsize=(25, 12)) fig.patch.set_facecolor('white') line_width = 2 n_lines = 3 n_columns = 3 counter = it.count(1) # ----- FOR EACH GENERATION ------ # # FITNESS x = range(len(results["fitness"])) y = results["fitness"] ax = plt.subplot(n_lines, n_columns, next(counter)) ax.set_title("Fitness average\naccording to number of generations\n") ax.plot(x, y, linewidth=line_width) # PROPORTION OF EACH TYPE OF EXCHANGE x_max = len(results["exchanges"]) x = range(x_max) ax = plt.subplot(n_lines, n_columns, next(counter)) ax.set_title( "Proportion of each type of exchange\naccording to number of generations\n" ) type_of_exchanges = sorted([i for i in results["exchanges"][0].keys()]) y = [] for i in range(len(type_of_exchanges)): y.append([]) for i in range(x_max): for exchange_idx in range(len(type_of_exchanges)): y[exchange_idx].append( results["exchanges"][i][type_of_exchanges[exchange_idx]]) ax.set_ylim([-0.02, 1.02]) for exchange_idx in range(len(type_of_exchanges)): ax.plot(x, y[exchange_idx], label="Exchange {}".format(type_of_exchanges[exchange_idx]), linewidth=line_width) ax.legend(fontsize=8) # NUMBER OF EXCHANGES GENERATION x = range(len(results["n_exchanges"])) y = results["n_exchanges"] ax = plt.subplot(n_lines, n_columns, next(counter)) ax.set_title( "Total number of exchanges\naccording to number of generations\n") ax.plot(x, y, linewidth=line_width) # NUMBER OF INTERVENTION OF EACH GOOD x_max = len(results["n_exchanges"]) x = range(x_max) y = [] for i in range(len(results["n_goods_intervention"][0].keys())): y.append([]) for i in range(x_max): for key in results["n_goods_intervention"][0].keys(): y[key].append(results["n_goods_intervention"][i][key]) ax = plt.subplot(n_lines, n_columns, next(counter)) ax.set_title( "Number of interventions of each good\naccording to number of generations\n" ) for key in results["n_goods_intervention"][0].keys(): ax.plot(x, y[key], label="Good {}".format(key), linewidth=line_width) ax.legend(fontsize=8) # DIVERSITY OF PRODUCTION x = range(len(results["production_diversity"])) y = results["production_diversity"] ax = plt.subplot(n_lines, n_columns, next(counter)) ax.set_title("Production diversity\naccording to number of generations\n") ax.plot(x, y, linewidth=line_width) # N PRODUCERS n_goods = len(results["n_producers"][0]) ax = plt.subplot(n_lines, n_columns, next(counter)) ax.set_title("Number of producers for each good \n") for i in range(n_goods): y = [j[i] for j in results["n_producers"]] x = range(len(y)) ax.plot(x, y, linewidth=line_width, label="Good {}".format(i)) ax.legend(fontsize=8) # GLOBAL PRODUCTION n_goods = len(results["production"][0]) ax = plt.subplot(n_lines, n_columns, next(counter)) ax.set_title("Global production for each good \n") for i in range(n_goods): y = [j[i] for j in results["production"]] x = range(len(y)) ax.plot(x, y, linewidth=line_width, label="Good {}".format(i)) ax.legend(fontsize=8) # ------ PARAMETERS ----- # # 5th subplot: PARAMETERS ax = plt.subplot(n_lines, n_columns, next(counter)) ax.set_title("Parameters") ax.axis('off') msg = "" for key in sorted(parameters.keys()): msg += "{}: {}; \n".format(key, parameters[key]) ax.text(0.5, 0.5, msg, ha='center', va='center', size=12) plt.tight_layout() plt.savefig(fig_name) plt.close()
def test_plot_fault(self): plot = MapPlotSlab() plot.plot_top() plt.savefig(join(this_test_path, '~outs/plot_slab_top.png')) plt.close()
def chutuyuezhexian(ds, riqienddate, xiangmu, cum=False, quyu='', leixing='', pinpai='', nianshu=3, imgpath=dirmainpath / 'img'): """ 月度(全年,自然年度)累积对比图,自最早日期起,默认3年 :param ds: 数据表,必须用DateTime做index :param riqienddate: 数据记录的最近日期,可以是DateTIme的各种形式,只要pd能识别成功,形如2017-10-06 :param xiangmu: 主题,画图时写入标题 :param cum: :param quyu: 销售区域或区域聚合(分部) :param leixing: 终端类型 :param pinpai: :param nianshu: 用来对比的年份数,从当前年份向回数 :param imgpath: 图片存储路径 :return: """ # print(df.tail(10)) # monthcur = riqienddate + MonthBegin(-1) # 2017-10-01 nianshushiji = ds.index.max().year - ds.index.min().year + 1 if nianshushiji > nianshu: nianshushiji = nianshu nianlist = [] for i in range(nianshushiji): nianlist.append( riqienddate + YearBegin(-(i + 1))) # 2017-01-01,2016-01-01,2015-01-01 # if xiangmu == '退货客户数' : # print(df) dfn = pd.DataFrame(ds) # 取出日期索引的数据列 # 分年份生成按照每天日期重新索引的数据列 dslist = [] for i in range(nianshushiji): # dfnian = pd.DataFrame() if i == 0: periods = int(riqienddate.strftime('%j')) else: periods = 365 dstmp = dfn.reindex(pd.date_range( (riqienddate + YearBegin(-1 - (1 * i))), periods=periods, freq='D'), fill_value=0) # if xiangmu == '退货客户数': # print(dstmp.tail(30)) if cum: dfnian = dstmp.resample('M').sum() else: dfnian = dstmp.resample('M').max() dfnian.columns = ['%04d' % nianlist[i].year] dfnian.index = range(len(dfnian.index)) dslist.append(dfnian) # 连接年份DataFrame if len(dslist) == 0: log.info('年度对比数据为空!') return None dfy = pd.DataFrame(dslist[0]) # 0,0 1 2 3 4 for i in range(1, len(dslist)): # 1 2 3 4 dfy = dfy.join(dslist[i], how='outer') # 0 1 2 3 4 # print(dfy) zuobiao = pd.Series(range(1, len(dfy.index) + 1)) # 从1开始生成序列,配合月份,日期的话是自动从1开始的,不用特别处理 dfy.index = zuobiao.apply(lambda x: '%02d' % x) nianyue = '%04d年' % riqienddate.year biaoti = leixing + quyu + pinpai + nianyue + xiangmu dslistmax = [] # dslistabs = [abs(x) for x in dslist] dfyabs = dfy.apply(lambda x: abs(x)) # print(dfyabs.max()) for clname in dfyabs.columns: dslistmax.append(dfyabs[clname].max()) # 取绝对值的最大,涵盖退货的负值金额 # print(type(dslistmax)) # print(dslistmax) # global ywananchor imglist = [] if cum: cumstr = '月累积' dfjieguo = dfy.cumsum() dfjieguo.plot(title=biaoti + cumstr) if max(map(abs, dslistmax)) > ywananchor: plt.gca().yaxis.set_major_formatter( FuncFormatter(lambda x, pos: "%d万" % int(x / 10000)) ) # 纵轴主刻度文本用y_formatter函数计算 biaozhukedu(dfjieguo, '%02d' % riqienddate.month) imgpathstr = str(imgpath) if not os.path.exists(imgpathstr): os.mkdir(imgpathstr) log.info('%s不存在,将被创建' % imgpathstr) itemimgpath = str(imgpath / f'{biaoti}{cumstr}.png') plt.savefig(itemimgpath) imglist.append(itemimgpath) plt.close() cumstr = '月折线' dfy.plot(title='%s%s' % (biaoti, cumstr)) if max(map(abs, dslistmax)) > ywananchor: plt.gca().yaxis.set_major_formatter( FuncFormatter(lambda x, pos: "%d万" % int(x / 10000)) ) # 纵轴主刻度文本用y_formatter函数计算 biaozhukedu(dfy, '%02d' % riqienddate.month) itemimgpath = str(imgpath / f'{biaoti}{cumstr}.png') plt.savefig(itemimgpath) imglist.append(itemimgpath) plt.close() return imglist
label=r'vel ($yr^{-1}$)') #ax2.set_xlim([0,10]) ax2.set_ylabel(r'$yr^{-1}$') #ax2.set_ylim([-1e-6, 2e-6]) ax2.legend(loc=0) ax2.set_position(pos2) align_yaxis(ax1, 0, ax2, 0) plt.title('%s - %s'%(site, cmpt)) plt.savefig('%s_%s.png'%(site, cmpt)) plt.xlabel('year') plt.grid('on') ########### plt.show() plt.close()
def chuturizhexian(df, riqienddate, xiangmu, cum=False, quyu='', leixing='', pinpai='', imgpath=dirmainpath / 'img'): """ 日数据(月份)累积对比图,当月、环比、同期比 riqienddate形如2017-12-08,代表数据结束点的日期 :param df: :param riqienddate: :param xiangmu: :param cum: :param quyu: :param leixing: :param pinpai: :param imgpath: :return: """ riqicurmonthfirst = riqienddate + MonthBegin(-1) # 日期格式的当月1日 riqibeforemonthfirst = riqienddate + MonthBegin(-2) # 日期格式的上月1日 riqilastmonthfirst = riqienddate + MonthBegin(-13) # 日期格式的去年当月1日 tianshu = (riqienddate + MonthEnd(-1)).day # 当月的天数 # print(df) ds = pd.DataFrame(df) datesb = pd.date_range(riqibeforemonthfirst, periods=tianshu, freq='D') # 上月日期全集,截止到当月最后一天为止 if ds.index.min() <= datesb.max(): # 存在有效数据则生成按全月每天索引的DataFrame,否则置空 ds1 = ds.reindex(datesb, fill_value=0) # 重新索引,补全所有日期,空值用0填充 ds1.index = (range(1, len(datesb) + 1)) # 索引天日化 ds1.columns = f'{riqibeforemonthfirst.year:04d}{riqibeforemonthfirst.month:02d}' + ds1.columns # 列命名,形如201709 else: ds1 = pd.DataFrame() datesl = pd.date_range(riqilastmonthfirst, periods=tianshu, freq='D') # 处理去年当月数据 if ds.index.min() <= datesl.max(): # 存在有效数据则生成按全月每天索引的DataFrame,否则置空 ds3 = ds.reindex(datesl, fill_value=0) ds3.index = range(1, len(datesl) + 1) ds3.columns = ( '%04d%02d' % (riqilastmonthfirst.year, riqilastmonthfirst.month)) + ds3.columns else: ds3 = pd.DataFrame() datesc = pd.date_range(riqicurmonthfirst, periods=riqienddate.day, freq='D') # 处理当月数据,至截止日期 if ds.index.min() <= datesc.max( ): # 存在有效数据则生成按按照每天索引的DataFrame,否则置空并退出,避免空转 ds2 = ds.reindex(datesc, fill_value=0) ds2.index = range(1, len(datesc) + 1) ds2.columns = ( '%04d%02d' % (riqicurmonthfirst.year, riqicurmonthfirst.month)) + ds2.columns else: return dff = ds2.join(ds1, how='outer').join(ds3, how='outer') nianyue = '%04d%02d' % (riqicurmonthfirst.year, riqicurmonthfirst.month) biaoti = leixing + quyu + pinpai + nianyue + xiangmu # clnames = [] # for ct in range(0, len(dff.columns), 2): # clnames.append(dff.columns[ct]) dfc = dff if cum: dfc = dfc.cumsum() # 数据累积求和 biaoti = biaoti + '日累积' # print(dfc) dfc.plot(title=biaoti) # plt.ylim(0) #设定纵轴从0开始 biaozhukedu(dfc, riqienddate.day) imgsavepath = imgpath / (biaoti + '(日累积月).png') touchfilepath2depth(imgsavepath) plt.savefig(str(imgsavepath)) plt.close() imglistctrz = list() imglistctrz.append(str(imgsavepath)) return imglistctrz
def test_Y_PC_vs_DEP(self): plot_fault_framework(self.fm) plt.savefig(join(self.outs_dir, '~dep_Y_PC.png')) plt.savefig(join(self.outs_dir, '~dep_Y_PC.pdf')) plt.close()
def histbin(self, var1, var2): if var1 == "customer_extra_view_choices" and var2 == "delta_position": x = np.asarray(self.stats.data[var1]) y = np.asarray(self.stats.data[var2]) n_bin = 10 a = np.linspace(0, 10, n_bin + 1) b = np.zeros(n_bin) for i in range(n_bin): yo = list() for idx, xi in enumerate(x): if a[i] <= xi < a[i + 1]: yo.append(y[idx]) b[i] = np.median(yo) if len(yo) else 0 # ----- # fig = plt.figure() ax = fig.add_subplot(1, 1, 1) plt.xlim(self.range_var[var1]) plt.ylim(self.range_var[var2]) plt.xlabel(self.format_label(var1)) plt.ylabel(self.format_label(var2)) ax.bar(a[:-1] + (a[1] - a[0]) / 2, b, a[1] - a[0], color='grey') plt.savefig("{}/hist_median_{}_{}.pdf".format( self.fig_folder, var1, var2)) # --- # if self.display: plt.show() plt.close() # ---- # b = np.zeros(n_bin) c = np.zeros(n_bin) for i in range(n_bin): yo = list() for idx, xi in enumerate(x): if a[i] <= xi < a[i + 1]: yo.append(y[idx]) b[i] = np.mean(yo) if len(yo) else 0 c[i] = np.std(yo) if len(yo) else 0 # ----- # fig = plt.figure() ax = fig.add_subplot(1, 1, 1) plt.xlim(self.range_var[var1]) plt.ylim(self.range_var[var2]) plt.xlabel(self.format_label(var1)) plt.ylabel(self.format_label(var2)) ax.bar(a[:-1] + (a[1] - a[0]) / 2, b, a[1] - a[0], color='grey', yerr=c) plt.savefig("{}/hist_mean_{}_{}.pdf".format( self.fig_folder, var1, var2)) # --- # if self.display: plt.show() plt.close()
## reader = vj.inv.ResultFileReader('../../outs/nrough_06_naslip_11.h5') slip = reader.get_slip() cal = vj.moment.MomentCalculator(fault_file, earth_file) mos, mws = cal.get_afterslip_Mos_Mws(slip) print(mos, mws) epochs = slip.get_epochs() vj.moment.plot_Mos_Mws(epochs, Mos=mos, ylim=[1e21, 1.3e22], yticks=[0.2e22, 0.4e22, 0.6e22, .8e22, 1e22, 1.2e22]) plt.savefig('mos_mws_nrough_06_naslip_11.pdf') plt.show() plt.close() ## reader = vj.inv.ResultFileReader('../../outs/nrough_06_naslip_10.h5') slip = reader.get_slip() cal = vj.moment.MomentCalculator(fault_file, earth_file) mos, mws = cal.get_afterslip_Mos_Mws(slip) epochs = slip.get_epochs() vj.moment.plot_Mos_Mws(epochs, Mos=mos, ylim=[1e21, 1.3e22], yticks=[0.2e22, 0.4e22, 0.6e22, .8e22, 1e22, 1.2e22]) plt.savefig('mos_mws_nrough_06_naslip_10.pdf') plt.show() plt.close()
def distance_over_fov(pool_backup, fig_name): # Create directories if not already existing os.makedirs(os.path.dirname(fig_name), exist_ok=True) # Shortcuts parameters = pool_backup.parameters backups = pool_backup.backups # Look at the parameters n_simulations = len(parameters["seed"]) n_positions = parameters["n_positions"] t_max = parameters["t_max"] # Containers x = np.zeros(n_simulations) y = np.zeros(n_simulations) y_err = np.zeros(n_simulations) z = np.zeros(n_simulations) # How many time steps from the end of the simulation are included in analysis span_ratio = 0.33 # Take last third span = int(span_ratio * t_max) for i, b in enumerate(backups): x[i] = b.parameters.r # Compute the mean distance between the two firms data = np.absolute( b.positions[-span:, 0] - b.positions[-span:, 1]) / n_positions spacing = np.mean(data) spacing_std = np.std(data) y[i] = spacing y_err[i] = spacing_std # Get mean profits z[i] = np.mean(b.profits[-span:, :]) # Plot this fig = plt.figure(figsize=(10, 6)) ax = plt.subplot() # Enhance aesthetics ax.set_xlim(-0.01, 1.01) if max(y) < 0.5: ax.set_ylim(-0.01, 0.51) ax.set_xticks(np.arange(0, 1.1, 0.25)) ax.set_yticks(np.arange(0, 0.51, 0.1)) ax.set_xlabel("$r$") ax.set_ylabel("Mean distance") ax.set_title("Mean distance between firms over $r$") # Display line for indicating 'random' level seed = 123 np.random.seed(seed) random_pos = np.random.random(size=(2, 10 ** 6)) random_dist = np.mean(np.absolute(random_pos[0] - random_pos[1])) ax.axhline(random_dist, color='0.5', linewidth=0.5, linestyle="--", zorder=1) # Do the scatter plot scat = ax.scatter(x, y, c=z, zorder=10, alpha=0.25) # Add a color bar fig.colorbar(scat, label="Profits") # Cut the margins plt.tight_layout() # Save fig plt.savefig(fig_name) plt.close()
def eventloop(shell, init_code=None, init_file=None, console_id=0, pictures=None): """ The GUI Process and Thread running the eventloop """ shell.logdir.find_log_path() qapp = GuiApplication(shell, sys.argv) qapp.setShortCuts() qapp.newWindow('main') #To run in a new thread but on the same gui process #panid = qapp.mainWindow.newThread() qapp.mainWindow.show() desktopGeometry = QDesktopWidget().availableGeometry() qapp.mainWindow.resize(int(desktopGeometry.width() * 3 / 5), int(desktopGeometry.height() * 3 / 5)) qtRectangle = qapp.mainWindow.frameGeometry() centerPoint = desktopGeometry.center() qtRectangle.moveCenter(centerPoint) qapp.mainWindow.move(qtRectangle.topLeft()) # Make sure the gui proxy for the main thread is created qapp.panels.restore_state_from_config('base') # if not config['debug']['skip_restore_perspective']: # if config['default_perspective'] != 'base': # qapp.panels.restore_state_from_config(config['default_perspective']) qapp.processEvents() qapp.cmdserver = CommandServer(shell) if not init_file is None: cmd = {'cmd': 'execute_file', 'args': (init_file, console_id)} qapp.cmdserver.cmd_queue.put(cmd) if not init_code is None: cmd = {'cmd': 'execute_code', 'args': (init_code, console_id)} qapp.cmdserver.cmd_queue.put(cmd) if not pictures is None: cmd = {'cmd': 'open_images', 'args': pictures} qapp.cmdserver.cmd_queue.put(cmd) cmd = config.get('init_command') qapp.cmdserver.cmd_queue.put(cmd) qapp.cmdserver.start_queue_loop(qapp) qapp.cmdserver.start(qapp) exit_code = qapp.exec_() #Kill all the children parent = psutil.Process(os.getpid()) for child in parent.children(recursive=True): child.kill() from pylab import plt plt.close('all') sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ print(f'Exiting {PROGNAME}. Releasing lock.') shell.logdir.release_lock_file()
def run(self, no_plots=False, resume=False, verbose=False, **kwargs): # runs pymultinest # progress = ProgressPrinter( # n_params=self.n_params, # outputfiles_basename=self.basename) # progress.start() pymultinest.run(self.likelihood, self.priors.prior_transform, self.n_params, outputfiles_basename=self.basename, resume=resume, verbose=verbose, **kwargs) json.dump(self.parameter_names, open(self.basename + 'params.json', 'w')) # save parameter names # analyze the output data a = pymultinest.Analyzer(outputfiles_basename=self.basename, n_params=self.n_params) self.analyzer = a # check to see if the required file exists before proceeding # (multinest has a limitation where the file name can only be # of a certain length, so the output file name might not be as # expected). if os.path.exists(self.basename + 'stats.dat'): s = a.get_stats() self.stats = s # the statistics on the chain modes = s['modes'][0] self.mean = modes['mean'] self.sigma = modes['sigma'] self.evidence = s['global evidence'] sigma1 = list() sigma3 = list() marginals = s['marginals'] for i in np.arange(self.n_params): sigma1.append(marginals[i]['1sigma']) sigma3.append(marginals[i]['3sigma']) self.sigma1 = sigma1 self.sigma3 = sigma3 if not (no_plots): # try importing seaborn if it exists: try: seaborn = __import__('seaborn') seaborn.set_style('white') seaborn.set_context("paper", font_scale=1.5, rc={"lines.linewidth": 1.0}) except ImportError: pass plt.figure() plt.plot(self.spectrum.wavelength.value, self.spectrum.flux.value, color='red', label='data') param_dict = OrderedDict([ (key, value) for key, value in zip(self.parameter_names, self.mean) ]) s2 = self.model.evaluate(**param_dict) # plot the mean of the posteriors for the parameters plt.plot(self.spectrum.wavelength.value, s2.flux.value, '-', color='blue', alpha=0.3, label='data') # for posterior_param in a.get_equal_weighted_posterior()[::100,:-1]: # param_dict = OrderedDict([(key, value) for key, value in zip(self.parameter_names, posterior_param)]) # s2 = self.model.evaluate(**param_dict) # plt.plot(self.spectrum.wavelength.value, s2.flux.value, '-', color='blue', alpha=0.3, label='data') plt.savefig(self.basename + 'posterior.pdf') plt.close() self.mkplots()
def plotIce(di, u, name, direc, u2=None, u2_levels=None, u2_color='k', title='', cmap='gist_yarg', scale='lin', umin=None, umax=None, numLvls=12, levels=None, levels_2=None, tp=False, tpAlpha=0.5, contour_type='filled', params=None, extend='neither', show=True, ext='.png', res=150, cb=True, cb_format='%.1e', zoom_box=False, zoom_box_kwargs=None, plot_pts=None, plot_continent=False, cont_plot_params=None, box_params=None): """ Args: :di: DataInput object with desired projection :u: solution to plot; can be either a function on a 2D mesh, or a string key to matrix variable in <di>.data. :name: title of the plot, latex accepted :direc: directory string location to save image. :cmap: colormap to use - see images directory for sample and name :scale: scale to plot, either 'log', 'lin', or 'bool' :numLvls: number of levels for field values :levels: manual levels, if desired. :tp: boolean determins plotting of triangle overlay :tpAlpha: alpha level of triangles 0.0 (transparent) - 1.0 (opaque) :extends: for the colorbar, extend upper range and may be ["neither", "both", "min", "max"]. default is "neither". for plotting the zoom-box, make <zoom_box> = True and supply dict *zoom_box_kwargs* with parameters :zoom: ammount to zoom :loc: location of box :loc1: loc of first line :loc2: loc of second line :x1: first x-coord :y1: first y-coord :x2: second x-coord :y2: second y-coord :scale_font_color: scale font color :scale_length: scale length in km :scale_loc: 1=top, 2=bottom :plot_grid: plot the triangles :axes_color: color of axes :plot_points: dict of points to plot Returns: A sigle *direc/name.ext* in the source directory. """ # get the original projection coordinates and data : if isinstance(u, str): s = "::: plotting %s's \"%s\" field data directly :::" % (di.name, u) print_text(s, '242') vx, vy = np.meshgrid(di.x, di.y) v = di.data[u] elif isinstance(u, Function) \ or isinstance(u, dolfin.functions.function.Function): s = "::: plotting FEniCS Function \"%s\" :::" % name print_text(s, '242') mesh = u.function_space().mesh() coord = mesh.coordinates() fi = mesh.cells() v = u.compute_vertex_values(mesh) vx = coord[:, 0] vy = coord[:, 1] # get the projection info : if isinstance(di, dict) and 'pyproj_Proj' in di.keys() \ and 'continent' in di.keys(): lon, lat = di['pyproj_Proj'](vx, vy, inverse=True) cont = di['continent'] elif isinstance(di, DataInput): lon, lat = di.proj(vx, vy, inverse=True) cont = di.cont else: s = ">>> plotIce REQUIRES A 'DataFactory' DICTIONARY FOR " + \ "PROJECTION STORED AS KEY 'pyproj_Proj' AND THE CONTINENT TYPE " + \ "STORED AS KEY 'continent' <<<" print_text(s, 'red', 1) sys.exit(1) # Antarctica : if params is None: if cont is 'antarctica': w = 5513335.22665 h = 4602848.6605 fig = plt.figure(figsize=(14, 10)) ax = fig.add_subplot(111) lon_0 = 0 lat_0 = -90 # new projection : m = Basemap(ax=ax, width=w, height=h, resolution='h', projection='stere', lat_ts=-71, lon_0=lon_0, lat_0=lat_0) offset = 0.015 * (m.ymax - m.ymin) # draw lat/lon grid lines every 5 degrees. # labels = [left,right,top,bottom] m.drawmeridians(np.arange(0, 360, 20.0), color='black', labels=[True, False, True, True]) m.drawparallels(np.arange(-90, 90, 5.0), color='black', labels=[True, False, True, True]) m.drawmapscale(-130, -68, 0, -90, 400, yoffset=offset, barstyle='fancy') # Greenland : elif cont is 'greenland': w = 1532453.49654 h = 2644074.78236 fig = plt.figure(figsize=(8, 11.5)) ax = fig.add_subplot(111) lon_0 = -41.5 lat_0 = 71 # new projection : m = Basemap(ax=ax, width=w, height=h, resolution='h', projection='stere', lat_ts=71, lon_0=lon_0, lat_0=lat_0) offset = 0.015 * (m.ymax - m.ymin) # draw lat/lon grid lines every 5 degrees. # labels = [left,right,top,bottom] m.drawmeridians(np.arange(0, 360, 5.0), color='black', labels=[False, False, False, True]) m.drawparallels(np.arange(-90, 90, 5.0), color='black', labels=[True, False, True, False]) m.drawmapscale(-34, 60.5, -41.5, 71, 400, yoffset=offset, barstyle='fancy') elif type(params) is dict: llcrnrlat = params['llcrnrlat'] urcrnrlat = params['urcrnrlat'] llcrnrlon = params['llcrnrlon'] urcrnrlon = params['urcrnrlon'] scale_color = params['scale_color'] scale_length = params['scale_length'] scale_loc = params['scale_loc'] figsize = params['figsize'] lat_interval = params['lat_interval'] lon_interval = params['lon_interval'] plot_grid = params['plot_grid'] plot_scale = params['plot_scale'] axes_color = params['axes_color'] dlon = (urcrnrlon - llcrnrlon) / 2.0 dlat = (urcrnrlat - llcrnrlat) / 2.0 lon_0 = llcrnrlon + dlon lat_0 = llcrnrlat + dlat fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111) # new projection : m = Basemap(ax=ax, llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat, llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon, resolution='h', projection='stere', lon_0=lon_0, lat_0=lat_0) offset = 0.015 * (m.ymax - m.ymin) # draw lat/lon grid lines every degree. # labels = [left,right,top,bottom] if plot_grid: m.drawmeridians(np.arange(0, 360, lon_interval), color='black', labels=[False, False, False, True]) m.drawparallels(np.arange(-90, 90, lat_interval), color='black', labels=[True, False, False, False]) if scale_loc == 1: fact = 1.8 elif scale_loc == 2: fact = 0.2 if plot_scale: dx = (m.xmax - m.xmin) / 2.0 dy = (m.ymax - m.ymin) / 2.0 xmid = m.xmin + dx ymid = m.ymin + fact * dy slon, slat = m(xmid, ymid, inverse=True) m.drawmapscale(slon, slat, slon, slat, scale_length, barstyle='fancy', fontcolor=scale_color) for axis in ['top', 'bottom', 'left', 'right']: ax.spines[axis].set_color(axes_color) else: s = ">>> plotIce REQUIRES A 'dict' OF SPECIFIC PARAMETERS FOR 'custom' <<<" print_text(s, 'red', 1) sys.exit(1) # convert to new projection coordinates from lon,lat : x, y = m(lon, lat) m.drawcoastlines(linewidth=0.5, color='black') #m.shadedrelief() #m.bluemarble() #m.etopo() if plot_continent: if cont is 'greenland': llcrnrlat = 57 urcrnrlat = 80.1 llcrnrlon = -57 urcrnrlon = 15 axcont = inset_locator.inset_axes(ax, **cont_plot_params) axcont.xaxis.set_ticks_position('none') axcont.yaxis.set_ticks_position('none') # continent projection : mc = Basemap(ax=axcont, llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat, llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon, resolution='c', projection='stere', lon_0=lon_0, lat_0=lat_0) mc.drawcoastlines(linewidth=0.5, color='black') x_c, y_c = mc(lon, lat) v_cont = v.copy() v_cont[:] = 1.0 axcont.tricontourf(x_c, y_c, fi, v_cont, cmap=pl.get_cmap('Reds')) #============================================================================= # plotting : if umin != None and levels is None: vmin = umin elif levels is not None: vmin = levels.min() else: vmin = v.min() if umax != None and levels is None: vmax = umax elif levels is not None: vmax = levels.max() else: vmax = v.max() # set the extended colormap : cmap = pl.get_cmap(cmap) #cmap.set_under(under) #cmap.set_over(over) # countour levels : if scale == 'log': if levels is None: levels = np.logspace(np.log10(vmin), np.log10(vmax), numLvls) v[v < vmin] = vmin + 2e-16 v[v > vmax] = vmax - 2e-16 formatter = LogFormatter(10, labelOnlyBase=False) norm = colors.LogNorm() # countour levels : elif scale == 'sym_log': if levels is None: levels = np.linspace(vmin, vmax, numLvls) v[v < vmin] = vmin + 2e-16 v[v > vmax] = vmax - 2e-16 formatter = LogFormatter(e, labelOnlyBase=False) norm = colors.SymLogNorm(vmin=vmin, vmax=vmax, linscale=0.001, linthresh=0.001) elif scale == 'lin': if levels is None: levels = np.linspace(vmin, vmax, numLvls) norm = colors.BoundaryNorm(levels, cmap.N) elif scale == 'bool': v[v < 0.0] = 0.0 levels = [0, 1, 2] norm = colors.BoundaryNorm(levels, cmap.N) # please do zoom in! if zoom_box: zoom = zoom_box_kwargs['zoom'] loc = zoom_box_kwargs['loc'] loc1 = zoom_box_kwargs['loc1'] loc2 = zoom_box_kwargs['loc2'] llcrnrlat = zoom_box_kwargs['llcrnrlat'] urcrnrlat = zoom_box_kwargs['urcrnrlat'] llcrnrlon = zoom_box_kwargs['llcrnrlon'] urcrnrlon = zoom_box_kwargs['urcrnrlon'] plot_zoom_scale = zoom_box_kwargs['plot_zoom_scale'] scale_font_color = zoom_box_kwargs['scale_font_color'] scale_length = zoom_box_kwargs['scale_length'] scale_loc = zoom_box_kwargs['scale_loc'] plot_grid = zoom_box_kwargs['plot_grid'] axes_color = zoom_box_kwargs['axes_color'] zb_plot_pts = zoom_box_kwargs['plot_points'] x1, y1 = m(llcrnrlon, llcrnrlat) x2, y2 = m(urcrnrlon, urcrnrlat) axins = inset_locator.zoomed_inset_axes(ax, zoom, loc=loc) inset_locator.mark_inset(ax, axins, loc1=loc1, loc2=loc2, fc="none", ec=axes_color) for axis in ['top', 'bottom', 'left', 'right']: axins.spines[axis].set_color(axes_color) #axins.spines[axis].set_linewidth(2) if scale_loc == 1: fact = 1.8 elif scale_loc == 2: fact = 0.2 dx = (x2 - x1) / 2.0 dy = (y2 - y1) / 2.0 xmid = x1 + dx ymid = y1 + fact * dy slon, slat = m(xmid, ymid, inverse=True) # new projection : mn = Basemap(ax=axins, width=w, height=h, resolution='h', projection='stere', lat_ts=lat_0, lon_0=lon_0, lat_0=lat_0) if plot_zoom_scale: mn.drawmapscale(slon, slat, slon, slat, scale_length, yoffset=0.025 * 2.0 * dy, barstyle='fancy', fontcolor=scale_font_color) mn.drawcoastlines(linewidth=0.5, color='black') axins.set_xlim(x1, x2) axins.set_ylim(y1, y2) axins.xaxis.set_ticks_position('none') axins.yaxis.set_ticks_position('none') if isinstance(u, str): #cs = ax.pcolor(x, y, v, cmap=get_cmap(cmap), norm=norm) if contour_type == 'filled': cs = ax.contourf(x, y, v, levels=levels, cmap=cmap, norm=norm, extend=extend) if zoom_box: axins.contourf(x, y, v, levels=levels, cmap=cmap, norm=norm, extend=extend) if contour_type == 'lines': cs = ax.contour(x, y, v, levels=levels, colors='k') for line in cs.collections: if line.get_linestyle() != [(None, None)]: line.set_linestyle([(None, None)]) line.set_color('red') line.set_linewidth(1.5) if levels_2 is not None: cs2 = ax.contour(x, y, v, levels=levels_2, colors='k') for line in cs2.collections: if line.get_linestyle() != [(None, None)]: line.set_linestyle([(None, None)]) line.set_color('#c1000e') line.set_linewidth(0.5) ax.clabel(cs, inline=1, colors='k', fmt='%i') if zoom_box: axins.contour(x, y, v, levels=levels, colors='k') elif isinstance(u, Function) \ or isinstance(u, dolfin.functions.function.Function): #cs = ax.tripcolor(x, y, fi, v, shading='gouraud', # cmap=get_cmap(cmap), norm=norm) if contour_type == 'filled': cs = ax.tricontourf(x, y, fi, v, levels=levels, cmap=cmap, norm=norm, extend=extend) if zoom_box: axins.tricontourf(x, y, fi, v, levels=levels, cmap=cmap, norm=norm, extend=extend) elif contour_type == 'lines': cs = ax.tricontour(x, y, fi, v, linewidths=2.0, levels=levels, colors='k') for line in cs.collections: if line.get_linestyle() != [(None, None)]: line.set_linestyle([(None, None)]) line.set_color('red') line.set_linewidth(1.5) if levels_2 is not None: cs2 = ax.tricontour(x, y, fi, v, levels=levels_2, colors='0.30') for line in cs2.collections: if line.get_linestyle() != [(None, None)]: line.set_linestyle([(None, None)]) line.set_color('#c1000e') line.set_linewidth(0.5) ax.clabel(cs, inline=1, colors='k', fmt='%i') if zoom_box: axins.tricontour(x, y, fi, v, levels=levels, colors='k') axins.clabel(cs, inline=1, colors='k', fmt='%1.2f') if u2 is not None: v2 = u2.compute_vertex_values(mesh) csu2 = ax.tricontour(x, y, fi, v2, linewidths=1.5, levels=u2_levels, colors=u2_color) #for line in csu2.collections: # if line.get_linestyle() != [(None, None)]: # line.set_linestyle([(None, None)]) if plot_pts is not None: lat_a = plot_pts['lat'] lon_a = plot_pts['lon'] sty_a = plot_pts['style'] clr_a = plot_pts['color'] for lat_i, lon_i, sty_i, clr_i in zip(lat_a, lon_a, sty_a, clr_a): x_i, y_i = m(lon_i, lat_i) ax.plot(x_i, y_i, color=clr_i, marker=sty_i) if box_params is not None: x1, y1 = m(box_params['llcrnrlon'], box_params['llcrnrlat']) x2, y2 = m(box_params['urcrnrlon'], box_params['urcrnrlat']) box_x_s = [x1, x2, x2, x1, x1] box_y_s = [y1, y1, y2, y2, y1] ax.plot(box_x_s, box_y_s, '-', lw=1.0, color=box_params['color']) if zoom_box: if zb_plot_pts is not None: lat_a = zb_plot_pts['lat'] lon_a = zb_plot_pts['lon'] sty_a = zb_plot_pts['style'] clr_a = zb_plot_pts['color'] for lat_i, lon_i, sty_i, clr_i in zip(lat_a, lon_a, sty_a, clr_a): x_i, y_i = m(lon_i, lat_i) axins.plot(x_i, y_i, color=clr_i, marker=sty_i) # plot triangles : if tp == True: tp = ax.triplot(x, y, fi, 'k-', lw=0.2, alpha=tpAlpha) if zoom_box and plot_grid: tpaxins = axins.triplot(x, y, fi, 'k-', lw=0.2, alpha=tpAlpha) # include colorbar : if cb and scale != 'bool': divider = make_axes_locatable(ax) #plt.gca()) cax = divider.append_axes("right", "5%", pad="3%") cbar = fig.colorbar( cs, cax=cax, #format=formatter, ticks=levels, format=cb_format) #cbar = plt.colorbar(cs, cax=cax, format=formatter, # ticks=np.around(levels,decimals=1)) # title : tit = plt.title(title) #tit.set_fontsize(40) plt.tight_layout(rect=[.03, .03, 0.97, 0.97]) d = os.path.dirname(direc) if not os.path.exists(d): os.makedirs(d) plt.savefig(direc + name + ext, res=res) if show: plt.show() plt.close(fig) return m
def mkplots(self): # run to make plots of the resulting posteriors. Modified from marginal_plots.py # from pymultinest. Produces basename+marg.pdf and basename+marge.png files prefix = self.basename parameters = json.load(file(prefix + 'params.json')) n_params = len(parameters) a = pymultinest.Analyzer(n_params=n_params, outputfiles_basename=prefix) s = a.get_stats() p = pymultinest.PlotMarginal(a) try: values = a.get_equal_weighted_posterior() except IOError as e: print 'Unable to open: %s' % e return assert n_params == len(s['marginals']) modes = s['modes'] dim2 = os.environ.get('D', '1' if n_params > 20 else '2') == '2' nbins = 100 if n_params < 3 else 20 if dim2: plt.figure(figsize=(5.1 * n_params, 5 * n_params)) for i in range(n_params): plt.subplot(n_params, n_params, i + 1) plt.xlabel(parameters[i]) m = s['marginals'][i] plt.xlim(m['5sigma']) oldax = plt.gca() x, w, patches = oldax.hist(values[:, i], bins=nbins, edgecolor='grey', color='grey', histtype='stepfilled', alpha=0.2) oldax.set_ylim(0, x.max()) newax = plt.gcf().add_axes(oldax.get_position(), sharex=oldax, frameon=False) p.plot_marginal(i, ls='-', color='blue', linewidth=3) newax.set_ylim(0, 1) ylim = newax.get_ylim() y = ylim[0] + 0.05 * (ylim[1] - ylim[0]) center = m['median'] low1, high1 = m['1sigma'] print center, low1, high1 newax.errorbar(x=center, y=y, xerr=np.transpose( [[center - low1, high1 - center]]), color='blue', linewidth=2, marker='s') oldax.set_yticks([]) #newax.set_yticks([]) newax.set_ylabel("Probability") ylim = oldax.get_ylim() newax.set_xlim(m['5sigma']) oldax.set_xlim(m['5sigma']) #plt.close() for j in range(i): plt.subplot(n_params, n_params, n_params * (j + 1) + i + 1) p.plot_conditional(i, j, bins=20, cmap=plt.cm.gray_r) for m in modes: plt.errorbar(x=m['mean'][i], y=m['mean'][j], xerr=m['sigma'][i], yerr=m['sigma'][j]) ax = plt.gca() if j == i - 1: plt.xlabel(parameters[i]) plt.ylabel(parameters[j]) [l.set_rotation(45) for l in ax.get_xticklabels()] else: ax.set_xticklabels([]) ax.set_yticklabels([]) plt.xlim([ m['mean'][i] - 5 * m['sigma'][i], m['mean'][i] + 5 * m['sigma'][i] ]) plt.ylim([ m['mean'][j] - 5 * m['sigma'][j], m['mean'][j] + 5 * m['sigma'][j] ]) #plt.savefig('cond_%s_%s.pdf' % (params[i], params[j]), bbox_tight=True) #plt.close() plt.tight_layout() plt.savefig(prefix + 'marg.pdf') plt.savefig(prefix + 'marg.png') plt.close() else: from matplotlib.backends.backend_pdf import PdfPages print '1dimensional only. Set the D environment variable D=2 to force' print '2d marginal plots.' pp = PdfPages(prefix + 'marg1d.pdf') for i in range(n_params): plt.figure(figsize=(5, 5)) plt.xlabel(parameters[i]) m = s['marginals'][i] plt.xlim(m['5sigma']) oldax = plt.gca() x, w, patches = oldax.hist(values[:, i], bins=20, edgecolor='grey', color='grey', histtype='stepfilled', alpha=0.2) oldax.set_ylim(0, x.max()) newax = plt.gcf().add_axes(oldax.get_position(), sharex=oldax, frameon=False) p.plot_marginal(i, ls='-', color='blue', linewidth=3) newax.set_ylim(0, 1) ylim = newax.get_ylim() y = ylim[0] + 0.05 * (ylim[1] - ylim[0]) center = m['median'] low1, high1 = m['1sigma'] print center, low1, high1 newax.errorbar(x=center, y=y, xerr=np.transpose( [[center - low1, high1 - center]]), color='blue', linewidth=2, marker='s') oldax.set_yticks([]) newax.set_ylabel("Probability") ylim = oldax.get_ylim() newax.set_xlim(m['5sigma']) oldax.set_xlim(m['5sigma']) plt.savefig(pp, format='pdf', bbox_inches='tight') plt.close() pp.close()
from pylab import plt from cpab.cpa1d.needful_things import * from of.gpu import CpuGpuArray class TF: plot = 1 and 1 params_flow_int = get_params_flow_int() # # 1/0 pylab.ion() plt.close('all') np.random.seed(32) XMINS = [0] XMAXS = [1] nCx = 10 nCx = 50 nCx = 100 # nCx = 100*2 # nCx = 500*2 vol_preserve = False warp_around,zero_v_across_bdry= [False], [True]
def distance(pool_backup, fig_name=None, ax=None): # Shortcuts parameters = pool_backup.parameters backups = pool_backup.backups # Look at the parameters n_simulations = len(parameters["seed"]) n_positions = parameters["n_positions"] t_max = parameters["t_max"] # Containers x = np.zeros(n_simulations) y = np.zeros(n_simulations) z = np.zeros(n_simulations) y_err = np.zeros(n_simulations) # How many time steps from the end of the simulation are included in analysis span_ratio = 0.33 # Take last third span = int(span_ratio * t_max) for i, b in enumerate(backups): x[i] = b.parameters.r # Compute the mean distance between the two firms data = np.absolute( b.positions[-span:, 0] - b.positions[-span:, 1]) / n_positions spacing = np.mean(data) y[i] = spacing # Get std y_err[i] = np.std(data) # Get mean profits z[i] = np.mean(b.profits[-span:, :]) # Plot this if ax is None: fig = plt.figure(figsize=(5, 5), dpi=200) ax = fig.add_subplot() # Enhance aesthetics ax.set_xlim(-0.009, 1.005) ax.set_ylim(-0.009, 1.005) # if max(y) < 0.5: # ax.set_ylim(-0.01, 0.51) ax.set_xticks(np.arange(0, 1.1, 0.25)) ax.set_yticks(np.arange(0, 1.1, 0.25)) ax.set_xlabel("$r$") ax.set_ylabel("Distance") # ax.set_title("Mean distance between firms over $r$") # Display line for indicating 'random' level # seed = 123 # np.random.seed(seed) # random_pos = np.random.random(size=(2, 10 ** 6)) # random_dist = np.mean(np.absolute(random_pos[0] - random_pos[1])) # ax.axhline(random_dist, color='0.5', linewidth=0.5, linestyle="--", zorder=1) # if color: # _color(fig=fig, ax=ax, x=x, y=y, z=z) # else: _bw(ax=ax, x=x, y=y, y_err=y_err) if fig_name: # Cut the margins plt.tight_layout() # Create directories if not already existing os.makedirs(os.path.dirname(fig_name), exist_ok=True) # Save fig plt.savefig(fig_name) plt.close()
def plot_slip_overview(slip, output_file, if_x_log=False, xlim=[0, 1344], ylim = [0,100], yticks = [20, 40, 60], xticks = [1, 10, 100, 1000], xticklabels = [r'$10^0$', r'$10^1$', r'$10^2$', r'$10^3$'], rotation = 45, fontsize = 10, ): num_subflts_strike = slip.num_subflt_along_strike num_subflts_dip = slip.num_subflt_along_dip epochs = slip.get_epochs() fig, axes = plt.subplots(num_subflts_dip, num_subflts_strike, sharex=True, sharey=True) for ii in range(num_subflts_dip): for jj in range(num_subflts_strike): ax = axes[ii][jj] slip_subflt = slip.get_cumu_slip_at_subfault(ii,jj) plt.sca(ax) plt.fill_between(x=epochs, y1=slip_subflt, y2=0, color='r') if if_x_log: ax.set_xscale('log') plt.xlim(xlim) plt.ylim(ylim) plt.grid('on') plt.box('on') plt.tick_params(axis='both',which='both', bottom='off', top='off', left='off', right='off', labelbottom='off', labeltop='off', labelleft='off', labelright='off') fig.subplots_adjust(hspace=0, wspace=0) for ax in axes[-1,::2]: plt.sca(ax) plt.tick_params(axis='x',which='major', bottom='on', top='off', left='off', right='off', labelbottom='on', labeltop='off', labelleft='off', labelright='off') ax.set_xticks(xticks) ax.set_xticklabels(xticklabels, rotation=rotation, fontsize=fontsize) plt.xlabel('day') for ax in axes[0,1::2]: plt.sca(ax) plt.tick_params(axis='x',which='major', bottom='off', top='on', left='off', right='off', labelbottom='off', labeltop='on', labelleft='off', labelright='off') ax.set_xticks(xticks) ax.set_xticklabels(xticklabels, rotation=rotation, fontsize=fontsize) plt.xlabel('day') for ax in axes[::2,0]: plt.sca(ax) plt.tick_params(axis='y',which='major', bottom='off', top='off', left='on', right='off', labelbottom='off', labeltop='off', labelleft='on', labelright='off') ax.set_yticks(yticks) #ax.set_yticklabels(range(0,100,20)) for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(10) tick.label.set_rotation('horizontal') plt.ylabel('slip/m') for ax in axes[::2,-1]: plt.sca(ax) plt.tick_params(axis='y',which='major', bottom='off', top='off', left='off', right='on', labelbottom='off', labeltop='off', labelleft='off', labelright='on') ax.set_yticks(yticks) #ax.set_yticklabels(range(0,100,20)) for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(10) tick.label.set_rotation('horizontal') plt.ylabel('slip/m') ax.yaxis.set_label_position("right") fig.set_size_inches(33,10) plt.savefig(output_file) plt.close()
def weatherstat(df, destguid=None): dfduplicates = df.groupby('date').apply( lambda d: tuple(d.index) if len(d.index) > 1 else None).dropna() log.info(dfduplicates) df.drop_duplicates(inplace=True) # 去重,去除可能重复的天气数据记录,原因可能是邮件重复发送等 # print(df.head(30)) df['date'] = df['date'].apply(lambda x: pd.to_datetime(x)) # 日期做索引,去重并重新排序 df.index = df['date'] df = df[~df.index.duplicated()] df.sort_index(inplace=True) # print(df) df.dropna(how='all', inplace=True) # 去掉空行,索引日期,后面索引值相同的行会被置空,需要去除 # print(len(df)) # df['gaowen'] = df['gaowen'].apply(lambda x: np.nan if str(x).isspace() else int(x)) #处理空字符串为空值的另外一骚 df['gaowen'] = df['gaowen'].apply(lambda x: int(x) if x else None) # 数字串转换成整数,如果空字符串则为空值 df['diwen'] = df['diwen'].apply(lambda x: int(x) if x else None) df['fengsu'] = df['fengsu'].apply(lambda x: int(x) if x else None) df['shidu'] = df['shidu'].apply(lambda x: int(x) if x else None) # df['gaowen'] = df['gaowen'].astype(int) # df['diwen'] = df['diwen'].astype(int) # df['fengsu'] = df['fengsu'].astype(int) # df['shidu'] = df['shidu'].astype(int) df.fillna(method='ffill', inplace=True) # 向下填充处理可能出现的空值,bfill是向上填充 df['wendu'] = (df['gaowen'] + df['diwen']) / 2 df['richang'] = df['sunoff'] - df['sunon'] df['richang'] = df['richang'].astype(int) df['wendu'] = df['wendu'].astype(int) # print(df.tail(30)) df_recent_year = df.iloc[-365:] # print(df_recent_year) # print(df[df.gaowen == df.iloc[-364:]['gaowen'].max()]) # df_before_year = df.iloc[:-364] plt.figure(figsize=(16, 20)) ax1 = plt.subplot2grid((4, 2), (0, 0), colspan=2, rowspan=2) ax1.plot(df['gaowen'], lw=0.3, label=u'日高温') ax1.plot(df['diwen'], lw=0.3, label=u'日低温') ax1.plot(df['wendu'], 'g', lw=0.7, label=u'日温度(高温低温平均)') quyangtianshu = 10 ax1.plot(df['wendu'].resample('%dD' % quyangtianshu).mean(), 'b', lw=1.2, label='日温度(每%d天平均)' % quyangtianshu) ax1.plot(df[df.fengsu > 5]['fengsu'], '*', label='风速(大于五级)') plt.legend(loc=2) # 起始统计日 kedu = df.iloc[0] ax1.plot([kedu['date'], kedu['date']], [0, kedu['wendu']], 'c--', lw=0.4) ax1.scatter([ kedu['date'], ], [kedu['wendu']], 50, color='Wheat') fsize = 8 txt = str(kedu['wendu']) ax1.annotate(txt, xy=(kedu['date'], kedu['wendu']), xycoords='data', xytext=(-(len(txt) * fsize), +20), textcoords='offset points', fontsize=fsize, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2", color='Purple')) dates = "%02d-%02d" % (kedu['date'].month, kedu['date'].day) ax1.annotate(dates, xy=(kedu['date'], 0), xycoords='data', xytext=(-10, -20), textcoords='offset points', fontsize=8, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0")) # 去年今日,如果数据不足一年,取今日 if len(df) >= 366: locqnjr = -365 else: locqnjr = -1 kedu = df.iloc[locqnjr] # kedu = df.iloc[-364] print(kedu) ax1.plot([kedu['date'], kedu['date']], [0, kedu['wendu']], 'c--') ax1.scatter([ kedu['date'], ], [kedu['wendu']], 50, color='Wheat') ax1.annotate(str(kedu['wendu']), xy=(kedu['date'], kedu['wendu']), xycoords='data', xytext=(-5, +20), textcoords='offset points', arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2", color='Purple')) dates = "%02d-%02d" % (kedu['date'].month, kedu['date'].day) ax1.annotate(dates, xy=(kedu['date'], 0), xycoords='data', xytext=(-10, -35), textcoords='offset points', fontsize=8, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0")) # 今日 kedu = df.iloc[-1] # print(kedu) ax1.plot([kedu['date'], kedu['date']], [0, kedu['wendu']], 'c--') ax1.scatter([ kedu['date'], ], [kedu['gaowen']], 50, color='BlueViolet') ax1.annotate(str(kedu['gaowen']), xy=(kedu['date'], kedu['gaowen']), xycoords='data', xytext=(-10, +20), textcoords='offset points', arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2", color='Purple')) ax1.scatter([ kedu['date'], ], [kedu['wendu']], 50, color='BlueViolet') ax1.annotate(str(kedu['wendu']), xy=(kedu['date'], kedu['wendu']), xycoords='data', xytext=(10, +5), textcoords='offset points', arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2", color='Purple')) ax1.scatter([ kedu['date'], ], [kedu['diwen']], 50, color='BlueViolet') ax1.annotate(str(kedu['diwen']), xy=(kedu['date'], kedu['diwen']), xycoords='data', xytext=(-10, -20), textcoords='offset points', arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2", color='Purple')) dates = "%02d-%02d" % (kedu['date'].month, kedu['date'].day) ax1.annotate(dates, xy=(kedu['date'], 0), xycoords='data', xytext=(-10, -35), textcoords='offset points', fontsize=8, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0")) # 最近一年最高温 kedu = df_recent_year[df_recent_year.gaowen == df_recent_year.iloc[-364:] ['gaowen'].max()].iloc[0] # print(kedu) ax1.plot([kedu['date'], kedu['date']], [0, kedu['gaowen']], 'c--') ax1.scatter([ kedu['date'], ], [kedu['gaowen']], 50, color='Wheat') ax1.annotate(str(kedu['gaowen']), xy=(kedu['date'], kedu['gaowen']), xycoords='data', xytext=(-20, +5), textcoords='offset points', arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2", color='Purple')) dates = "%02d-%02d" % (kedu['date'].month, kedu['date'].day) ax1.annotate(dates, xy=(kedu['date'], 0), xycoords='data', xytext=(-10, -20), textcoords='offset points', fontsize=8, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0")) # 最近一年最低温 kedu = df_recent_year[df_recent_year.diwen == df_recent_year.iloc[-364:] ['diwen'].min()].iloc[0] ax1.plot([kedu['date'], kedu['date']], [0, kedu['diwen']], 'c--') ax1.scatter([ kedu['date'], ], [kedu['diwen']], 50, color='Wheat') ax1.annotate(str(kedu['diwen']), xy=(kedu['date'], kedu['diwen']), xycoords='data', xytext=(-20, +5), textcoords='offset points', arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2", color='Purple')) dates = "%02d-%02d" % (kedu['date'].month, kedu['date'].day) ax1.annotate(dates, xy=(kedu['date'], 0), xycoords='data', xytext=(-10, -20), textcoords='offset points', fontsize=8, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0")) # 最高温 kedu = df[df.gaowen == df['gaowen'].max()].iloc[0] ax1.plot([kedu['date'], kedu['date']], [0, kedu['gaowen']], 'c--') ax1.scatter([ kedu['date'], ], [kedu['gaowen']], 50, color='Wheat') ax1.annotate(str(kedu['gaowen']), xy=(kedu['date'], kedu['gaowen']), xycoords='data', xytext=(-20, +5), textcoords='offset points', arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2", color='Purple')) dates = "%02d-%02d" % (kedu['date'].month, kedu['date'].day) ax1.annotate(dates, xy=(kedu['date'], 0), xycoords='data', xytext=(-10, -20), textcoords='offset points', fontsize=8, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0")) # 最低温 kedu = df[df.diwen == df['diwen'].min()].iloc[0] ax1.plot([kedu['date'], kedu['date']], [0, kedu['diwen']], 'c--') ax1.scatter([ kedu['date'], ], [kedu['diwen']], 50, color='Wheat') ax1.annotate(str(kedu['diwen']), xy=(kedu['date'], kedu['diwen']), xycoords='data', xytext=(-20, +5), textcoords='offset points', arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2", color='Purple')) dates = "%02d-%02d" % (kedu['date'].month, kedu['date'].day) ax1.annotate(dates, xy=(kedu['date'], 0), xycoords='data', xytext=(-10, -20), textcoords='offset points', fontsize=8, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0")) ax1.set_ylabel(u'(摄氏度℃)') ax1.grid(True) ax1.set_title(u'最高气温、最低气温和均值温度图') ax3 = plt.subplot2grid((4, 2), (2, 0), colspan=2, rowspan=2) # print(type(ax3)) ax3.plot(df_recent_year['shidu'], 'c.', lw=0.3, label=u'湿度') ax3.plot(df_recent_year['shidu'].resample('15D').mean(), 'g', lw=1.5) ax3.set_ylabel(u'(百分比%)') ax3.set_title(u'半月平均湿度图') img_wenshifeng_path = dirmainpath / "img" / 'weather' / 'wenshifeng.png' img_wenshifeng_path_str = str(img_wenshifeng_path) touchfilepath2depth(img_wenshifeng_path) plt.legend(loc='lower left') plt.savefig(img_wenshifeng_path_str) imglist = list() imglist.append(img_wenshifeng_path_str) plt.close() plt.figure(figsize=(16, 10)) fig, ax1 = plt.subplots() plt.plot(df['date'], df['sunon'], lw=0.8, label=u'日出') plt.plot(df['date'], df['sunoff'], lw=0.8, label=u'日落') ax = plt.gca() # ax.yaxis.set_major_formatter(FuncFormatter(min_formatter)) # 主刻度文本用pi_formatter函数计算 ax.yaxis.set_major_formatter( FuncFormatter(lambda x, pos: "%02d:%02d" % (int(x / 60), int(x % 60)))) # 主刻度文本用pi_formatter函数计算 plt.ylim((0, 24 * 60)) plt.yticks(np.linspace(0, 24 * 60, 25)) plt.xlabel(u'日期') plt.ylabel(u'时刻') plt.legend(loc=6) plt.title(u'日出日落时刻和白天时长图') plt.grid(True) ax2 = ax1.twinx() print(ax2) plt.plot(df_recent_year['date'], df_recent_year['richang'], 'r', lw=1.5, label=u'日长') ax = plt.gca() # ax.yaxis.set_major_formatter(FuncFormatter(min_formatter)) # 主刻度文本用pi_formatter函数计算 ax.yaxis.set_major_formatter( FuncFormatter(lambda x, pos: "%02d:%02d" % (int(x / 60), int(x % 60)))) # 主刻度文本用pi_formatter函数计算 # ax.set_xticklabels(rotation=45, horizontalalignment='right') plt.ylim((3 * 60, 12 * 60)) plt.yticks(np.linspace(3 * 60, 15 * 60, 13)) plt.ylabel(u'时分') plt.legend(loc=5) plt.grid(True) # plt.show() img_sunonoff_path = dirmainpath / 'img' / 'weather' / 'sunonoff.png' img_sunonoff_path_str = str(img_sunonoff_path) touchfilepath2depth(img_sunonoff_path) plt.savefig(img_sunonoff_path_str) imglist.append(img_sunonoff_path_str) plt.close() imglist2note(get_notestore(), imglist, destguid, '武汉天气图')