def plot(orbits_f, flt, orbits_b, bin, pixnr): plt.cla() # fig = plt.figure() fig = plt.subplot(111) fig.set_ylim([-.1,1.1]) fig.set_title("pixel "+str(pixnr)) print(np.min(orbits_f), np.max(orbits_f), np.min(orbits_b), np.max(orbits_b)) s_bin = smooth(orbits_b, bin) bin_slice = (1.0 - bin[:,pixnr].flatten()) sbin_slice = (1.0 - s_bin[:,pixnr].flatten()) ax = np.arange(bin_slice.size) # plt.plot(ax, bin_slice, 'ro', ax, sbin_slice, 'r-') plt.plot(orbits_b, bin_slice, 'r-') s_flt = smooth(orbits_f, flt) flt_slice = flt[:,pixnr].flatten() sflt_slice = s_flt[:,pixnr].flatten() ma = np.max(flt_slice) if ma > 0: flt_slice /= ma sflt_slice /= ma ax = np.arange(flt_slice.size) plt.plot(orbits_f, flt_slice, 'bo', orbits_f, sflt_slice, 'g-') plt.show() return
def main(): conn = krpc.connect() vessel = conn.space_center.active_vessel streams = init_streams(conn,vessel) print vessel.control.throttle plt.axis([0, 100, 0, .1]) plt.ion() plt.show() t0 = time.time() timeSeries = [] vessel.control.abort = False while not vessel.control.abort: t_now = time.time()-t0 tel = Telemetry(streams,t_now) timeSeries.append(tel) timeSeriesRecent = timeSeries[-40:] plt.cla() plt.semilogy([tel.t for tel in timeSeriesRecent], [norm(tel.angular_velocity) for tel in timeSeriesRecent]) #plt.semilogy([tel.t for tel in timeSeriesRecent[1:]], [quat_diff_test(t1,t2) for t1,t2 in zip(timeSeriesRecent,timeSeriesRecent[1:])]) #plt.axis([t_now-6, t_now, 0, .1]) plt.draw() plt.pause(0.0000001) #time.sleep(0.0001) with open('log.json','w') as f: f.write(json.dumps([tel.__dict__ for tel in timeSeries],indent=4)) print 'The End'
def plot_pf(pf, xlim=100, ylim=100, weights=True): if weights: a = plt.subplot(221) a.cla() plt.xlim(0, ylim) #plt.ylim(0, 1) a.set_yticklabels('') plt.scatter(pf.particles[:, 0], pf.weights, marker='.', s=1, color='k') a.set_ylim(bottom=0) a = plt.subplot(224) a.cla() a.set_xticklabels('') plt.scatter(pf.weights, pf.particles[:, 1], marker='.', s=1, color='k') plt.ylim(0, xlim) a.set_xlim(left=0) #plt.xlim(0, 1) a = plt.subplot(223) a.cla() else: plt.cla() plt.scatter(pf.particles[:, 0], pf.particles[:, 1], marker='.', s=1, color='k') plt.xlim(0, xlim) plt.ylim(0, ylim)
def graph_ROC(max_ACC, TP, FP, name="STD"): aTP = np.vstack(TP) n = len(TP) mean_TP = np.mean(aTP, axis=0) stderr_TP = np.std(aTP, axis=0) / (n ** 0.5) var_TP = np.var(aTP, axis=0) max_TP = mean_TP + 3 * stderr_TP min_TP = mean_TP - 3 * stderr_TP # sTP = sum(TP) / len(TP) sFP = FP[0] print len(sFP), len(mean_TP), len(TP[0]) smax_ACC = np.mean(max_ACC) plt.cla() plt.clf() plt.close() plt.plot(sFP, mean_TP) plt.fill_between(sFP, min_TP, max_TP, color='black', alpha=0.2) plt.xlim((0,0.1)) plt.ylim((0,1)) plt.title('ROC Curve (accuracy=%.3f)' % smax_ACC) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.savefig(r"../scratch/"+name+"_ROC_curve.pdf", bbox_inches='tight') # Write the data to the file f = file(r"../scratch/"+name+"_ROC_curve.csv", "w") f.write("FalsePositive,TruePositive,std_err, var, n\n") for fp, tp, err, var in zip(sFP, mean_TP, stderr_TP, var_TP): f.write("%s, %s, %s, %s, %s\n" % (fp, tp, err, var, n)) f.close()
def run_test(name): basepath = os.path.join('results', name) if not os.path.exists(basepath): os.makedirs(basepath) ctrl = LBSimulationController(TestLDCSim) ctrl.run(ignore_cmdline=True) horiz = np.loadtxt('ldc_golden/re400_horiz', skiprows=1) vert = np.loadtxt('ldc_golden/re400_vert', skiprows=1) plt.plot(2 * (horiz[:,0] - 0.5), -2 * (horiz[:,1] - 0.5), '.', label='Sheu, Tsai paper') plt.plot(2 * (vert[:,0] - 0.5), -2 * (vert[:,1] - 0.5), '.', label='Sheu, Tsai paper') save_output(basepath, MAX_ITERS) plt.legend(loc='lower right') plt.gca().yaxis.grid(True) plt.gca().xaxis.grid(True) plt.gca().xaxis.grid(True, which='minor') plt.gca().yaxis.grid(True, which='minor') plt.title('Lid Driven Cavity, Re = 400') print os.path.join(basepath, 're400.pdf' ) plt.savefig(os.path.join(basepath, 're400.pdf' ), format='pdf') plt.clf() plt.cla() plt.show() shutil.rmtree(tmpdir)
def plot1(self,oligodata,name): for level in oligodata: valcheck=[] x=[] y=[] maxval=0 for val in oligodata[level]: if oligodata[level][val]>maxval: maxval-=maxval maxval+=oligodata[level][val] crval=self.get_CR(val) if val!=crval and (val not in valcheck) and (crval not in valcheck): valcheck.append(val) valcheck.append(crval) x.append(oligodata[level][val]) y.append(oligodata[level][crval]) maxval=maxval+0.05*maxval ## print 'maxval=',maxval plt.plot(x,y,'k+') plt.plot([-1,maxval],[-1,maxval],'k') ## plt.xlabel('x') ## plt.ylabel('y') plt.text(maxval/2,maxval-2*float(maxval)/100,r'$S_{'+ level+'}^{'+self.sotype+'}$',va='top',ha='center',fontsize=20) ## plt.legend() resname=self.inpufile.path+name+'_'+level.rpartition('/')[0]+'-'+level.rpartition('/')[2]+'.pdf' plt.savefig(resname) plt.cla() plt.close()
def plot2(self,oligodata,name): for level in oligodata: valcheck=['z(a)','z(c)','z(g)','z(t)','z(t+a)/z(c+g)'] x=[] y=[] maxval=0 for val in oligodata[level]: if (val not in valcheck) and (oligodata[level][val]>maxval): maxval-=maxval maxval+=oligodata[level][val] if (val not in valcheck): cval=self.get_C(val[0:int(name[3])-1]) cval=cval+'a+'+cval+'c+'+cval+'g+'+cval+'t' if (cval not in valcheck): valcheck.append(val) valcheck.append(cval) x.append(oligodata[level][val]) y.append(oligodata[level][cval]) maxval=maxval+0.05*maxval ## print 'maxval=',maxval plt.plot(x,y,'k+') plt.plot([-1,maxval],[-1,maxval],'k') ## plt.xlabel('x') ## plt.ylabel('y') plt.text(maxval/2,maxval-2*float(maxval)/100,r'$S_{'+ level+'}^{'+self.sotype+'}$',va='top',ha='center',fontsize=20) ## plt.legend() resname=self.inpufile.path+name+'_'+level.rpartition('/')[0]+'-'+level.rpartition('/')[2]+'.pdf' plt.savefig(resname) plt.cla() plt.close()
def draw_bar_plot(self, dictlist, title, fid_x, fid_y1, fid_y2, fid_y3, y_min, y_max, legend1, legend2, legend3, outputfile, x_interval=1): ind = np.arange(len(dictlist)) x_ray = self.get_x_from_dictlist(dictlist, fid_x, x_interval) y_1 = self.get_int_list_from_dictlist(dictlist, fid_y1) y_2 = self.get_int_list_from_dictlist(dictlist, fid_y2) y_3 = self.get_int_list_from_dictlist(dictlist, fid_y3) plt.cla() width = 0.35 y_3_bottom = [] for i in range(len(y_1)): y_3_bottom.append(y_1[i] + y_2[i]) p1 = plt.bar(ind, y_1, width, color='r') p2 = plt.bar(ind, y_2, width, color='y', bottom=y_1) p3 = plt.bar(ind, y_3, width, color='g', bottom=y_3_bottom) self.autolabel(p1) self.autolabel(p2) self.autolabel(p3) plt.title(title + '\n') plt.xticks(ind+width/2., x_ray ) plt.yticks(np.arange(0,y_max,20)) plt.legend( (p1[0], p2[0], p3[0]), (legend1, legend2, legend3) ) plt.grid(True) plt.savefig(outputfile)
def plot_scores(fn,expa,x,y,xl,yl,title=''): Persons(expa).plot(plt,x,y) plt.title('PLS, '+str(len(y))+' samples'+title) plt.xlabel(xl) plt.ylabel(yl) plt.savefig(out_pre+"scores"+fn+".png") plt.cla()
def do_plot(mds, plot, ymax, extra=None): fig = plt.figure() ax = fig.add_subplot(111) steps = mds.Steps.Steps values = mds.MDS.Values if ymax is None: ymax = np.max(values) Graph.timeSeries(ax, steps, values, 'b', label='MDS', Ave=True) plt.xlabel('time') plt.ylabel(r'$ops/sec$') if not mds.CPU is None: values = mds.CPU.Values (handles, labels) = Graph.percent(ax, steps, values, 'k', label='% CPU', Ave=True) if (not handles is None) and (not labels is None): plt.legend(handles, labels) else: print "mds.do_plot(): Warning - Plotting CPU utilization failed." else: plt.legend() plt.setp( ax.get_xticklabels(), rotation=30, horizontalalignment='right') start_time = steps[0]/(24.0*60.0*60.0) + mpl.dates.date2num(datetime.date(1970,1,1)) plt.title("%s metadata operations for %s" % (mds.name, mpl.dates.num2date(start_time).strftime("%Y-%m-%d")) ) if ymax is None: ymax = ymax ax.set_ybound(lower=0, upper=ymax) if plot is None: plt.show() else: plt.savefig(plot) plt.cla()
def generate_plots(session, result_dir, output_dir): ratios = read_ratios(result_dir) iteration = session.query(func.max(cm2db.RowMember.iteration)) clusters = [r[0] for r in session.query(cm2db.RowMember.cluster).distinct().filter( cm2db.RowMember.iteration == iteration)] figure = plt.figure(figsize=(6,3)) for cluster in clusters: plt.clf() plt.cla() genes = [r.row_name.name for r in session.query(cm2db.RowMember).filter( and_(cm2db.RowMember.cluster == cluster, cm2db.RowMember.iteration == iteration))] cluster_conds = [c.column_name.name for c in session.query(cm2db.ColumnMember).filter( and_(cm2db.ColumnMember.cluster == cluster, cm2db.ColumnMember.iteration == iteration))] all_conds = [c[0] for c in session.query(cm2db.ColumnName.name).distinct()] non_cluster_conds = [cond for cond in all_conds if not cond in set(cluster_conds)] cluster_data = ratios.loc[genes, cluster_conds] non_cluster_data = ratios.loc[genes, non_cluster_conds] min_value = ratios.min() max_value = ratios.max() for gene in genes: values = [normalize_js(val) for val in cluster_data.loc[gene,:].values] values += [normalize_js(val) for val in non_cluster_data.loc[gene,:].values] plt.plot(values) # plot the "in"/"out" separator line cut_line = len(cluster_conds) plt.plot([cut_line, cut_line], [min_value, max_value], color='red', linestyle='--', linewidth=1) plt.savefig(os.path.join(output_dir, "exp-%d" % cluster)) plt.close(figure)
def print_A_phi_lsld(self, S, mua, musp, xsrc, zsrc, phi0, root, w, s): #print S/1.e9 ls = self.ls ld = self.ld g = self.func(S, mua, musp, ls, ld, self.Xdet, self.Zdet, self.slab_d, xsrc, zsrc, self.seriessum, self.wbyv) r = np.sqrt(self.slab_d**2 + (self.Xdet - xsrc)**2 + (self.Zdet - zsrc)**2) alnrA = np.log(np.abs(g)*r) dlnrA = np.log(self.Amp*r) filename = "lnrA_lsld_%s_%d.png" % (w, s) plt.cla() plt.plot(r, dlnrA, 'b,', label='Data') plt.plot(r, alnrA, 'r.', label='Fit') plt.xlabel(r'$r$ (mm)') plt.ylabel(r'$\log(rA)$') plt.title("%s (w=%s, s=%d)"%(root, w, s)) plt.legend() plt.savefig(filename) filename = "phi_lsld_%s_%d.png" % (w, s) plt.cla() plt.plot(r, self.Pha, 'b,', label='Data') plt.plot(r, np.angle(g)+phi0, 'r.', label='Fit') plt.xlabel('$r$ (mm)') plt.ylabel(r'$\phi$ (radian)') plt.title("%s (w=%s, s=%d)"%(root, w, s)) plt.legend() plt.savefig(filename) filename = "dat_lsld_%s_%d.txt" % (w, s) r = self.dIdx.astype(int)/int(self.amshape[0]) c = self.dIdx.astype(int)%int(self.amshape[0]) d = np.vstack((self.dIdx, r, c, self.Xdet, self.Zdet, self.Amp, self.Pha)).T #np.savetxt(filename, d, fmt='%.0f %.0f %.0f %f %f %f %f', header="index row col xpos zpos Amp Pha") np.savetxt(filename, d, fmt='%.0f %.0f %.0f %f %f %f %f')
def _update(num, data): nonlocal cmap1, bins, ax # clear axes, load data to refresh plt.cla() data = np.loadtxt(core_dict['DataFolder'] + "/data0.txt", float) # plots plt.axvline(x = np.average(data), color = cmap1(0.5), ls="--" , linewidth=1.7) plt.hist(data, bins, alpha=0.6, normed=1, facecolor=cmap1(0.8), label="X ~ Beta(2,5)") # labels legend = plt.legend(loc='upper right', framealpha = 1.0) legend.get_frame().set_linewidth(1) plt.title(core_dict['PlotTitle'], style='italic') plt.xlabel('Regret') plt.ylabel('Frequency') ax.set_ylim([0,0.2])
def make_plot(choice): """ Three options: growing, decaying, flat """ choice_f = flat if choice is "growing": choice_f = grow elif choice is "decaying": choice_f = decay ys = [choice_f(x) * np.sin(np.pi * x) for x in xs] upper_bounds = np.array([choice_f(x) for x in xs]) lower_bounds = upper_bounds * -1 plot.plot(xs, ys, "b", linewidth=linewidth + 1) plot.plot(xs, upper_bounds, "r", linewidth=linewidth) plot.plot(xs, lower_bounds, "r", linewidth=linewidth) # Limit plot.ylim(-3, 3) # Annotate plot.xlabel("Time", fontsize=fontsize) plot.ylabel(r"$\delta \Sigma$", fontsize=fontsize + 5) plot.title("", fontsize=fontsize + 1) # Save and Close plot.savefig("%s_mode.png" % choice) plot.show() plot.cla()
def vis_detections(im, class_name, dets, thresh=0.3): """Visual debugging of detections.""" import matplotlib.pyplot as plt im_show = im if sdha_cfg.channels == 3: im = im[:, :, (2, 1, 0)] im_show = im elif sdha_cfg.channels == 4: b,g,r,mhi = cv2.split(im) im_show = cv2.merge([r,g,b]) else: pass for i in xrange(np.minimum(10, dets.shape[0])): bbox = dets[i, :4] score = dets[i, -1] if score > thresh: plt.cla() plt.imshow(im_show) plt.gca().add_patch( plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False, edgecolor='g', linewidth=3) ) plt.title('{} {:.3f}'.format(class_name, score)) plt.show()
def callback(params): print("Log likelihood {}".format(-objective(params))) plt.cla() print(params) # Show posterior marginals. plot_xs = np.reshape(np.linspace(-7, 7, 300), (300,1)) pred_mean, pred_cov = predict(params, X, y, plot_xs) marg_std = np.sqrt(np.diag(pred_cov)) ax.plot(plot_xs, pred_mean, 'b') ax.fill(np.concatenate([plot_xs, plot_xs[::-1]]), np.concatenate([pred_mean - 1.96 * marg_std, (pred_mean + 1.96 * marg_std)[::-1]]), alpha=.15, fc='Blue', ec='None') # Show samples from posterior. rs = npr.RandomState(0) sampled_funcs = rs.multivariate_normal(pred_mean, pred_cov, size=10) ax.plot(plot_xs, sampled_funcs.T) ax.plot(X, y, 'kx') ax.set_ylim([-1.5, 1.5]) ax.set_xticks([]) ax.set_yticks([]) plt.draw() plt.pause(1.0/60.0)
def run_test(name, i): global RE RE = reynolds[i] global MAX_ITERS MAX_ITERS = max_iters[i] basepath = os.path.join('results', name, 're%s' % RE) if not os.path.exists(basepath): os.makedirs(basepath) ctrl = LBSimulationController(TestLDCSim, TestLDCGeometry) ctrl.run() horiz = np.loadtxt('ldc_golden/vx2d', skiprows=4) vert = np.loadtxt('ldc_golden/vy2d', skiprows=4) plt.plot(horiz[:, 0] * 2 - 1, horiz[:, i+1], label='Paper') plt.plot(vert[:, i+1], 2 * (vert[:, 0] - 0.5), label='Paper') save_output(basepath) plt.legend(loc='lower right') plt.gca().yaxis.grid(True) plt.gca().xaxis.grid(True) plt.gca().xaxis.grid(True, which='minor') plt.gca().yaxis.grid(True, which='minor') plt.title('Lid Driven Cavity, Re = %s' % RE) print os.path.join(basepath, 'results.pdf') plt.savefig(os.path.join(basepath, 'results.pdf'), format='pdf') plt.clf() plt.cla() plt.show()
def on_key(self,event): if event.key == "enter": self.ax.set_title('Aguarde') plt.draw() points = [] for e in xrange(len(self.X)): points.append(City(self.X[e],self.Y[e])) #magic magic = SimulatedAnnealing(points,self.current) points, string = magic.run() self.X = [] self.Y = [] for p in points: self.X.append(p.getX()) self.Y.append(p.getY()) self.set_figure(string) self.ax.fill(self.X, self.Y, edgecolor='r', fill=False) plt.draw() if event.key == 'r': self.X = [] self.Y = [] plt.cla() self.reload() plt.draw()
def PlotResult(): plt_data=result_21cm plt_mean=plt_data.mean() plt_std=plt_data.std() hp.mollview(plt_data,min=plt_mean-plt_std,max=plt_mean+plt_std, title='rebuild_21cm_freq%d' % i) plt.savefig('N_%d_rebuild_21cm_%d.eps' % (N, i)) plt.cla() # plot rebuilt 21cm map, which has subtract its average value plt_data=map1[i,pol]-result_21cm plt_mean=plt_data.mean() plt_std=plt_data.std() hp.mollview(plt_data,min=plt_mean-plt_std,max=plt_mean+plt_std, title='residuals_21cm_freq%d' %i) plt.savefig('N_%d_residuals_21cm%d.eps' % (N, i)) plt_data=map1[i,pol] plt_mean=plt_data.mean() plt_std=plt_data.std() hp.mollview(plt_data,min=plt_mean-plt_std,max=plt_mean+plt_std,title='sim_21cm_freq%d' % i) plt.savefig('N_%d_sim_21cm_%d.eps' % (N, i)) plt.cla() plt_data=map3[i,pol] plt_mean=plt_data.mean() plt_std=plt_data.std() hp.mollview(plt_data,min=plt_mean-plt_std,max=plt_mean+plt_std,title='sim_syn_%d' % i) plt.savefig('N_%d_sim_syn_%d.eps' % (N, i)) plt.clf()
def callback(): request = self.pipe.recv() if request is None: return False # self.fig.suptitle('t={:.8f}'.format(request.t)) for n,f in enumerate(request.flist): ax=self.axes[n] self.fig.sca(ax) plt.cla() # ax.set_title(mp.component_name(self.components[n]) + ' @ t={:.2f} ) ax.set_title(r'$|E|^2, t={:.2f}$'.format(request.t)) ax.set_xlabel(r'$x$') ax.set_ylabel(r'$y$') #mp.component_name(self.components[n]) + ' @ t={:.2f} ) # cb=self.cbs[n] # clim = cb.get_clim() f=f*f if not self.fix_clim: self.clim[0] = min(self.clim[0],np.amin(f)) self.clim[1] = max(self.clim[1],np.amax(f)) img = ax.contourf(self.X,self.Y,np.transpose(f), self.num_contours, cmap=self.cmap, vmin=self.clim[0],vmax=self.clim[1]) ax.set_aspect('equal') self.cbs[n]=self.fig.colorbar(img, cax=self.cbs[n].ax) self.cbs[n].set_clim(self.clim[0],self.clim[1]) self.cbs[n].set_ticks(np.linspace(self.clim[0],self.clim[1],3)) self.cbs[n].draw_all() self.fig.canvas.draw() return True
def update(val): fin=open(sef[int(picker.val)],'r') sefdata=fin.readlines() for i in range(0,4):sefdata.pop(0) ch=[] br=[] ra1=[] zone=[] rf=[] for data in sefdata: liste=data.split() # liste = re.findall(r"[\w.][\f]+",data) br.append(liste[0]) br=map(float,br) ra1.append(liste[2]) ra1=map(float,ra1) zone.append(liste[5]) zone=map(int,zone) rf.append(liste[6]) slide=10.0**val for i,b in enumerate(br): br[i]=br[i]*1e6 ch.append(ra1[i]*br[i]) br[i]=br[i]*slide #for line in ax.lines: print line ax.lines[int(picker.val)*2+1].set_xdata(br) plt.draw() verschiebefaktoren[int(picker.val)]=slide verschiebetemperaturen[int(picker.val)]=temps[int(picker.val)] plt.figure(4) plt.cla() plt.plot(verschiebetemperaturen,verschiebefaktoren) plt.draw() return slide
def print_progress(self, t, losses, sess): if t % self.n_print == 0: print("iter %d loss %.2f " % (t, np.mean(losses))) self.variational.print_params(sess) # Sample functions from variational model mean, std = sess.run([self.variational.m, self.variational.s]) rs = np.random.RandomState(0) zs = rs.randn(10, self.variational.num_vars) * std + mean zs = tf.constant(zs, dtype=tf.float32) inputs = np.linspace(-3, 3, num=400, dtype=np.float32) x = tf.expand_dims(tf.constant(inputs), 1) mus = tf.pack([self.model.mapping(x, z) for z in tf.unpack(zs)]) outputs = sess.run(mus) # Get data y, x = sess.run([self.data.data[:, 0], self.data.data[:, 1]]) # Plot data and functions plt.cla() ax.plot(x, y, 'bx') ax.plot(inputs, outputs.T) ax.set_xlim([-3, 3]) ax.set_ylim([-0.5, 1.5]) plt.draw()
def update(): pyplot.cla() pyplot.axis([0, 255, -128, 128]) pyplot.ylabel("Error (higher means too bright)") pyplot.xlabel("Ideal colour") pyplot.grid() delta = [0, 0, 0] for n, ideal, measured in pop_with_progress(analyse_colours_video(), 50): pyplot.draw() for c in [0, 1, 2]: ideals[c].append(ideal[c]) delta[c] = measured[c] - ideal[c] deltas[c].append(delta[c]) pyplot.plot([ideal[0]], [delta[0]], "rx", [ideal[1]], [delta[1]], "gx", [ideal[2]], [delta[2]], "bx") fits = [fit_fn(ideals[n], deltas[n]) for n in [0, 1, 2]] pyplot.plot( range(0, 256), [fits[0](x) for x in range(0, 256)], "r-", range(0, 256), [fits[1](x) for x in range(0, 256)], "g-", range(0, 256), [fits[2](x) for x in range(0, 256)], "b-", ) pyplot.draw()
def plot_session_PSTH(self, session, tetrode, experiment=-1, site=-1, cluster = None, sortArray='currentFreq', timeRange = [-0.5, 1], replace=0, lw=3, colorEachCond=None): sessionObj = self.get_session_obj(session, experiment, site) sessionDir = sessionObj.ephys_dir() ephysData, bdata, info = self.load_session_data(session, experiment, site, tetrode, cluster) eventOnsetTimes = ephysData['events']['stimOn'] spikeTimestamps = ephysData['spikeTimes'] if bdata is not None: sortArray = bdata[sortArray] if colorEachCond is None: colorEachCond = self.get_colours(len(np.unique(sortArray))) else: sortArray = [] plotTitle = info['sessionDir'] ephysData = ephyscore.load_ephys(sessionObj.subject, sessionObj.paradigm, sessionDir, tetrode, cluster) eventOnsetTimes = ephysData['events']['stimOn'] spikeTimestamps = ephysData['spikeTimes'] if replace==1: plt.cla() elif replace==2: plt.sca(ax) else: plt.figure() plot_psth(spikeTimestamps, eventOnsetTimes, sortArray = sortArray, timeRange=timeRange, lw=lw, colorEachCond=colorEachCond, plotLegend=0)
def plot_session_freq_tuning(self, session, tetrode, experiment = -1, site = -1, cluster = None, sortArray='currentFreq', replace=0, timeRange=[0,0.1]): if replace: plt.cla() else: plt.figure() sessionObj = self.get_session_obj(session, experiment, site) sessionDir = sessionObj.ephys_dir() ephysData, bdata, info = self.load_session_data(session, experiment, site, tetrode, cluster) freqEachTrial = bdata[sortArray] # eventData = self.loader.get_session_events(sessionDir) # eventOnsetTimes = self.loader.get_event_onset_times(eventData) # spikeData = self.loader.get_session_spikes(sessionDir, tetrode, cluster) # spikeTimestamps = spikeData.timestamps eventOnsetTimes = ephysData['events']['stimOn'] spikeTimestamps = ephysData['spikeTimes'] plotTitle = sessionDir freqLabels = ["%.1f"%freq for freq in np.unique(freqEachTrial)/1000] self.one_axis_tc_or_rlf(spikeTimestamps, eventOnsetTimes, freqEachTrial, timeRange=timeRange) ax = plt.gca() ax.set_xticks(range(len(freqLabels))) ax.set_xticklabels(freqLabels, rotation='vertical')
def plot_skus(data, plot_name, save=True): import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import matplotlib.dates as mdates q = data['q'] p = data['ppr'] flag = data['promo_flag'] np = data['npr'] fig, ax = plt.subplots(figsize=(15,8)) q.plot(ax=ax, grid=True, color='black') p.plot(ax=ax, secondary_y=True, grid=True, color='red') np.plot(ax=ax, secondary_y=True, grid=True, color='gray') flag.plot(ax=ax, secondary_y=True, grid=True, color='blue') ax.xaxis.set_major_locator(mdates.MonthLocator(interval=2)) ax.set_ylabel(q.name) ax.right_ax.set_ylabel(p.name) fig.autofmt_xdate() ax.legend() fig.tight_layout() fig.savefig(plot_name) plt.close(fig) plt.cla() return None
def plot_distribution(nx_graph, filename): """ Plots the in/out degree distribution of the Graph :rtype : None :param nx_graph: nx.Digraph() - Directed NetworkX Graph :param filename: String - Name of the file to save the plot """ in_degrees = nx_graph.in_degree() in_values = sorted(set(in_degrees.values())) out_degrees = nx_graph.out_degree() out_values = sorted(set(out_degrees.values())) in_hist = [in_degrees.values().count(x) for x in in_values] out_hist = [out_degrees.values().count(x) for x in out_values] plt.clf() plt.cla() plt.figure() plt.plot(in_values, in_hist,'ro-') # in-degree plt.plot(out_values, out_hist,'bv-') # out-degree # plt.yscale('log') plt.legend(['In-degree','Out-degree']) plt.xlabel('Degree') plt.ylabel('Number of nodes') plt.title('In-Out Degree Distribution') plt.savefig(filename + '.png', format='png') plt.close()
def update(frame_number): plt.cla() if map_msg is not None: for lane in map_msg.hdmap.lane: draw_lane_boundary(lane, ax, 'b', map_msg.lane_marker) draw_lane_central(lane, ax, 'r') for key in map_msg.navigation_path: x = [] y = [] for point in map_msg.navigation_path[key].path.path_point: x.append(point.y) y.append(point.x) ax.plot(x, y, ls='-', c='g', alpha=0.3) if planning_msg is not None: x = [] y = [] for tp in planning_msg.trajectory_point: x.append(tp.path_point.y) y.append(tp.path_point.x) ax.plot(x, y, ls=':', c='r', linewidth=5.0) ax.axvline(x=0.0, alpha=0.3) ax.axhline(y=0.0, alpha=0.3) ax.set_xlim([10, -10]) ax.set_ylim([-10, 200]) y = 10 while y < 200: ax.plot([10, -10], [y, y], ls='-', c='g', alpha=0.3) y = y + 10 plt.yticks(np.arange(10, 200, 10)) adc = plt.Circle((0, 0), 0.3, color='r') plt.gcf().gca().add_artist(adc) ax.relim()
def kinect3DPlotDemo(): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') plt.ion() plt.show() openni2.initialize() dev = openni2.Device.open_any() ds = dev.create_depth_stream() ds.start() while(1): f = ds.read_frame().get_buffer_as_uint16() a = np.ndarray((480,640),dtype=np.uint16,buffer=f) ipts = [] for y in range(180, 300, 20): for x in range(260, 380, 20): ipts.append((x, y, a[y][x])) m = np.matrix(ipts).T fpts = rwCoordsFromKinect(m) #get real world coordinates plt.cla() ax.scatter([pt[0] for pt in fpts], [pt[1] for pt in fpts], [pt[1] for pt in fpts], color='r') plt.draw() p = planeFromPts(np.matrix(random.sample(fpts, 3))) #fit a plane to these points print p plt.pause(.1)
def plotHistory(self,name=''): """ permet une sauvegarde graphique de l'evolution de la population au fil des generations. @param name: chaine de caracteres pour le fichier de sortie """ from os.path import exists, isdir _base = 'datas' if exists(_base) and isdir(_base): _fmt = _base + '/' else: _fmt = '' _fmt += 'graph%s_%s_%d-%d' _name = _fmt % (name,self.alphabet,self.szPop,self.age) if HASPLOT: _max = self.bestEval plt.axis([0, self.age, 0, _max*1.5]) #axes du graphe for i,_lab in enumerate( ('min','moy','max') ): datas = [ self.history[_][0][i] for _ in range(self.age) ] # datas = [ self.history[_][i] for _ in range(self.age) ] plt.plot(datas,label=_lab) _label='%s, pop : %d, bestfitness : %2.3f (age %s) ' %\ (name,self.szPop,self.bestEval,self.quand) plt.title(_label) plt.legend() # plt.show() plt.savefig(_name) #sauvegarde du graphe print( 'sauvegarde dans',_name ) plt.cla() #efface les axes du graphe else: print( 'no plotting output available' )
def testTransientCurrent(self): fileNameBase = '_'.join(self.id().split('.')[-3:]) snp = si.p.SimulatorNumericParser( si.fd.EvenlySpacedFrequencyList(5e6, 10000), cacheFileName=fileNameBase).AddLines([ 'device R1 1 R 5.0', 'device D2 4 currentcontrolledvoltagesource 1.0', 'device G2 1 ground', 'device O2 1 open', 'voltagesource VG1 1', 'device L4 2 L 0.00022', 'device C3 2 C 4.7e-06', 'currentsource CG2 1', 'output D2 2', 'connect D2 2 CG2 1 R1 1', 'connect C3 2 D2 1 L4 2', 'connect G2 1 D2 3', 'output D2 4', 'connect D2 4 O2 1', 'connect C3 1 L4 1 VG1 1' ]) tm = snp.TransferMatrices() td = si.td.wf.TimeDescriptor(-2e-3, int(math.floor((5e-3 - -2e-3) * 10e6)), 10e6) VG1 = si.td.wf.StepWaveform(td, 5., -2e-3) CG2 = si.td.wf.PulseWaveform(td, -0.2, 0., .1e-6) si.td.wf.Waveform.adaptionStrategy = 'SinX' tmp = si.td.f.TransferMatricesProcessor(tm) [Vout, Iout] = tmp.ProcessWaveforms([VG1, CG2]) VinMinusVout = si.td.wf.Waveform(Vout.TimeDescriptor(), [5. - v for v in Vout.Values()]) self.CheckWaveformResult(Iout, 'Waveform_' + fileNameBase + '_Iout.txt', 'current') self.CheckWaveformResult(Vout, 'Waveform_' + fileNameBase + '_Vout.txt', 'voltage') Voutfd = Vout.FrequencyContent() Ioutfd = Iout.FrequencyContent() VinMinusVoutfd = VinMinusVout.FrequencyContent() plot = False if plot: import matplotlib.pyplot as plt voy = Voutfd.Values('dB') ioy = Ioutfd.Values('dB') vivoy = VinMinusVoutfd.Values('dB') vof = Voutfd.Frequencies('MHz') iof = Ioutfd.Frequencies('MHz') vivof = VinMinusVoutfd.Frequencies('MHz') plt.subplot(1, 1, 1) plt.plot(vof, voy, label='Vout') plt.plot(iof, ioy, label='Iout') plt.plot(vivof, vivoy, label='Vin-Vout') plt.xscale('log') plt.show() plt.cla() zoy = [pow(10., (voy[n] - ioy[n]) / 20.) for n in range(len(voy))] ziy = [ pow(10., (vivoy[n] - ioy[n]) / 20.) for n in range(len(voy)) ] zof = Voutfd.Frequencies() zif = VinMinusVoutfd.Frequencies() plt.subplot(1, 1, 1) plt.plot(zof, zoy, label='Zo') plt.plot(zif, ziy, label='Zo') plt.xscale('log') plt.yscale('log') plt.show() # make a complex impedance plot ZloadFrequencies = [] ZloadImpedance = [] ZsourceFrequencies = [] ZsourceImpedance = [] for n in range(len(Voutfd)): try: Zload = Voutfd[n] / Ioutfd[n] ZloadFrequencies.append(Voutfd.Frequencies()[n]) ZloadImpedance.append(Zload) Zsource = VinMinusVoutfd[n] / Ioutfd[n] ZsourceFrequencies.append(Voutfd.Frequencies()[n]) ZsourceImpedance.append(Zsource) except Exception as e: raise e Zloadfd = si.fd.FrequencyDomain( si.fd.GenericFrequencyList(ZloadFrequencies), ZloadImpedance) Zsourcefd = si.fd.FrequencyDomain( si.fd.GenericFrequencyList(ZsourceFrequencies), ZsourceImpedance) plot = False if plot: import matplotlib.pyplot as plt zsy = Zsourcefd.Values('mag') zly = Zloadfd.Values('mag') zsf = Zsourcefd.Frequencies() zlf = Zloadfd.Frequencies() plt.subplot(1, 1, 1) plt.plot(zsf, zsy, label='Zsource') plt.plot(zlf, zly, label='Zload') plt.xscale('log') plt.yscale('log') plt.show()
def pc2obs(voxel_size = 0.3, plot=False, ros=True): global points_raw, color_image_raw, robot_state, bridge, currentStatus, handle_easy, pub, sim_time #print(points_raw) # if type(points_raw) == type(0) or type(color_image_raw) == type(0): if type(points_raw) == type(0) or sim_time == 0.0: print("NOT CONNECTED") sleep(0.1) return False, False, False t1 = time.time() points = pc2.read_points(points_raw, skip_nans=True, field_names=("x", "y", "z")) points = np.array(list(points), dtype=np.float32) if len(points) == 0: return False, False, False t2 = time.time() #print("length pre-processed points: {}".format(len(points))) np_vox = np.ceil((np.max(points, axis=0) - np.min(points, axis=0)) / voxel_size) non_empty_voxel_keys, inverse, nb_pts_per_voxel = np.unique(((points - np.min(points, axis=0)) // voxel_size).astype(int), axis=0, return_inverse=True, return_counts=True) idx_pts_sorted = np.argsort(inverse) voxel_grid = {} grid_barycenter, grid_candidate_center = [], [] last_seen = int(0) for idx, vox in enumerate(non_empty_voxel_keys): voxel_grid[tuple(vox)] = points[idx_pts_sorted[int(last_seen):int(last_seen + nb_pts_per_voxel[idx])]] grid_barycenter.append(np.mean(voxel_grid[tuple(vox)], axis=0)) grid_candidate_center.append(voxel_grid[tuple(vox)][np.linalg.norm(voxel_grid[tuple(vox)] - np.mean(voxel_grid[tuple(vox)], axis=0), axis=1).argmin()]) last_seen += nb_pts_per_voxel[idx] points = np.array(list(filter(lambda x: x[0] != 0, list(grid_candidate_center)))) t3 = time.time() points_layer = [] for i, p in enumerate(points): # When the pointcloud has z-foward axis, the xyz-coordinate order should be [p[0], p[2], -p[1]]. if -p[1] > 0.1 and -p[1] < 0.6: points_layer.append([p[0], p[2], -p[1]]) # When the pointcloud has x-foward axis, the xyz-coordinate order should be [-p[1], p[0], p[2]]. # if p[2] > 0.1 and p[2] < 0.6: # points_layer.append([-p[1], p[0], p[2]]) samples = np.array(points_layer) if plot: print("time took") print(t2-t1) print(t3-t2) print(time.time() - t3) plt.scatter(points[:,0], points[:,2], label='voxel grid filtering') if len(samples): plt.scatter(samples[:,0], samples[:,1], label='height filtering') plt.xlim(-1.5,1.5) plt.ylim(0,6) plt.legend() plt.title("Top view points after filter processing") plt.xlabel("x (m)") plt.ylabel("y (m)") plt.pause(0.05) plt.cla() plt.clf() color_image = color_image_raw # Show images #cv2.namedWindow('RealSense', cv2.WINDOW_AUTOSIZE) #cv2.imshow('RealSense', color_image) #cv2.imshow('RealSense_depth', depth_image) if cv2.waitKey(1) == 27: #esc cv2.destroyAllWindows() rospy.signal_shutdown("esc") if args.csv: f.close() sys.exit(1) if ros: pub_pc2 = pc2.create_cloud(header, fields, samples) pub_pc2.header.stamp = rospy.Time.now() pub.publish(pub_pc2) return samples, robot_state, sim_time
ax.scatter(Kps,Kis,Kds, s=area, c=colors, alpha=0.3,marker='o') ax.set_xlabel('Kp') ax.set_ylabel('Kd') ax.set_zlabel('Ki') ax.axis([0,10,0,10]) plt.show(block=False) plt.pause(1) done = False for x in range(0,GA.numGeracoes): print("Gen: %d ====================================" % (x+1)) melhorFitness,indexMelhorIndividuo,totalMutacoes = GA.itera() #plt.clf() plt.cla() if done: break bola = Circulo(1,screenCenter[0],screenCenter[1],raio,corBola) plataforma = Retangulo(1,screenCenter[0],screenCenter[1],400,10,corPlataforma) kp = GA.populacao[indexMelhorIndividuo].cromossomos[0] ki = GA.populacao[indexMelhorIndividuo].cromossomos[1] kd = GA.populacao[indexMelhorIndividuo].cromossomos[2] initalPos = 0.5 done = simula(initalPos,kp,ki,kd,dividerMain) for iterador, individuo in enumerate(GA.populacao):
#print (np.around(y_std[0, 0], 3)) #print (np.around(y_std[1, 0], 3)) #print (np.around(y_std[1, 1], 3)) # print (np.around(y_mac_per_pJ[0, 0], 3)) # print (np.around(y_mac_per_pJ[1, 0], 3)) # print (np.around(y_mac_per_pJ[1, 1], 3)) #################### plot_layer = 0 #################### plt.cla() ax = plt.gca() # plt.plot(x, y_mac_per_cycle[0, 0, :, plot_layer], color='green', marker="D", markersize=5, label='baseline') plt.plot(x, 2 * 700e6 * np.sum(y_mac_per_cycle[1, 0, :, :], axis=1) / 1e12, color='blue', marker="s", markersize=5, label='skip') plt.plot(x, 2 * 700e6 * np.sum(y_mac_per_cycle[1, 1, :, :], axis=1) / 1e12, color='black', marker="^", markersize=6, label='cards') plt.ylim(bottom=0) plt.xticks(x) # plt.xticks([0.08, 0.12]) # plt.yticks([]) # ax.axes.xaxis.set_ticklabels([]) # ax.axes.yaxis.set_ticklabels([]) plt.grid(True, linestyle='dotted') fig = plt.gcf() # fig.set_size_inches(4., 2.5) plt.tight_layout() plt.legend()
#--------------------------------------------Insights-------------------------------- #check centroid values by taking mean of each attribute grouped by cluster print(df.groupby('Clus_km').mean()) print(X[:, 0]) area = np.pi * ( X[:, 1] )**2 #taking area of everyone row in attribtue 'education', correlates to the size of the data point cirlce plt.scatter( X[:, 0], X[:, 3], s=area, c=labels.astype(np.float), alpha=0.5) #alpha is for level of transparenccy, c is for color sequence plt.xlabel('Age', fontsize=18) plt.ylabel('Income', fontsize=16) plt.savefig('k_means.png') #------------------------------Further Insights------------------------------------------------ from mpl_toolkits.mplot3d import Axes3D fig = plt.figure(1, figsize=(8, 6)) #stroes previos figure in fig object plt.clf() #clears current figs canvas so that a new fig may be drawn on pyplot ax = Axes3D( fig, rect=[0, 0, .95, 1], elev=48, azim=134 ) #elev = elevation viewing angle, azim is another viewing angle, rect = size of graph plt.cla() #clears axis so you can relabel the x,y,z axes ax.set_xlabel('Education') ax.set_ylabel('Age') ax.set_zlabel('Income') ax.scatter(X[:, 1], X[:, 0], X[:, 3], c=labels.astype(np.float)) plt.savefig('Axes3D.png')
def test_net(raw_rcnn_data_file_list, imdb, max_per_image=1200, thresh=0.05, vis=False): """Test a Fast R-CNN network on an image database.""" """NEW: replace the thresh""" thresh = cfg.TEST.POST_PROCESS_THRESH num_images = len(imdb.image_index) # all detections are collected into: # all_boxes[cls][image] = N x 5 array of detections in # (x1, y1, x2, y2, score) all_boxes = [[[] for _ in xrange(num_images)] for _ in xrange(imdb.num_classes)] output_dir = os.path.abspath( os.path.join(cfg.ROOT_DIR, 'output', 'test_ensemble/')) if not (os.path.exists(output_dir)): os.makedirs(output_dir) # timers _t = {'im_detect': Timer(), 'misc': Timer()} if not cfg.TEST.HAS_RPN: roidb = imdb.roidb with open(raw_rcnn_data_file_list[0].strip(), 'rb') as f: raw_rcnn_data = cPickle.load(f) for i in range(1, len(raw_rcnn_data_file_list)): with open(raw_rcnn_data_file_list[i].strip(), 'rb') as f: raw_rcnn_data_temp = cPickle.load(f) for j in range(len(raw_rcnn_data['scores'])): raw_rcnn_data['scores'][j] = np.concatenate( (raw_rcnn_data['scores'][j], raw_rcnn_data_temp['scores'][j])) raw_rcnn_data['boxes'][j] = np.concatenate( (raw_rcnn_data['boxes'][j], raw_rcnn_data_temp['boxes'][j])) # print(raw_rcnn_data) for i in xrange(num_images): # filter out any ground truth boxes if cfg.TEST.HAS_RPN: box_proposals = None else: # The roidb may contain ground-truth rois (for example, if the roidb # comes from the training or val split). We only want to evaluate # detection on the *non*-ground-truth rois. We select those the rois # that have the gt_classes field set to 0, which means there's no # ground truth. box_proposals = roidb[i]['boxes'][roidb[i]['gt_classes'] == 0] im = cv2.imread(imdb.image_path_at(i)) _t['im_detect'].tic() scores = raw_rcnn_data['scores'][i] boxes = raw_rcnn_data['boxes'][i] # print(scores) # print(scores.shape) # print(boxes) # print(boxes.shape) # print('-----------') _t['im_detect'].toc() _t['misc'].tic() if vis: image = im[:, :, (2, 1, 0)] plt.cla() plt.imshow(image) # skip j = 0, because it's the background class for j in xrange(1, imdb.num_classes): inds = np.where(scores[:, j] > thresh)[0] cls_scores = scores[inds, j] cls_boxes = boxes[inds, j * 4:(j + 1) * 4] cls_dets = np.hstack((cls_boxes, cls_scores[:, np.newaxis])) \ .astype(np.float32, copy=False) keep = nms(cls_dets, cfg.TEST.NMS) cls_dets = cls_dets[keep, :] if vis: vis_detections(image, imdb.classes[j], cls_dets) all_boxes[j][i] = cls_dets if vis: plt.show() # Limit to max_per_image detections *over all classes* if max_per_image > 0: image_scores = np.hstack( [all_boxes[j][i][:, -1] for j in xrange(1, imdb.num_classes)]) if len(image_scores) > max_per_image: image_thresh = np.sort(image_scores)[-max_per_image] for j in xrange(1, imdb.num_classes): keep = np.where(all_boxes[j][i][:, -1] >= image_thresh)[0] all_boxes[j][i] = all_boxes[j][i][keep, :] _t['misc'].toc() logging.warning('im_detect: {:d}/{:d} {:.3f}s {:.3f}s'.format( i + 1, num_images, _t['im_detect'].average_time, _t['misc'].average_time)) """写我自己的输出""" if imdb.name.startswith('sz'): my_result_file = os.path.join(output_dir, 'sz_result_test_ensemble.json') result_json = {} with open(my_result_file, 'w') as f: for cls, all_pic_result in enumerate(all_boxes): for image_index_id, result_n in enumerate(all_pic_result): for result in result_n: if cls == 0: break real_cls = cls if cls == 4: """针对比赛这里的class要转换""" real_cls = 20 result_key = str( imdb._image_index[image_index_id]) + '.jpg' if result_key not in result_json: result_json[result_key] = [] result_json[result_key].append([ float(result[0]), float(result[1]), float(result[2]), float(result[3]), real_cls, float(result[4]) ]) f.write(json.dumps(result_json)) print('Result has been written into: %s' % my_result_file) det_file = os.path.join(output_dir, 'detections_test_ensemble.pkl') with open(det_file, 'wb') as f: cPickle.dump(all_boxes, f, cPickle.HIGHEST_PROTOCOL) print 'Evaluating detections' result = imdb.evaluate_detections(all_boxes, output_dir) logging.warning('Thresh is %f!' % float(thresh)) logging.warning('Max box is %d' % max_per_image) logging.warning('NMS is %f' % cfg.TEST.NMS) return result
def testVRMComplicatedProcessing(self): os.chdir(os.path.dirname(os.path.realpath(__file__))) fileNameBase = '_'.join(self.id().split('.')) Vout = si.td.wf.Waveform().ReadFromFile( 'Waveform_TestPI_TestPI_testVRMParasitics_Vout.txt') Vin = si.td.wf.Waveform().ReadFromFile( 'Waveform_TestPI_TestPI_testVRMParasitics_Vin.txt') Vlcalc = Vin - Vout K = Vlcalc.TimeDescriptor().K T = 1. / Vlcalc.TimeDescriptor().Fs L = 220e-6 R = .1 C = 4.7e-6 Lc = 100e-9 Rc = 200e-3 A = T * T / (T * T + Lc * C + Rc * C * T) print(A) il = [0. for k in range(len(Vlcalc))] vl = Vlcalc.Values() il[0] = vl[0] * T / (L + R * T) for k in range(1, K): il[k] = vl[k] * T / (L + R * T) + il[k - 1] * L / (L + R * T) Ilcalc = si.td.wf.Waveform(Vlcalc.TimeDescriptor(), il) iout = [0. for k in range(len(Ilcalc))] vout = Vout.Values() il = si.td.wf.Waveform().ReadFromFile( 'Waveform_TestPI_TestPI_testVRMParasitics_Il.txt').Values() ilz0 = 1. ilz1 = -C * A * (2 * Lc + Rc * T) / (T * T) ilz2 = Lc * C * A / (T * T) voutz0 = -C / T * A voutz1 = C / T * A ioutz1 = C * A * (2 * Lc + Rc * T) / (T * T) ioutz2 = -Lc * C * A / (T * T) iout[0] = il[0] * ilz0 + vout[0] * voutz0 iout[1] = il[1] * ilz0 + il[0] * ilz1 + vout[1] * voutz0 + vout[ 0] * voutz1 + iout[0] * ioutz1 for k in range(2, K): iout[k] = il[k] * ilz0 + il[k - 1] * ilz1 + il[ k - 2] * ilz2 + vout[k] * voutz0 + vout[k - 1] * voutz1 + iout[ k - 1] * ioutz1 + iout[k - 2] * ioutz2 Ioutcalc = si.td.wf.Waveform(Vlcalc.TimeDescriptor(), iout) Il = si.td.wf.Waveform().ReadFromFile( 'Waveform_TestPI_TestPI_testVRMParasitics_Il.txt') Vl = si.td.wf.Waveform().ReadFromFile( 'Waveform_TestPI_TestPI_testVRMParasitics_Vl.txt') Iout = si.td.wf.Waveform().ReadFromFile( 'Waveform_TestPI_TestPI_testVRMParasitics_Iout.txt') plot = False if plot: import matplotlib.pyplot as plt plt.subplot(1, 1, 1) plt.plot(Ilcalc.Times(), Ilcalc.Values(), label='Ilcalc') plt.plot(Il.Times(), Il.Values(), label='Il') plt.legend(loc='upper right', labelspacing=0.1) plt.show() plt.cla() plt.plot(Ioutcalc.Times(), Ioutcalc.Values(), label='Ioutcalc') plt.plot(Iout.Times(), Iout.Values(), label='Iout') plt.legend(loc='upper right', labelspacing=0.1) plt.show() plt.cla()
def plot(func, xpoints, color_name, xlabel, ylabel, theme, gui, line_style, file_path, discrete=False): # Show plot summary print('***** Plot Summary *****') print("Funtion: {}".format(func)) if discrete: print("Plotting funcion for points: {}".format(', '.join( map(str, xpoints)))) else: print("Starting abcissa: {}".format(xpoints[0])) print("Ending abcissa: {}".format(xpoints[-1])) if (len(xpoints) > 1): print("Stepsize: {}".format(xpoints[1] - xpoints[0])) print("Color: {}".format(color_name)) print("X-label: {}".format(xlabel)) print("Y-label: {}".format(ylabel)) print() if theme == 'dark': mplstyle.use('dark_background') else: mplstyle.use('default') xvals = xpoints yvals = create_y_values(func, xvals) try: # Check if color is hex code is_hex = re.search(r'^#(?:[0-9a-fA-F]{3}){1,2}$', color_name) if not is_hex: colors = mcolors.cnames if color_name not in colors: print(color_name, ": Color not found.") color_name = 'blue' plt.plot(xvals, yvals, color=color_name, linewidth=2.0, linestyle=line_style) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(r'$ ' + func + ' $') except Exception: print("An error occured.") if file_path != "": plt.savefig(file_path) plt.grid(True) if not gui: plt.show() else: if not os.path.exists('.temp/'): os.mkdir('.temp/') plt.savefig(".temp/generated_plot.png") plt.cla() plt.clf()
def SPDC(wavep, angle, L, distz, wp): wavep = wavep / 1000.0 # wavelength of pump field in 405nm ### angle = 28.9 # Angle in degree thetap = np.radians(angle) # thetap in radians45.64, 42.58 40.5 42.148 L = L * 1000.00 # Crystal thickness in 2mm distz = distz * 10000.0 # distz in cm 100cm , wp in um ######################################## #*******Dispersion relation o ray*************** def noo(n): global wavep n2 = 2.7405 + ((0.0184) / ((n**2) - 0.0179)) - (0.0155 * n**2) rio = round(math.sqrt(n2), 4) return rio #********Dispersion relation e ray*************** def neo(n): global wavep n2 = 2.3730 + ((0.0128) / ((n**2) - 0.0156)) - (0.0044 * n**2) rio = round(math.sqrt(n2), 4) return rio ############################################# #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #####Two photon wavefunction############## def two_photon_wavefunction(xs, ys, xi, yi, wp): ss = (np.square(xs) + np.square(ys)) + (np.square(xi) + np.square(yi)) + ( 2 * np.sqrt((np.square(xs) + np.square(ys)) * (np.square(xi) + np.square(yi))) * np.cos(np.arctan2(ys, xs) - np.arctan2(yi, xi))) kp = (2 * (np.pi)) / wavep kpz = (kp * etap) + (alphap * (xs + xi)) - ( (1 / (2 * kp * etap)) * (np.square(betap * (xs + xi)) + np.square(gammap * (ys + yi)))) ksz = (kp * nobar / 2) - ((1 / (kp * nobar)) * (np.square(xs) + np.square(ys))) kiz = (kp * nobar / 2) - ((1 / (kp * nobar)) * (np.square(xi) + np.square(yi))) tmp = ((ksz + kiz - kpz) * (L / 2)) #------------------------------------------------------------------------------------- ksze = ((kp / 2.0) * etas) + (alphas * (xs)) - ( (1 / (kp * etas)) * (np.square(betas * xs) + np.square(gammas * ys))) tmpeo = ((ksze + kiz - kpz) * (L / 2)) #---------------------------------------------------------------------------------------------- kize = ((kp / 2.0) * etai) + (alphai * (xi)) - ( (1 / (kp * etai)) * (np.square(betai * xi) + np.square(gammai * yi))) tmpoe = ((ksz + kize - kpz) * (L / 2)) #-------------------------------------------------------------------------------------------- pumpfield = np.exp(-(wp**2 + ((2j) * (distz / (kp * etap)))) * (ss / 4.0)) fullfunction = pumpfield * ( (np.sinc(tmpeo / (np.pi)) * np.exp(-1.0j * tmpeo)) + (np.sinc(tmpoe / (np.pi)) * np.exp(-1.0j * tmpoe)) + (np.sinc(tmp / (np.pi)) * np.exp(-1.0j * tmp))) return fullfunction #----------------------------------------------------- #*************************************************** if angle <= 41.0: rho = 0.6 elif angle > 41 and angle < 41.5: rho = 0.8 elif angle >= 41.5 and angle < 41.8: rho = 0.9 elif angle > 41.8 and angle < 45: rho = 1.0 elif angle >= 45.0 and angle < 50.0: rho = 1.5 elif angle >= 50.0 and angle < 65.0: rho = 2.0 elif angle >= 65: rho = 2.8 ###print (rho) ###rho=2.8 grdpnt = 200 dx = (2 * rho / grdpnt) xs, ys = np.meshgrid(np.linspace(-rho, rho, grdpnt), np.linspace(-rho, rho, grdpnt)) # alpha ,beta ,gamma, eta *********************** no = noo(wavep) ne = neo(wavep) den = np.square(no * np.sin(thetap)) + np.square(ne * np.cos(thetap)) alphap = ((np.square(no) - np.square(ne)) * (np.sin(thetap)) * (np.cos(thetap))) / den betap = (no * ne) / den gammap = no / math.sqrt(den) etap = ne * gammap nobar = noo(2 * wavep) #------------------8888888888888------------------------ nos = noo(2 * wavep) nes = neo(2 * wavep) thetas = thetap - np.arctan2(ys, xs) dens = np.square(nos * np.sin(thetap)) + np.square(nes * np.cos(thetap)) alphas = ((np.square(nos) - np.square(nes)) * (np.sin(thetap)) * (np.cos(thetap))) / dens betas = (nos * nes) / dens gammas = nos / np.sqrt(dens) etas = nes * gammas nobar = noo(2 * wavep) ###etapp = (no*ne)/math.sqrt(den) #########For wavefunction(e --> oo) ################### funcmat = np.zeros([grdpnt, grdpnt]) funcmat1 = np.zeros([grdpnt, grdpnt]) for k in np.arange(-5, 5): for m in np.arange(-5, 5): #//////////////////////////////////////////////////////// noi = noo(2 * wavep) nei = neo(2 * wavep) thetai = thetap + np.arctan2(-ys + m * dx, -xs + k * dx) deni = np.square(noi * np.sin(thetap)) + np.square( nei * np.cos(thetap)) alphai = ((np.square(noi) - np.square(nei)) * (np.sin(thetap)) * (np.cos(thetap))) / deni betai = (noi * nei) / deni gammai = noi / np.sqrt(deni) etai = nei * gammai nobar = noo( 2 * wavep ) #88888888888888__________________----************************////////////////////// funcmat = funcmat + (np.square( np.absolute( two_photon_wavefunction(xs, ys, -xs + k * dx, -ys + m * dx, wp)))) * dx * dx plt.imshow(funcmat) plt.colorbar() plt.clim(0.0000001, 0.000045) # (0.0000001,0.000045) plt.title('Angle =%g' % (angle)) ##__________________________________________________________________________________________________## if not os.path.isdir('static'): os.mkdir('static') else: # Remove old plot files for filename in glob.glob(os.path.join('static', '*.png')): os.remove(filename) # Use time since Jan 1, 1970 in filename in order make # a unique filename that the browser has not chached plotfile = os.path.join('static', str(time.time()) + '.png') plt.savefig(plotfile) plt.cla() plt.clf() return plotfile
def plot_line(arrays, color_name, xlabel, ylabel, theme, gui, line_style, file_path): # Show plot summary print('***** Plot Summary *****') print('Arrays: {}'.format(arrays)) print('Color: {}'.format(color_name)) print('X-label: {}'.format(xlabel)) print('Y-label: {}'.format(ylabel)) if theme == 'dark': mplstyle.use('dark_background') else: mplstyle.use('default') try: # Check if color is hex code is_hex = re.search(r'^#(?:[0-9a-fA-F]{3}){1,2}$', color_name) if not is_hex: colors = mcolors.cnames if color_name not in colors: print(color_name, ": Color not found.") color_name = 'blue' # Extract numbers from X-array xvals = list(map(float, arrays[1:arrays.find(']')].split(','))) # Extract numbers from Y-array yvals = list( map(float, arrays[arrays.find(']') + 3:len(arrays) - 1].split(','))) if len(xvals) == len(yvals): plt.plot(xvals, yvals, color=color_name, linewidth=2.0, linestyle=line_style) plt.savefig(file_path) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(r'$ ' + 'Line:' + str(xvals) + ',' + str(yvals) + ' $') if file_path != "": plt.savefig(file_path) else: print("Error: You need same number of X and Y values") except Exception: print("An error occured.") if file_path != "": plt.savefig(file_path) plt.grid(True) if not gui: plt.show() else: if not os.path.exists('.temp/'): os.mkdir('.temp/') plt.savefig(".temp/generated_plot.png") plt.cla() plt.clf()
def display_examples_histogram_of_n(self, examples_loaction, plot_area): maps6 = [] maps7 = [] maps8 = [] maps9 = [] maps10 = [] for i in range(10): maps6.append( self.read_constituency_map_from_file( os.path.join(examples_loaction, "map6 " + str(i) + ".txt"))) maps7.append( self.read_constituency_map_from_file( os.path.join(examples_loaction, "map7 " + str(i) + ".txt"))) maps8.append( self.read_constituency_map_from_file( os.path.join(examples_loaction, "map8 " + str(i) + ".txt"))) maps9.append( self.read_constituency_map_from_file( os.path.join(examples_loaction, "map9 " + str(i) + ".txt"))) maps10.append( self.read_constituency_map_from_file( os.path.join(examples_loaction, "map10 " + str(i) + ".txt"))) plt.scatter(maps6[9].display_graph()[1], maps6[9].display_graph()[0], c=maps6[9].display_graph()[2], cmap='nipy_spectral', s=plot_area) plt.xlabel('Longitude', fontsize=14) plt.ylabel('Latitude', fontsize=14) plt.savefig("histogram 6 n") plt.cla() plt.scatter(maps7[9].display_graph()[1], maps7[9].display_graph()[0], c=maps7[9].display_graph()[2], cmap='nipy_spectral', s=plot_area) plt.xlabel('Longitude', fontsize=14) plt.ylabel('Latitude', fontsize=14) plt.savefig("histogram 7 n") plt.cla() plt.scatter(maps8[9].display_graph()[1], maps8[9].display_graph()[0], c=maps8[9].display_graph()[2], cmap='nipy_spectral', s=plot_area) plt.xlabel('Longitude', fontsize=14) plt.ylabel('Latitude', fontsize=14) plt.savefig("histogram 8 n") plt.cla() plt.scatter(maps9[9].display_graph()[1], maps9[9].display_graph()[0], c=maps9[9].display_graph()[2], cmap='nipy_spectral', s=plot_area) plt.xlabel('Longitude', fontsize=14) plt.ylabel('Latitude', fontsize=14) plt.savefig("histogram 9 n") plt.cla() plt.scatter(maps10[9].display_graph()[1], maps10[9].display_graph()[0], c=maps10[9].display_graph()[2], cmap='nipy_spectral', s=plot_area) plt.xlabel('Longitude', fontsize=14) plt.ylabel('Latitude', fontsize=14) plt.savefig("histogram 10 n") plt.cla()
def main(): # calculate the true result of the funtion ground_truth = np.dot(np.linalg.inv(Q), b) print('groud truth is: ', ground_truth) print('true min value is:', f(ground_truth)) # visualization prepare fig = plt.figure(figsize=(14, 14)) ax = fig.add_subplot(111, projection='3d') # set initial point x = np.array([-1.0, -1.0]).T learning_rate = 0.01 threshold = 1e-4 iteration_num = 0 recorder = [x] gradient = df(x) # start iteration while np.linalg.norm(gradient) > threshold: # update new point x = x - learning_rate * gradient # update gradient gradient = df(x) # update num iteration_num += 1 # update recorder recorder.append(x) # visualization if iteration_num % 10 == 0: plt.cla() # visualize surface X = np.arange(-1.5, 1.5, 0.1) Y = np.arange(-1.5, 1.5, 0.1) X, Y = np.meshgrid(X, Y) Z = np.zeros_like(X) for i in range(0, X.shape[0]): for j in range(0, X.shape[1]): Z[i, j] = f(np.array([X[i, j], Y[i, j]]).T) ax.plot_surface(X, Y, Z) # visualize gradient descent recorder_x, recorder_y, recorder_z = [], [], [] for i in range(0, len(recorder)): recorder_x.append(recorder[i][0]) recorder_y.append(recorder[i][1]) recorder_z.append(f(np.array(recorder[i]).T)) # print(recorder_x, recorder_y, recorder_z) ax.plot3D(recorder_x, recorder_y, recorder_z, color='r', marker='.') plt.pause(0.1) print('result is: ', x) print('calculated min value is: ', f(x)) print('iteration number is: ', iteration_num) plt.cla() # visualize surface X = np.arange(-1.5, 1.5, 0.1) Y = np.arange(-1.5, 1.5, 0.1) X, Y = np.meshgrid(X, Y) Z = np.zeros_like(X) for i in range(0, X.shape[0]): for j in range(0, X.shape[1]): Z[i, j] = f(np.array([X[i, j], Y[i, j]]).T) ax.plot_surface(X, Y, Z) # visualize gradient descent recorder_x, recorder_y, recorder_z = [], [], [] for i in range(0, len(recorder)): recorder_x.append(recorder[i][0]) recorder_y.append(recorder[i][1]) recorder_z.append(f(np.array(recorder[i]).T)) ax.plot3D(recorder_x, recorder_y, recorder_z, color='r', marker='.') ax.scatter([recorder_x[-1]], [recorder_y[-1]], [recorder_y[-1]], marker='*') plt.show()
def plot_datasets(self, data, fname, extra_labels, showreboots=False, output='pdf'): """ Plot timeseries data (of type dataname). The data can be either simple (one or no datapoint at any point in time, or indexed (by indextype). dataname is assumed to be in the form of [title, [label1, label2, ...], [data1, data2, ...]] extra_labels is a list of tuples [(datetime, 'label'), ...] """ sar_parser = self.sar_parser title = data[0][0] unit = data[0][1] axis_labels = data[0][2] datanames = data[1] if not isinstance(datanames, list): raise Exception("plottimeseries expects a list of datanames: %s" % data) fig = plt.figure(figsize=(10.5, 6.5)) axes = fig.add_subplot(111) axes.set_title('{0} time series'.format(title), fontsize=12) axes.set_xlabel('Time') axes.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d %H:%M')) # Twenty minutes. Could probably make it a parameter axes.xaxis.set_minor_locator(mdates.MinuteLocator(interval=20)) fig.autofmt_xdate() ylabel = title if unit: ylabel += " - " + unit axes.set_ylabel(ylabel) y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False) axes.yaxis.set_major_formatter(y_formatter) axes.yaxis.get_major_formatter().set_scientific(False) color_norm = colors.Normalize(vmin=0, vmax=len(datanames) - 1) scalar_map = cm.ScalarMappable(norm=color_norm, cmap=plt.get_cmap('Set1')) timestamps = self.timestamps() counter = 0 for i in datanames: try: dataset = [sar_parser._data[d][i] for d in timestamps] except: print("Key {0} does not exist in this graph".format(i)) raise axes.plot(timestamps, dataset, 'o:', label=axis_labels[counter], color=scalar_map.to_rgba(counter)) counter += 1 # Draw extra_labels if extra_labels: for extra in extra_labels: axes.annotate(extra[1], xy=(mdates.date2num(extra[0]), sar_parser.find_max(extra[0], datanames)), xycoords='data', xytext=(30, 30), textcoords='offset points', arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) # If we have a sosreport draw the reboots if showreboots and sar_parser.sosreport is not None and \ sar_parser.sosreport.reboots is not None: reboots = sar_parser.sosreport.reboots for reboot in reboots.keys(): reboot_date = reboots[reboot]['date'] rboot_x = mdates.date2num(reboot_date) (xmin, xmax) = plt.xlim() (ymin, ymax) = plt.ylim() if rboot_x < xmin or rboot_x > xmax: continue axes.annotate('', xy=(mdates.date2num(reboot_date), ymin), xycoords='data', xytext=(-30, -30), textcoords='offset points', arrowprops=dict(arrowstyle="->", color='blue', connectionstyle="arc3,rad=-0.1")) # Show any data collection gaps in the graph gaps = sar_parser.find_data_gaps() if len(gaps) > 0: for i in gaps: (g1, g2) = i x1 = mdates.date2num(g1) x2 = mdates.date2num(g2) (ymin, ymax) = plt.ylim() axes.add_patch( Rectangle((x1, ymin), x2 - x1, ymax - ymin, facecolor="lightgrey")) # Add a grid to the graph to ease visualization axes.grid(True) lgd = None # Draw the legend only when needed if len(datanames) > 1 or \ (len(datanames) == 1 and len(datanames[0].split('#')) > 1): # We want the legends box roughly square shaped # and not take up too much room props = matplotlib.font_manager.FontProperties(size='xx-small') if len(datanames) < LEGEND_THRESHOLD: cols = int((len(datanames)**0.5)) lgd = axes.legend(loc=1, ncol=cols, shadow=True, prop=props) else: cols = int(len(datanames)**0.6) lgd = axes.legend(loc=9, ncol=cols, bbox_to_anchor=(0.5, -0.29), shadow=True, prop=props) if len(datanames) == 0: return None try: if lgd: plt.savefig(fname, bbox_extra_artists=(lgd, ), bbox_inches='tight') else: plt.savefig(fname, bbox_inches='tight') except: import traceback print(traceback.format_exc()) import sys sys.exit(-1) plt.cla() plt.clf() plt.close('all')
def visualize_path(self, edge, path, start): def coord_transform(p): return [2 * p[1] + 0.5, 2 * p[0] + 0.5] if do_animation: last = path[0][0] trajectory = [[last[1]], [last[0]]] for p, q in path: distance = math.hypot(p[0] - last[0], p[1] - last[1]) if distance <= 1.0: trajectory[0].append(p[1]) trajectory[1].append(p[0]) else: ipx, ipy = self.get_interpolated_path(last, p) trajectory[0].extend(ipy) trajectory[1].extend(ipx) last = q trajectory[0].append(last[1]) trajectory[1].append(last[0]) for idx, state in enumerate(np.transpose(trajectory)): plt.cla() # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect( 'key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) # draw spanning tree plt.imshow(self.occ_map, 'gray') for p, q in edge: p = coord_transform(p) q = coord_transform(q) plt.plot([p[0], q[0]], [p[1], q[1]], '-oc') sx, sy = coord_transform(start) plt.plot([sx], [sy], 'pr', markersize=10) # draw move path plt.plot(trajectory[0][:idx + 1], trajectory[1][:idx + 1], '-k') plt.plot(state[0], state[1], 'or') plt.axis('equal') plt.grid(True) plt.pause(0.01) else: # draw spanning tree plt.imshow(self.occ_map, 'gray') for p, q in edge: p = coord_transform(p) q = coord_transform(q) plt.plot([p[0], q[0]], [p[1], q[1]], '-oc') sx, sy = coord_transform(start) plt.plot([sx], [sy], 'pr', markersize=10) # draw move path last = path[0][0] for p, q in path: distance = math.hypot(p[0] - last[0], p[1] - last[1]) if distance == 1.0: plt.plot([last[1], p[1]], [last[0], p[0]], '-k') else: ipx, ipy = self.get_interpolated_path(last, p) plt.plot(ipy, ipx, '-k') plt.arrow(p[1], p[0], q[1] - p[1], q[0] - p[0], head_width=0.2) last = q plt.show()
def main(): print(__file__ + " start!!") # start and goal position sx = 10.0 # [m] sy = 10.0 # [m] sz = 10.0 gx = 50.0 # [m] gy = 50.0 # [m] gz = 50.0 robot_size = 5.0 # [m] ox = [] oy = [] oz = [] for i in range(60): for j in range(60): oy.append(i) ox.append(0.00) oz.append(j) for i in range(60): for j in range(60): oy.append(i) ox.append(60.00) oz.append(j) for i in range(60): for j in range(2,12): for k in range(20,25): oy.append(j) ox.append(i) oz.append(k) for i in range(60): for j in range(55,60): for k in range(40,50): oy.append(j) ox.append(i) oz.append(k) for i in range(20,30): for j in range(25,30): for k in range(20,25): oy.append(j) ox.append(i) oz.append(k) for i in range(30,40): for j in range(30,35): for k in range(35,40): oy.append(j) ox.append(i) oz.append(k) ox = np.array(ox).astype(float) oy = np.array(oy).astype(float) oz = np.array(oz).astype(float) while(1): ox,oy,oz = move_obs(ox,oy,oz) # print(ox[-1:-250]) go = [gx,gy,gz] current_point1 = [sx,sy,sz] print(current_point1) dis = np.linalg.norm(np.asarray(go)-np.asarray(current_point1)) print(dis) if(dis<5): print("Goal Reached") break # gx = ((ogx-sx)*15)/(dis) + sx # gy = ((ogy-sy)*15)/(dis) + sy # gz = ((ogz-sz)*15)/(dis) + sz plt.cla() if show_animation: ax.scatter(ox, oy, oz, color='g', marker = "o") ax.scatter(sx, sy, sz, color='r', marker = "^"); ax.scatter(gx, gy, gz, color='r', marker = "^"); u = np.linspace(0, np.pi, 10) v = np.linspace(0, 2 * np.pi, 10) x = sx+15*np.outer(np.sin(u), np.sin(v)) y = sy+15*np.outer(np.sin(u), np.cos(v)) z = sz+15*np.outer(np.cos(u), np.ones_like(v)) ax.plot_wireframe(x, y, z, color="b") nox = [] noy = [] noz = [] for i in range(len(ox)): obs = [ox[i],oy[i],oz[i]] current_point1 = [sx,sy,sz] if(np.linalg.norm(np.asarray(current_point1)-np.asarray(obs))<15): nox.append(ox[i]) noy.append(oy[i]) noz.append(oz[i]) print(len(ox),len(nox)) rx, ry, rz= PRM_planning(sx, sy, sz, gx, gy, gz, nox, noy, noz, robot_size) nx=rx[-2] ny=ry[-2] nz=rz[-2] sx = ((nx-sx)*15)/(dis) + sx sy = ((ny-sy)*15)/(dis) + sy sz = ((nz-sz)*15)/(dis) + sz if show_animation: ax.plot(np.array(rx),np.array(ry),np.array(rz)) # print(rx) # ax.scatter3D(rx, ry, rz, color='red', s=10) ax.scatter(rx, ry, rz, color='r', marker = "o") # plt.figure() plt.draw() plt.pause(0.1)
def train(self): self.Wji = np.random.rand(self.Nh, self.Ni) * self.Wini self.Wkj = np.random.rand(self.Ns, self.Nh + 1) * self.Wini self.taWji = np.ones((self.Nh, self.Ni)) * self.delta0 self.taWkj = np.ones((self.Ns, self.Nh + 1)) * self.delta0 grji_ant = grkj_ant = 0 MSE = np.zeros(self.epoch_max) plt.ion() for epoca in xrange(self.epoch_max): gradji = gradkj = 0 deltaji = np.zeros(self.Wji.shape) deltakj = np.zeros(self.Wkj.shape) z = np.zeros(self.N) E = np.zeros(self.N) for i in xrange(self.N): xi = np.array([-1, self.X_train[i]]).reshape(1, -1) netj = np.dot(self.Wji, xi.T) #yj = np.tanh(netj.T) yj = 1 / (1 + np.exp(-netj.T)) yj_pol = np.insert(yj[0], 0, -1).reshape(1, -1) z[i] = np.dot(self.Wkj, yj_pol.T)[0][0] e = self.d[i] - z[i] #gradji += np.dot((-e * self.Wkj[:,1:] * (1 - yj**2)).T, xi) gradji += np.dot((-e * self.Wkj[:, 1:] * yj * (1 - yj)).T, xi) gradkj += (-e * yj_pol) E[i] = 0.5 * e**2 grji = np.sign(gradji) grkj = np.sign(gradkj) if epoca == 0: self.Wkj += (-self.delta0 * gradkj) self.Wji += (-self.delta0 * gradji) else: Dji = grji * grji_ant Dkj = grkj * grkj_ant sizeji = Dji.shape sizekj = Dkj.shape for i in xrange(sizeji[0]): for j in xrange(sizeji[1]): if (Dji[i, j] > 0): self.taWji[i, j] = min( self.taWji[i, j] * self.eta_plus, self.delta_max) elif (Dji[i, j] < 0): self.taWji[i, j] = max( self.taWji[i, j] * self.eta_less, self.delta_min) if (grji[i, j] > 0): deltaji[i, j] = -self.taWji[i, j] elif (grji[i, j] < 0): deltaji[i, j] = self.taWji[i, j] for i in xrange(sizekj[0]): for j in xrange(sizekj[1]): if (Dkj[i, j] > 0): self.taWkj[i, j] = min( self.taWkj[i, j] * self.eta_plus, self.delta_max) elif (Dkj[i, j] < 0): self.taWkj[i, j] = max( self.taWkj[i, j] * self.eta_less, self.delta_min) if (grkj[i, j] > 0): deltakj[i, j] = -self.taWkj[i, j] elif (grkj[i, j] < 0): deltakj[i, j] = self.taWkj[i, j] self.Wkj += deltakj self.Wji += deltaji grji_ant = grji grkj_ant = grkj MSE[epoca] = np.sum(E) / self.N if (epoca % 200 == 0 or epoca == self.epoch_max - 1): if (epoca != 0): plt.cla() plt.clf() self.plot(z, epoca) print MSE[-1] return MSE
def plot( path, pdf_name, agents, x, y, y_lo, y_up, x_label, y_label, title_prefix, labels=None, x_cut=None, decreasing_x_axis=False, open_plot=True, title=None, plot_title=True, plot_markers=True, plot_legend=True, legend_at_bottom=False, ma=False, ma_width=10, latex_rendering=False, custom=False ): """ Standard plotting routine. :param path: (str) experiment path :param pdf_name: (str) :param agents: (list) list of agents :param x: (list) x axis data :param y: (list) list of array-like containing the x data for each agent :param y_lo: (list) list of array-like containing the lower bound on the confidence interval of the y data :param y_up: (list) list of array-like containing the upper bound on the confidence interval of the y data :param x_label: (str) :param y_label: (str) :param title_prefix: (str) :param labels: (list) list of labels if agents is None :param x_cut: (int) cut the x_axis, does nothing if set to None :param decreasing_x_axis: (bool) :param open_plot: (bool) :param title: (str) :param plot_title: (bool) :param plot_markers: (bool) :param plot_legend: (bool) :param legend_at_bottom: (bool) :param ma: (bool) Moving average :param ma_width: (int) :param latex_rendering: (bool) :param custom: (bool) :return: None """ # Font size and LaTeX rendering # matplotlib.rcParams["figure.figsize"] = [6.4, 5.5] # default: [6.4, 4.8] # TODO remove matplotlib.rcParams.update({'font.size': FONT_SIZE}) # default: 10 if latex_rendering: rc('font', **{'family': 'sans-serif', 'sans-serif': ['Helvetica']}) plt.rc('text', usetex=True) plt.rc('font', family='serif') ax = plt.figure().gca() ax.xaxis.set_major_locator(MaxNLocator(integer=True)) # Parse labels if agents is None: n_curves = len(labels) else: n_curves = len(agents) labels = [] for i in range(n_curves): labels.append(_format_label(str(agents[i]), latex_rendering)) # x-cut if x_cut is not None: x = x[:x_cut] for i in range(n_curves): y[i] = y[i][:x_cut] y_lo[i] = y_lo[i][:x_cut] y_up[i] = y_up[i][:x_cut] # Set markers and colors markers = ['o', 's', 'D', '^', '*', 'x', 'p', '+', 'v', '|'] colors = [[shade / 255.0 for shade in rgb] for rgb in COLOR_LIST] colors = colors[COLOR_SHIFT:] + colors[:COLOR_SHIFT] ax.set_prop_cycle(cycler('color', colors)) for i in range(n_curves): if ma: if y_lo is not None and y_up is not None: _x, y[i], y_lo[i], y_up[i] = moving_average(ma_width, x, y[i], y_lo[i], y_up[i]) else: _x, y[i], _, _ = moving_average(ma_width, x, y[i], None, None) else: _x = x if y_lo is not None and y_up is not None: c_i = colors[i % len(colors)] plt.fill_between(_x, y_lo[i], y_up[i], alpha=0.25, facecolor=c_i, edgecolor=c_i) if plot_markers: plt.plot(_x, y[i], '-o', label=labels[i], marker=markers[i % len(markers)]) else: plt.plot(_x, y[i], label=labels[i]) # x y labels plt.xlabel(x_label) plt.ylabel(y_label) # plt.ylim(bottom=0) if decreasing_x_axis: plt.xlim(max(x), min(x)) if custom: ax.yaxis.set_label_coords(-0.1, 0.1) #plt.figure(figsize=(20, 20)) if plot_legend: if legend_at_bottom: # Shrink current axis's height by p% on the bottom p = 0.4 box = ax.get_position() ax.set_position([box.x0, box.y0 + box.height * p, box.width, box.height * (1.0 - p)]) ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.25), fancybox=False, shadow=False, ncol=2) else: plt.legend(loc='best') plt.grid(True, linestyle='--') exp_dir_split_list = path.split("/") if 'results' in exp_dir_split_list: exp_name = exp_dir_split_list[exp_dir_split_list.index('results') + 1] else: exp_name = exp_dir_split_list[0] if plot_title: plt_title = _format_title(title) if title is not None else _format_title(title_prefix + exp_name) plt.title(plt_title) # Save plot_file_name = os.path.join(path, pdf_name + '.pdf') plt.savefig(plot_file_name, format='pdf') # Open if open_plot: open_prefix = 'gnome-' if sys.platform == 'linux' or sys.platform == 'linux2' else '' os.system(open_prefix + 'open ' + plot_file_name) # Clear and close plt.cla() plt.close()
plt.title('class: ' + text) #plt.suptitle('This is a somewhat long figure title', fontsize=16) # set axis titles plt.xlabel('Recall') plt.ylabel('Precision') # optional - set axes axes = plt.gca() # gca - get current axes axes.set_xlim([0.0, 1.0]) axes.set_ylim([0.0, 1.05]) # .05 to give some extra space # Alternative option -> wait for button to be pressed #while not plt.waitforbuttonpress(): pass # wait for key display # Alternative option -> normal display #plt.show() # save the plot fig.savefig(results_files_path + "/classes/" + class_name + ".png") plt.cla() # clear axes for next plot if show_animation: cv2.destroyAllWindows() results_file.write("\n# mAP of all classes\n") mAP = sum_AP / n_classes text = "mAP = {0:.2f}%".format(mAP * 100) results_file.write(text + "\n") print(text) # remove the temp_files directory shutil.rmtree(TEMP_FILES_PATH) """ Count total of detection-results """
def main(): plt.ion() if torch.cuda.is_available(): dev = "cuda:0" print("GPU is available!") else: dev = "cpu" #dev = "cpu" device = torch.device(dev) print(device) bs = 128 noise_size = 64 latent_size = 50 g = Generator(noise_size, 120, latent_size) d = Discriminator(latent_size, 60) da = DiffAutomata() enc = Encoder(28 * 28, 256, 50) load = torch.load("./models/autoencoder_persistent_8000.pt") enc.load_state_dict(load['encoder_state_dict']) da.load_state_dict(load['model_state_dict']) ds = torch.load("./MNIST/processed/training.pt") dt = TensorDataset(ds[0], ds[1]) dl = DataLoader(dt, batch_size = bs, shuffle = True, drop_last = True) g.to(device) d.to(device) da.to(device) enc.to(device) gsteps = 1 dsteps = 1 discriminator_optimizer = optim.Adam(d.parameters(), lr = 0.0002, betas = (0.5, 0.99), weight_decay = 0.02) generator_optimizer = optim.Adam(g.parameters(), lr = 0.0002, betas = (0.5, 0.99)) for epoch in range (200): print("saving model") torch.save({ "d_state_dict" : d.state_dict(), "g_state_dict" : g.state_dict(), "d_optimizer_state_dict" : discriminator_optimizer.state_dict(), "g_optimizer_state_dict" : generator_optimizer.state_dict(), }, "models_da/da_gan_%s.pt" % epoch) c = -1 for X, Y in dl: c += 1 for i in range (2): # generate bs x latent_size latent vectors from gaussian noise_vectors = torch.randn(bs, noise_size).to(device) # generate fake latent vectors g_latent = g.forward(noise_vectors) with torch.no_grad(): # pick bs real images from gaussian images = (X.type(torch.FloatTensor) / 255.).view(bs, 1, 28, 28).to(device) # get real latent vectors by encoding the images r_latent, _ = enc.forward(images) # bs x latent_size # to train discriminator, minimize log(fake), maximize log(real) fake = d.forward(g_latent.detach()) real = d.forward(r_latent.detach()) loss_d = -(torch.mean(torch.log(1 - fake)) + torch.mean(torch.log(real))) loss_d.backward() discriminator_optimizer.step() discriminator_optimizer.zero_grad() d.zero_grad() g.zero_grad() for i in range (gsteps): avg = 0 # now sample another bs x latent_size latent vectors from gaussian noise_vectors = torch.randn(bs, noise_size).to(device) g_latent_ = g.forward(noise_vectors) fake = d.forward(g_latent_) # to train generator, maximize log(fake) if c < 200 and epoch == 0: loss_g = -torch.mean(torch.log(fake)) else: loss_g = torch.mean(torch.log(1 - fake)) loss_g.backward() generator_optimizer.step() generator_optimizer.zero_grad() d.zero_grad() g.zero_grad() avg += loss_g print(loss_d, avg / gsteps, gsteps) if avg / gsteps > -0.7 and c > 500: gsteps = 2 elif avg / gsteps > -0.8: gsteps = 1 if c % 10 == 0: with torch.no_grad(): images = torch.zeros([bs, 51, 28, 28]).to(device) noise_vectors = torch.randn(bs, noise_size).to(device) g_latent = g.forward(noise_vectors) # -> bs x latent_size images[:, 0, 14, 14] = 1. images[:, 1:, 14, 14] = g_latent for step in range (32): mask = torch.randint(low = 0, high = 2, size = (bs, 1, 28, 28)) update_mask = torch.ones(bs, 1, 1, 1) images = da.forward(images, mask.to(device), update_mask.to(device)) for i in range (20): plt.subplot(4, 5, i + 1) plt.cla() plt.imshow(images[i, 0, :, :].view(28, 28).cpu().numpy()) plt.pause(0.0001)
def plot_color_bars( path, pdf_name, x, y, y_lo, y_up, cb_min, cb_max, cb_step, x_label, y_label, title_prefix, labels, cbar_label=None, x_cut=None, decreasing_x_axis=False, open_plot=False, title=None, plot_title=False, plot_markers=True, plot_legend=False, legend_at_bottom=False, ma=True, ma_width=10, latex_rendering=False ): """ Standard plotting routine with color bars. :param path: (str) experiment path :param pdf_name: (str) :param x: (list) x axis data :param y: (list) list of array-like containing the x data for each agent :param y_lo: (list) list of array-like containing the lower bound on the confidence interval of the y data :param y_up: (list) list of array-like containing the upper bound on the confidence interval of the y data :param x_label: (str) :param y_label: (str) :param title_prefix: (str) :param labels: (list) list of labels if agents is None :param x_cut: (int) cut the x_axis, does nothing if set to None :param decreasing_x_axis: (bool) :param open_plot: (bool) :param title: (str) :param plot_title: (bool) :param plot_markers: (bool) :param plot_legend: (bool) :param legend_at_bottom: (bool) :param ma: (bool) :param ma_width: (int) :param latex_rendering: (bool) :return: None """ # Font size and LaTeX rendering matplotlib.rcParams.update({'font.size': FONT_SIZE}) # default: 10 if latex_rendering: rc('font', **{'family': 'sans-serif', 'sans-serif': ['Helvetica']}) plt.rc('text', usetex=True) plt.rc('font', family='serif') ax = plt.figure().gca() ax.xaxis.set_major_locator(MaxNLocator(integer=True)) # Labels n_curves = len(labels) # number of curves for i in range(len(labels)): labels[i] = _format_label(labels[i], latex_rendering) # x-cut if x_cut is not None: x = x[:x_cut] for i in range(n_curves): y[i] = y[i][:x_cut] y_lo[i] = y_lo[i][:x_cut] y_up[i] = y_up[i][:x_cut] # Markers and colors markers = ['o', 's', 'D', '^', '*', 'x', 'p', '+', 'v', '|'] cb_parameters = np.array(range(cb_min, cb_max, cb_step)) norm = matplotlib.colors.Normalize(vmin=np.min(cb_parameters), vmax=np.max(cb_parameters)) c_m = matplotlib.cm.summer # color map # create a ScalarMappable and initialize a data structure s_m = matplotlib.cm.ScalarMappable(cmap=c_m, norm=norm) s_m.set_array([]) for i in range(n_curves): color_i = s_m.to_rgba(cb_parameters[i]) if ma: if y_lo is not None and y_up is not None: _x, y[i], y_lo[i], y_up[i] = moving_average(ma_width, x, y[i], y_lo[i], y_up[i]) else: _x, y[i], _, _ = moving_average(ma_width, x, y[i], None, None) else: _x = x # Interval plot if y_lo is not None and y_up is not None: plt.fill_between(_x, y_lo[i], y_up[i], alpha=0.25, facecolor=color_i, edgecolor=color_i) # Mean plot if plot_markers: plt.plot(_x, y[i], '-o', label=labels[i], marker=markers[i % len(markers)], color=color_i) else: plt.plot(_x, y[i], label=labels[i], color=color_i) plt.xlabel(x_label) plt.ylabel(y_label) # plt.ylim(bottom=0) if decreasing_x_axis: plt.xlim(max(x), min(x)) # Legend if plot_legend: if legend_at_bottom: # Shrink current axis's height by p% on the bottom p = 0.4 box = ax.get_position() ax.set_position([box.x0, box.y0 + box.height * p, box.width, box.height * (1.0 - p)]) ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.2), fancybox=False, shadow=False, ncol=2) else: plt.legend(loc='best') # Grid and color bar plt.grid(True, linestyle='--') cbar = plt.colorbar(s_m) if cbar_label is not None: cbar.set_label(cbar_label, rotation=270) exp_dir_split_list = path.split("/") if 'results' in exp_dir_split_list: exp_name = exp_dir_split_list[exp_dir_split_list.index('results') + 1] else: exp_name = exp_dir_split_list[0] if plot_title: plt_title = _format_title(title) if title is not None else _format_title(title_prefix + exp_name) plt.title(plt_title) # Save plot_file_name = os.path.join(path, pdf_name + '.pdf') plt.savefig(plot_file_name, format='pdf') # Open if open_plot: open_prefix = 'gnome-' if sys.platform == 'linux' or sys.platform == 'linux2' else '' os.system(open_prefix + 'open ' + plot_file_name) # Clear and close plt.cla() plt.close()
old0 = ptsG[jj][0] old1 = ptsG[jj][1] for iii in range(4): for jjj in range(4): new0 = new0 + Ppyt[iii, jjj] * (old0**iii) * (old1**jjj) new1 = new1 + Qpyt[iii, jjj] * (old0**iii) * (old1**jjj) dstGpyt[jj][0] = new0 dstGpyt[jj][1] = new1 xnew = dstGpyt[jj][1] ynew = dstGpyt[jj][0] + 256 xnew_int = int(xnew) ynew_int = int(ynew) plt.figure(7) plt.cla() if (xnew_int > 10 and ynew > 10 and xnew < hdim / 2 - 10 and ynew < vdim - 10): impixF = im_correct2[(xnew_int - DD):(xnew_int + DD + 1), (ynew_int - DD):(ynew_int + DD + 1)] GGF = makeGaussian(2 * DD + 1, fwhm=3, center=(ynew - ynew_int + DD, xnew - xnew_int + DD)) #approach3 multipF = impixF * GGF #approach3 acceptorF = np.sum(multipD) plt.figure(7) plt.subplot(1, 3, 1) plt.imshow(impixF), plt.title('warped positions with Python P&Q') plt.subplot(1, 3, 2)
def city_E(dir): # 设置模型 # 学习率 learning_rate = 0.01 # 类似于每次梯度下降移动步长 data_dir = 'D:/python/venv/2020year/2020 IKCEST/train_data_all' files = [ 'city_A', 'city_B', 'city_C', 'city_D', 'city_E', 'city_F', 'city_G', 'city_H', 'city_I', 'city_J', 'city_K' ] names = [ 'density.csv', 'grid_attr.csv', 'infection.csv', 'migration.csv', 'transfer.csv', 'weather.csv' ] Index = [['data', 'hour', 'grid_x', 'grid_y', 'Population_flow_index'], ['grid_x', 'grid_y', 'region_id'], ['city', 'region_id', 'data', 'num_new_persons'], [ 'data', 'departure_city', 'arrival_city', 'migration_scale_index' ], [ 'hour', 'start_grid_x', 'start_grid_y', 'end_grid_x', 'end_grid_y', 'transfer_intensity' ], [ 'data', 'hour', 'temperature', 'humidity', 'wind_direction', 'wind_speed', 'wind_force', 'weather' ]] # days_ = np.append(np.array(range(21200615, 21200631)), np.array(range(21200701, 21200715))) # days_ = days_.astype('int') # print(days_) for file in files[4:5]: i = 2 name = names[i] dir_ = data_dir + '/' + file + '/' + name print('目前文件为{}'.format(name)) data = pd.read_csv(dir_, header=0, names=Index[i]) data_2 = pd.read_csv( 'D:/python/venv/2020year/2020 IKCEST/result/{}/submission.csv'. format(dir), header=None, names=Index[i]) city = file.split('_')[-1] data_2 = data_2[data_2['city'] == city] print(data[:5]) days = data['data'].unique() # print(days) region_id = data['region_id'].unique() # 创建存储路径 save_path = r'D:\python\venv\2020year\2020 IKCEST\result visualization\{}\{}'.format( dir, city) if not os.path.exists(save_path): os.makedirs(save_path) for id in region_id: data_ = data[data['region_id'] == id] data_2_ = data_2[data_2['region_id'] == id] x = np.array(range(data_.shape[0])).astype('float32') y_ = list(data_['num_new_persons']) y = [] for i in range(len(y_)): y.append(sum(y_[:i + 1])) # print(y) y = np.array(y).astype('float32') max_y = y.max() y = y.reshape((len(y), 1)) x = x.reshape((len(x), 1)) st = NUM - data_2_.shape[0] x_2 = np.array(range(st, NUM)) y_2 = [] y_0 = np.array(data_2_['num_new_persons']) for i in range(len(y_0)): y_2.append(sum(y_0[:i + 1]) + max_y) plt.cla() plt.plot(x, y, color='blue') plt.plot(x_2, y_2, color='red') name_ = "city {},id{}".format(city, id) plt.title(name_) plt.savefig( r'D:\python\venv\2020year\2020 IKCEST\result visualization\{}\{}\{}' .format(dir, city, id))
def saveFig(name): plt.savefig('figs\\' + name + '.jpg') plt.cla()
def do_simulation(cx, cy, cyaw, ck, sp, dl): """ Simulation cx: course x position list cy: course y position list cy: course yaw position list ck: course curvature list sp: speed profile dl: course tick [m] """ goal = [cx[-1], cy[-1]] state = State(x=cx[0], y=cy[0], yaw=cyaw[0], v=0.0) time = 0.0 x = [state.x] y = [state.y] yaw = [state.yaw] v = [state.v] t = [0.0] d = [0.0] a = [0.0] target_ind, _ = calc_nearest_index(state, cx, cy, cyaw, 0) odelta, oa = None, None cyaw = smooth_yaw(cyaw) while MAX_TIME >= time: xref, target_ind, dref = calc_ref_trajectory(state, cx, cy, cyaw, ck, sp, dl, target_ind) x0 = [state.x, state.y, state.v, state.yaw] # current state oa, odelta, ox, oy, oyaw, ov = iterative_linear_mpc_control( xref, x0, dref, oa, odelta) if odelta is not None: di, ai = odelta[0], oa[0] state = update_state(state, ai, di) time = time + DT x.append(state.x) y.append(state.y) yaw.append(state.yaw) v.append(state.v) t.append(time) d.append(di) a.append(ai) if check_goal(state, goal, target_ind, len(cx)): print("Goal") break if show_animation: plt.cla() if ox is not None: plt.plot(ox, oy, "xr", label="MPC") plt.plot(cx, cy, "-r", label="course") plt.plot(x, y, "ob", label="trajectory") plt.plot(xref[0, :], xref[1, :], "xk", label="xref") plt.plot(cx[target_ind], cy[target_ind], "xg", label="target") plot_car(state.x, state.y, state.yaw, steer=di) plt.axis("equal") plt.grid(True) plt.title("Time[s]:" + str(round(time, 2)) + ", speed[km/h]:" + str(round(state.v * 3.6, 2))) plt.pause(0.0001) return t, x, y, yaw, v, d, a
def main(): """Plot an example of Stanley steering control on a cubic spline.""" # target course ax = [0.0, 100.0, 100.0, 50.0, 60.0] ay = [0.0, 0.0, -30.0, -20.0, 0.0] cx, cy, cyaw, ck, s = cubic_spline_planner.calc_spline_course( ax, ay, ds=0.1) target_speed = 30.0 / 3.6 # [m/s] max_simulation_time = 100.0 # Initial state state = State(x=-0.0, y=5.0, yaw=np.radians(20.0), v=0.0) last_idx = len(cx) - 1 time = 0.0 x = [state.x] y = [state.y] yaw = [state.yaw] v = [state.v] t = [0.0] target_idx, _ = calc_target_index(state, cx, cy) while max_simulation_time >= time and last_idx > target_idx: ai = pid_control(target_speed, state.v) di, target_idx = stanley_control(state, cx, cy, cyaw, target_idx) state.update(ai, di) time += dt x.append(state.x) y.append(state.y) yaw.append(state.yaw) v.append(state.v) t.append(time) if show_animation: # pragma: no cover plt.cla() # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect('key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) plt.plot(cx, cy, ".r", label="course") plt.plot(x, y, "-b", label="trajectory") plt.plot(cx[target_idx], cy[target_idx], "xg", label="target") plt.axis("equal") plt.grid(True) plt.title("Speed[km/h]:" + str(state.v * 3.6)[:4]) plt.pause(0.001) # Test assert last_idx >= target_idx, "Cannot reach goal" if show_animation: # pragma: no cover plt.plot(cx, cy, ".r", label="course") plt.plot(x, y, "-b", label="trajectory") plt.legend() plt.xlabel("x[m]") plt.ylabel("y[m]") plt.axis("equal") plt.grid(True) plt.subplots(1) plt.plot(t, [iv * 3.6 for iv in v], "-r") plt.xlabel("Time[s]") plt.ylabel("Speed[km/h]") plt.grid(True) plt.show()
def animate(i): x.append(next(index)) y.append(random.randint(0, 100)) plt.cla() plt.plot(x, y)
def mkfluxstar(fluxfile,gratcode): import pdb import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Cursor from astropy.io import fits from tmath.wombat.get_screen_size import get_screen_size from tmath.wombat.getmswave import getmswave from tmath.wombat.inputter_single import inputter_single from tmath.wombat.inputter import inputter from tmath.wombat.womscipyrebin import womscipyrebin from tmath.pydux.obs_extinction import obs_extinction from tmath.pydux.wave_telluric import wave_telluric from tmath.pydux.fitspl import fitspl from tmath.pydux.fitspl import fitspl_dev from tmath.pydux.finalscaler import finalscaler from tmath.pydux.abcalc import abcalc from tmath.pydux.pacheck import pacheck screen_width, screen_height=get_screen_size() plt.ion() screenpos='+{}+{}'.format(int(screen_width*0.2),int(screen_height*0.05)) fig=plt.figure() fig.canvas.manager.window.wm_geometry(screenpos) fig.canvas.set_window_title('Flux Star') fig.set_size_inches(8,5) # turns off key stroke interaction fig.canvas.mpl_disconnect(fig.canvas.manager.key_press_handler_id) # this should bring the window to the top, but it doesn't # wm=plt.get_current_fig_manager() #fig.canvas.manager.window.attributes('-topmost', 1) # blah=wm.window.attributes('-topmost', 1) #plt.pause(0.2) #fig.canvas.manager.window.attributes('-topmost', 0) # blah=wm.window.attributes('-topmost', 0) #extinction terms from Allen, 3rd edition extwave= [2400.,2600.,2800.,3000.,3200.,3400.,3600.,3800., \ 4000.,4500.,5000.,5500.,6000.,6500.,7000.,8000., \ 9000.,10000.,12000.,14000.] extvals=[68.0,89.0,36.0,4.5,1.30,0.84,0.68,0.55,0.46,0.31, \ 0.23,0.195,0.170,0.126,0.092,0.062,0.048,0.039, \ 0.028,0.021] fitsfile=fits.open(fluxfile) rawdata=fitsfile[0].data head=fitsfile[0].header num_apertures=rawdata.shape[1] wavearr=np.zeros((rawdata.shape[2],rawdata.shape[1])) objectname=head['OBJECT'] airmass=float(head['AIRMASS']) exptime=float(head['EXPTIME']) head=pacheck(head) if (exptime < 1): exptime=1. observat=head['OBSERVAT'].strip().lower() sitefactor=obs_extinction(observat) for i in range(0,num_apertures): wavearr[:,i]=getmswave(head,i) if (wavearr[-1,0] < 3000): print('************************************************') print('Spectrum not wavelength calibrated---bailing out') print('************************************************') sys.exit(1) ap_choice=-1 if (num_apertures != 1): axarr=fig.subplots(num_apertures,sharex=True) fig.subplots_adjust(hspace=0) for i in range(0,num_apertures): x=wavearr[:,i] y=rawdata[0,i,:] axarr[i].clear() plt.pause(0.01) axarr[i].plot(x,y,drawstyle='steps-mid') axarr[i].set_ylabel('Aperture {}'.format(i)) plt.pause(0.01) while (ap_choice < 0) or (ap_choice > num_apertures-1): ap_choice=inputter('Which aperture do you want to use for the flux star? ','int',False) fig.clf() else: ap_choice=0 ymin, ymax=finalscaler(rawdata[0,ap_choice,:]) fig.clf() x1=wavearr[:,ap_choice] y1=rawdata[1,ap_choice,:] y0=rawdata[0,ap_choice,:] plt.plot(x1,y1,drawstyle='steps-mid',color='r') plt.plot(x1,y0,drawstyle='steps-mid',color='k') plt.pause(0.01) plt.ylim([ymin,ymax]) plt.pause(0.01) print('\nPlotting optimal as black, normal as red') extract=inputter_single('Do you want to use (n)ormal or (o)ptimal extraction? ','no') if (extract == 'o'): star=rawdata[0,ap_choice,:] else: star=rawdata[1,ap_choice,:] # fix IRAF weirdness where data can go negative in dispcor interpolation star[np.where(star < 0)] = 0.01 wave=wavearr[:,ap_choice] extinction=womscipyrebin(extwave,extvals,wave) extfactor=np.exp(extinction*sitefactor*airmass) star=star*extfactor abcurve=abcalc(wave,objectname) wdata=10.0**(0.4*abcurve) fstar=star*wdata/exptime print('Now fit the continuum manually\n') plt.clf() ax=fig.add_subplot(111) cursor = Cursor(ax, useblit=True, color='k', linewidth=1 ) airlimit=1.5 splineresult=fitspl_dev(wave,np.log10(fstar),(airmass>airlimit),fig, cal='fluxstar{}'.format(gratcode)) splineresult=10**(splineresult) plt.cla() plt.plot(wave,fstar,drawstyle='steps-mid', color='r') plt.plot(wave,splineresult,drawstyle='steps-mid') plt.pause(0.01) delkeylist=['WAT0_001', 'WAT1_001', 'WAT2_001', 'WAT0_002', \ 'WAT1_002', 'WAT2_002', 'WAT3_001', 'WAT2_003', \ 'CTYPE1', 'CTYPE2', 'CTYPE3', 'CD1_1', 'CD2_2', \ 'CD3_3', 'LTM1_1', 'LTM2_2', 'LTM3_3', 'WCSDIM'] for k in delkeylist: try: head.remove(k) except KeyError: pass head.set('CRPIX1', 1) head.set('CRVAL1', wave[0]) head.set('CDELT1', wave[1]-wave[0]) head.set('CTYPE1', 'LINEAR') head.set('FLUXFILE',fluxfile) outfile='fluxstar'+gratcode+'.fits' print('Writing data to {}'.format(outfile)) outhdu=fits.PrimaryHDU(splineresult) hdul=fits.HDUList([outhdu]) hdul[0].header=head.copy() hdul.writeto(outfile,overwrite=True) print('mkfluxstar') print(fluxfile, gratcode) return
def test_net(sess, net, imdb, weights_filename, max_per_image=300, thresh=0.05, vis=False): """Test a Fast R-CNN network on an image database.""" num_images = len(imdb.image_index) # all detections are collected into: # all_boxes[cls][image] = N x 5 array of detections in # (x1, y1, x2, y2, score) all_boxes = [[[] for _ in range(num_images)] for _ in range(imdb.num_classes)] output_dir = get_output_dir(imdb, weights_filename) # timers _t = {'im_detect': Timer(), 'misc': Timer()} if not cfg.TEST.HAS_RPN: roidb = imdb.roidb for i in range(num_images): # filter out any ground truth boxes if cfg.TEST.HAS_RPN: box_proposals = None else: # The roidb may contain ground-truth rois (for example, if the roidb # comes from the training or val split). We only want to evaluate # detection on the *non*-ground-truth rois. We select those the rois # that have the gt_classes field set to 0, which means there's no # ground truth. box_proposals = roidb[i]['boxes'][roidb[i]['gt_classes'] == 0] im = cv2.imread(imdb.image_path_at(i)) _t['im_detect'].tic() scores, boxes = im_detect(sess, net, im, box_proposals) _t['im_detect'].toc() _t['misc'].tic() if vis: image = im[:, :, (2, 1, 0)] plt.cla() plt.imshow(image) # skip j = 0, because it's the background class for j in range(1, imdb.num_classes): inds = np.where(scores[:, j] > thresh)[0] cls_scores = scores[inds, j] cls_boxes = boxes[inds, j * 4:(j + 1) * 4] cls_dets = np.hstack((cls_boxes, cls_scores[:, np.newaxis])) \ .astype(np.float32, copy=False) keep = nms(cls_dets, cfg.TEST.NMS) cls_dets = cls_dets[keep, :] if vis: vis_detections(image, imdb.classes[j], cls_dets) all_boxes[j][i] = cls_dets if vis: plt.show() # Limit to max_per_image detections *over all classes* if max_per_image > 0: image_scores = np.hstack( [all_boxes[j][i][:, -1] for j in xrange(1, imdb.num_classes)]) if len(image_scores) > max_per_image: image_thresh = np.sort(image_scores)[-max_per_image] for j in xrange(1, imdb.num_classes): keep = np.where(all_boxes[j][i][:, -1] >= image_thresh)[0] all_boxes[j][i] = all_boxes[j][i][keep, :] _t['misc'].toc() print('im_detect: {:d}/{:d} {:.3f}s {:.3f}s'.format( i + 1, num_images, _t['im_detect'].average_time, _t['misc'].average_time)) det_file = os.path.join(output_dir, 'detections.pkl') with open(det_file, 'wb') as f: cPickle.dump(all_boxes, f, cPickle.HIGHEST_PROTOCOL) print('Evaluating detections') imdb.evaluate_detections(all_boxes, output_dir)
def predict_dtr_plot(ticker, x, y, x_train, y_train, days_predict, filePath): # get prediction dates base = date.today() dates = [base + timedelta(days=x) for x in range(days_predict)] predict_timestamp_list = [] # Used to display the date of prediction to user # convert to time stamp for dt in dates: predict_timestamp_list.append((str(dt))) timestamp = time.mktime(datetime.strptime((str(dt)), "%Y-%m-%d").timetuple()) np.append(x, int(timestamp)) model = DecisionTreeRegressor() # Define model - DTR worked best for most stocks. model.fit(x_train, y_train) # Fit to model predictions = model.predict(x) # predict print(len(predictions)) length = len(predictions) count = [0, 0] # prediction_timestamp_2plot = [] for predict in predictions: count[0] += 1 if count[0] > length - days_predict: count[1] += 1 print(f'Prediction ({predict_timestamp_list[count[1] - 1]}) = ' + str(predict)) # prediction_timestamp_2plot.append(predict_timestamp_list[count[1] - 1]) # Final step - create and show the graph pred_length = len(predict_timestamp_list) temp = [] count = 0 for length in range(length): count += 1 temp.append(count) plt.cla() # Clear old plot plt.clf() # predictions = predictions[(pred_length - days_predict):pred_length] predictions=predictions[-90:] plt.figure(figsize=(20, 5)) # prediction_dates = np.array(prediction_timestamp_2plot) plt.plot(predict_timestamp_list, predictions) plt.title(str(ticker)) plt.ylabel('Price', fontsize=12) # I use slice notation for the ticks - ex: a[start_index:end_index:step] plt.yticks(predictions[::10]) plt.xticks(predict_timestamp_list[::10]) # plt.xlabel('Time (Days)', fontsize=12) # plt.yscale('linear') # plt.xlabel(predict_timestamp_list) # ax = plt.figure().gca() # plt.suptitle(ticker, fontsize=20) # ax.xaxis.set_major_locator(MaxNLocator(integer=True)) # Improvement plt.grid(True) # ax.set_xticklabels(predict_timestamp_list, rotation=80) # plt.xticks(predict_timestamp_list[1::3], temp[1::3]) # This is numpy's slicing if filePath: # Make directory to store our export data try: plt.savefig(f"{filePath}/{ticker}.png") print(f"Plot image is located at: {filePath}/{ticker}/{ticker}.png") except: print(f"There was an exporting the plot image for {ticker}.") plt.show() # print("Mean sq. error:" + str(mean_squared_error(y, predictions))) return predictions, predict_timestamp_list
def _chart_finalize(self): plt.cla() plt.clf() plt.close() plt.close('all')