def run(): # Create a list of contact models to analyze models = [sim.models.SpringDashpot, sim.models.HertzMindlin] # Set particle radius to 1 mm steel['radius'] = 1e-3 # Compute the force-displacement curve for model in models: model = model(material=steel, limitForce=True) time, delta, force = model.displacement() plt.plot(delta[:,0] * 1e6, force * 1e3) if hasattr(model, 'displacementAnalytical'): time, delta, force = model.displacementAnalytical() plt.plot(delta[:,0] * 1e6, force * 1e3, ':o') plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0)) plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) plt.legend(['SpringDashpot (numerical)', 'SpringDashpot (analytical)', 'HertzMindlin'], loc='best') plt.xlabel(r'$\delta$ $(\mu m)$') plt.ylabel('Force (mN)') plt.grid(linestyle=':') plt.show()
def plot_feat_hist(data_name_list, filename=None): if len(data_name_list)>1: assert filename is not None pylab.figure(num=None, figsize=(8, 6)) num_rows = 1 + (len(data_name_list) - 1) / 2 num_cols = 1 if len(data_name_list) == 1 else 2 pylab.figure(figsize=(5 * num_cols, 4 * num_rows)) for i in range(num_rows): for j in range(num_cols): pylab.subplot(num_rows, num_cols, 1 + i * num_cols + j) x, name = data_name_list[i * num_cols + j] pylab.title(name) pylab.xlabel('Value') pylab.ylabel('Fraction') # the histogram of the data max_val = np.max(x) if max_val <= 1.0: bins = 50 elif max_val > 50: bins = 50 else: bins = max_val n, bins, patches = pylab.hist( x, bins=bins, normed=1, facecolor='blue', alpha=0.75) pylab.grid(True) if not filename: filename = "feat_hist_%s.png" % name.replace(" ", "_") pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
def cdf(x,colsym="",lab="",lw=4): """ plot the cumulative density function Parameters ---------- x : np.array() colsym : string lab : string lw : int linewidth Examples -------- >>> import numpy as np """ rcParams['legend.fontsize']=20 rcParams['font.size']=20 x = np.sort(x) n = len(x) x2 = np.repeat(x, 2) y2 = np.hstack([0.0, repeat(np.arange(1,n) / float(n), 2), 1.0]) plt.plot(x2,y2,colsym,label=lab,linewidth=lw) plt.grid('on') plt.legend(loc=2) plt.xlabel('Ranging Error[m]') plt.ylabel('Cumulative Probability')
def unteraufgabe_g(): # Sampling punkte x = np.linspace(0.0,1.0,1000) N = np.arange(2,16) LU = np.ones_like(N,dtype=np.floating) LT = np.ones_like(N,dtype=np.floating) # Approximiere Lebesgue-Konstante for i,n in enumerate(N): ################################################################ # # xU = np.linspace(0.0,1.0,n) # # LU[i] = ... # # j = np.arange(n+1) # xT = 0.5*(np.cos((2.0*j+1.0)/(2.0*(n+1.0))*np.pi) + 1.0) # # LT[i] = ... # ################################################################ continue # Plot plt.figure() plt.semilogy(N,LU,"-ob",label=r"Aequidistante Punkte") plt.semilogy(N,LT,"-og",label=r"Chebyshev Punkte") plt.grid(True) plt.xlim(N.min(),N.max()) plt.xlabel(r"$n$") plt.ylabel(r"$\Lambda^{(n)}$") plt.legend(loc="upper left") plt.savefig("lebesgue.eps")
def compareFrequencies(): times = generateTimes(sampleFreq, numSamples) signal = (80.0, 0.1) coherent = (60.0, 1.0) incoherent = (60.1, 1.0) highFNoise = (500.0, 0.01) timeData = generateTimeDomain(times, [signal, coherent, highFNoise]) timeData2 = generateTimeDomain(times, [signal, incoherent, highFNoise]) #timeData3 = generateTimeDomain(times, [signal, highFNoise]) #timeData = generateTimeDomain(times, [(60.0, 1.0)]) #timeData2 = generateTimeDomain(times, [(61.0, 1.0)]) roi = (0, 20) freqData = map(toDb, map(dtype, map(absolute, fourier(timeData))))[roi[0]:roi[1]] freqData2 = map(toDb, map(dtype, map(absolute, fourier(timeData2))))[roi[0]:roi[1]] #freqData3 = map(toDb, map(dtype, map(absolute, fourier(timeData3))))[roi[0]:roi[1]] frequencies = generateFFTFrequencies(sampleFreq, numSamples)[roi[0]:roi[1]] #pylab.subplot(111) pylab.plot(frequencies, freqData) #pylab.subplot(112) pylab.plot(frequencies, freqData2) #pylab.plot(frequencies, freqData3) pylab.grid(True) pylab.show()
def plot_size_of_c(size_of_c, path): xlabel('|C|') ylabel('Max model size |Ci|') grid(True) plot([x+1 for x in range(len(size_of_c))], size_of_c) savefig(os.path.join(path, 'size_of_c.png')) close()
def plot_feat_hist(data_name_list, filename=None): pylab.clf() # import pdb;pdb.set_trace() num_rows = 1 + (len(data_name_list) - 1) / 2 num_cols = 1 if len(data_name_list) == 1 else 2 pylab.figure(figsize=(5 * num_cols, 4 * num_rows)) for i in range(num_rows): for j in range(num_cols): pylab.subplot(num_rows, num_cols, 1 + i * num_cols + j) x, name = data_name_list[i * num_cols + j] pylab.title(name) pylab.xlabel('Value') pylab.ylabel('Density') # the histogram of the data max_val = np.max(x) if max_val <= 1.0: bins = 50 elif max_val > 50: bins = 50 else: bins = max_val n, bins, patches = pylab.hist( x, bins=bins, normed=1, facecolor='green', alpha=0.75) pylab.grid(True) if not filename: filename = "feat_hist_%s.png" % name pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
def plot_heuristic(heuristic, path): xlabel('|C|') ylabel('h') grid(True) plot(heuristic) savefig(os.path.join(path, 'heuristic.png')) close()
def plot_running_time(running_time, path): xlabel('|C|') ylabel('MTV iteration in secs.') grid(True) plot([x for x in range(len(running_time))], running_time) savefig(os.path.join(path, 'running_time.png')) close()
def fit_plot_unlabeled_data(unlabeled_data_x, labeled_data_x, labeled_data_y, fit_order, data_type, other_data_list, other_data_name): output = open('predictions.csv','wb') coeffs = np.polyfit(labeled_data_x, labeled_data_y, fit_order) #does poly git to nth deg on labeled data fit_eq = np.poly1d(coeffs) #Eqn from fit predicted_y = fit_eq(unlabeled_data_x) i = 0 writer = csv.writer(output,delimiter=',') header = [str(data_type),str(other_data_name),'Predicted_Num_Inc'] writer.writerow(header) while i < len(predicted_y): output_data = [unlabeled_data_x[i],other_data_list[i],predicted_y[i]] writer.writerow(output_data) print 'For '+str(data_type)+' of: '+str(unlabeled_data_x[i])+', Predicted Number of Incidents is: '+str(predicted_y[i]) i = i + 1 plt.scatter(unlabeled_data_x, predicted_y, color='blue', label='Predicted Number of Incidents') fit_line_x = np.arange(min(unlabeled_data_x), max(unlabeled_data_x), 1) plt.plot(fit_line_x, fit_eq(fit_line_x), color='red',linestyle='dashed',label=' Order '+str(fit_order)+' Polynomial Fit') #____Use below line to plot actual data also!! #plt.scatter(labeled_data_x, labeled_data_y, color='green', label='Actual Incident Report Data') plt.title('Predicted Number of 311 Incidents by '+str(data_type)) plt.xlabel(str(data_type)) plt.ylabel('Number of 311 Incidents') plt.grid() plt.xlim([min(unlabeled_data_x)-1500, max(unlabeled_data_x)+1500]) plt.legend(loc='upper left') plt.show()
def plot_BIC_score(BIC_SCORE, path): xlabel('|C|') ylabel('BIC score') grid(True) plot(BIC_SCORE) savefig(os.path.join(path, 'BIC.png')) close()
def plot(W, idx2term): """ Plot the interpretation of NMF basis vectors on Medlars data set. :param W: Basis matrix of the fitted factorization model. :type W: `scipy.sparse.csr_matrix` :param idx2term: Index-to-term translator. :type idx2term: `dict` """ print "Plotting highest weighted terms in basis vectors ..." for c in xrange(W.shape[1]): if sp.isspmatrix(W): top10 = sorted(enumerate(W[:, c].todense().ravel().tolist()[0]), key = itemgetter(1), reverse = True)[:10] else: top10 = sorted(enumerate(W[:, c].ravel().tolist()[0]), key = itemgetter(1), reverse = True)[:10] pos = np.arange(10) + .5 val = zip(*top10)[1][::-1] plb.figure(c + 1) plb.barh(pos, val, color = "yellow", align = "center") plb.yticks(pos, [idx2term[idx] for idx in zip(*top10)[0]][::-1]) plb.xlabel("Weight") plb.ylabel("Term") plb.title("Highest Weighted Terms in Basis Vector W%d" % (c + 1)) plb.grid(True) plb.savefig("documents_basisW%d.png" % (c + 1), bbox_inches = "tight") print "... Finished."
def plotFirstTacROC(dataset): import matplotlib.pylab as plt from os.path import join from src.utils import PROJECT_DIR plt.figure(figsize=(6, 6)) time_sampler = TimeSerieSampler(n_time_points=12) evaluator = Evaluator() time_series_idx = 0 methods = { "cross_correlation": "Cross corr. ", "kendall": "Kendall ", "symbol_mutual": "Symbol MI ", "symbol_similarity": "Symbol sim.", } for method in methods: print method predictor = SingleSeriesPredictor(good_methods[method], time_sampler) prediction = predictor.predictAllInstancesCombined(dataset, time_series_idx) roc_auc, fpr, tpr = evaluator.evaluate(prediction) plt.plot(fpr, tpr, label=methods[method] + " (auc = %0.3f)" % roc_auc) plt.legend(loc="lower right") plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.grid() plt.savefig(join(PROJECT_DIR, "output", "firstTACROC.pdf"))
def _on_button_press(event): if event.button != 1 or not event.inaxes: return lon, lat = m(event.xdata, event.ydata, inverse=True) # Convert to colat to ease indexing. colat = rotations.lat2colat(lat) x_range = (self.setup["physical_boundaries_x"][1] - self.setup["physical_boundaries_x"][0]) x_frac = (colat - self.setup["physical_boundaries_x"][0]) / x_range x_index = int(((self.setup["boundaries_x"][1] - self.setup["boundaries_x"][0]) * x_frac) + self.setup["boundaries_x"][0]) y_range = (self.setup["physical_boundaries_y"][1] - self.setup["physical_boundaries_y"][0]) y_frac = (lon - self.setup["physical_boundaries_y"][0]) / y_range y_index = int(((self.setup["boundaries_y"][1] - self.setup["boundaries_y"][0]) * y_frac) + self.setup["boundaries_y"][0]) plt.figure(1, figsize=(3, 8)) depths = available_depths values = data[x_index, y_index, :] plt.plot(values, depths) plt.grid() plt.ylim(depths[-1], depths[0]) plt.show() plt.close() plt.figure(0)
def plotter(resfile): # Import python matplotlib module try: import matplotlib.pylab as plt except: print >> sys.stderr, '\n Info: Python matplotlib module not found. Skipping plotting.' return None else: # Open input result file try: ifile = open(resfile, 'r') except: print >> sys.stderr, 'Error: Not able to open result file ', resfile sys.exit(-1) # Read data from the input file idata = ifile.readlines() # Close the input file try: ifile.close() except: print >> sys.stderr, 'Warning: Not able to close input file ', resfile # Read configuration file parser = readConfig() # Create and populate python lists x, y = [], [] for value in idata: if value[0] != '#': try: value.split()[2] except IndexError: pass else: x.append(value.split()[0]) y.append(value.split()[2]) # Set graph parameters and plot the completeness graph graph = os.path.splitext(resfile)[0] + '.' + parser.get('plotter', 'save_format') params = {'backend': 'ps', 'font.size': 10, 'axes.labelweight': 'medium', 'dpi' : 300, 'savefig.dpi': 300} plt.rcParams.update(params) fig = plt.figure() plt.title(parser.get('plotter', 'title'), fontweight = 'bold', fontsize = 12) plt.xlabel(parser.get('plotter', 'xlabel')) plt.ylabel(parser.get('plotter', 'ylabel')) plt.axis([float(min(x)) - 0.5, float(max(x)) + 0.5, 0.0, 110]) plt.grid(parser.get('plotter', 'grid'), linestyle = '-', color = '0.75') plt.plot(x, y, parser.get('plotter', 'style')) fig.savefig(graph) return graph
def plotLSQ(C_ms,lsqSc,lsqMu,lsqSl,LSQ,viewDirectory,TextSize=16): C_MS = C_ms - 1.0 #480x480 myfile = os.path.join(viewDirectory,'lsq.png') title='Cumulative LSQ Penalties' red = 'S(Q,E)' green = 'high E scatter' blue = 'slope of high E scatter' xlabel = r"$C_{ms}$ [unitless]" ylabel = "Cumulative Penalty [unitless]" pylab.clf() pylab.plot( C_MS, lsqSc, 'r-', linewidth=5 ) pylab.plot( C_MS, lsqMu, 'g-', linewidth=5 ) pylab.plot( C_MS, lsqSl, 'b-', linewidth=5 ) pylab.grid( 1 ) pylab.legend( (red, green, blue), loc="upper left" ) pylab.xlabel( xlabel ) pylab.ylabel( ylabel ) pylab.title(title) pylab.savefig( myfile ) myfile = os.path.join(viewDirectory,'lsq_f.png') pylab.clf() title='Final Cumulative LSQ Penalty' pylab.plot( C_MS,LSQ, 'b-', linewidth = 5) pylab.xlabel( xlabel ) pylab.ylabel( ylabel ) pylab.title( title ) pylab.grid(1) pylab.savefig( myfile ) return
def plotRocCurves(file_legend): pylab.clf() pylab.figure(1) pylab.xlabel('1 - Specificity', fontsize=12) pylab.ylabel('Sensitivity', fontsize=12) pylab.title("Need for Referral") pylab.grid(True, which='both') pylab.xticks([i/10.0 for i in range(1,11)]) pylab.yticks([i/10.0 for i in range(0,11)]) pylab.tick_params(axis="both", labelsize=15) for file, legend in file_legend: points = open(file,"rb").readlines() x = [float(p.split()[0]) for p in points] y = [float(p.split()[1]) for p in points] dev = [float(p.split()[2]) for p in points] x = [0.0] + x y = [0.0] + y dev = [0.0] + dev auc = np.trapz(y, x) * 100 aucDev = np.trapz(dev, x) * 100 pylab.grid() pylab.errorbar(x, y, yerr = dev, fmt='-') pylab.plot(x, y, '-', linewidth = 1.5, label = legend + u" (AUC = {0:0.1f}% \xb1 {1:0.1f}%)".format(auc,aucDev)) pylab.legend(loc = 4, borderaxespad=0.4, prop={'size':12}) pylab.savefig("referral/referral-curves.pdf", format='pdf')
def plot_df(self,show=False): from matplotlib import pylab as plt if self.afp is None: print 'afp not initilized. call update afp' return -1 linecords,td,df,rtn,minmaxy = self.afp formatter = PlotDateFormatter(df.index) #fig = plt.figure() #ax = plt.addsubplot() fig, ax = plt.subplots() ax.xaxis.set_major_formatter(formatter) ax.plot(np.arange(len(df)), df['p']) for cord in linecords: plt.plot(cord[0],cord[1],color='red') fig.autofmt_xdate() plt.xlim(-10,len(df.index) + 10) plt.ylim(df.p.min() - 10,df.p.max() + 10) plt.grid(ax) #if show: # plt.show() #"{0}{1}.png".format("./data/",datetime.datetime.strftime(datetime.datetime.now(),'%Y%M%m%S')) if self.plot_file: save_path = self.plot_file.format(self.symbol) if os.path.exists(os.path.dirname(save_path)): plt.savefig(save_path) plt.clf() plt.close()
def plotRocCurves(lesion, lesion_en): file_legend = [] for techniqueMid in techniquesMid: for techniqueLow in techniquesLow: file_legend.append((directory + techniqueLow + "/" + techniqueMid + "/operating-points-" + lesion + "-scale.dat", "Low-level: " + techniqueLow + ". Mid-level: " + techniqueMid + ".")) pylab.clf() pylab.figure(1) pylab.xlabel('1 - Specificity', fontsize=12) pylab.ylabel('Sensitivity', fontsize=12) pylab.title(lesion_en) pylab.grid(True, which='both') pylab.xticks([i/10.0 for i in range(1,11)]) pylab.yticks([i/10.0 for i in range(0,11)]) #pylab.tick_params(axis="both", labelsize=15) for file, legend in file_legend: points = open(file,"rb").readlines() x = [float(p.split()[0]) for p in points] y = [float(p.split()[1]) for p in points] x.append(0.0) y.append(0.0) auc = numpy.trapz(y, x) * -100 pylab.grid() pylab.plot(x, y, '-', linewidth = 1.5, label = legend + u" (AUC = {0:0.1f}%)".format(auc)) pylab.legend(loc = 4, borderaxespad=0.4, prop={'size':12}) pylab.savefig(directory + "plots/" + lesion + ".pdf", format='pdf')
def SpecMag(self): # ,dimension): # Dimension is unit type as V(olt) W(att), etc plt.plot(self.signalx, self.signaly) plt.xlabel('frequency [Hz]') # or frequency bin plt.ylabel('voltage [mV]') # auto add unit here plt.title(' ') # set title plt.grid(True) plt.show()
def SpecPh(self): # ,dimension): # Dimension is unit type as V(olt) W(att), etc plt.plot(self.signalx, self.signaly) plt.xlabel('frequency [Hz]') # or frequency bin plt.ylabel('phase [deg]') # or add radians plt.title(' ') # Set title plt.grid(True) plt.show()
def plot_fullstack( binning = np.linspace(0,10,1), myquery='', plotvar = default_plot_variable, \ scalefactor = 1., user_ylim = None): fig = plt.figure(figsize=(10,6)) plt.grid(True) lasthist = 0 myhistos = gen_histos(binning=binning,myquery=myquery,plotvar=plotvar,scalefactor=scalefactor) for key, (hist, bins) in myhistos.iteritems(): plt.bar(bins[:-1],hist, width=bins[1]-bins[0], color=colors[key], bottom = lasthist, edgecolor = 'k', label='%s: %d Events'%(labels[key],sum(hist))) lasthist += hist plt.title('CCSingleE Stacked Backgrounds',fontsize=25) plt.ylabel('Events',fontsize=20) if plotvar == '_e_nuReco' or plotvar == '_e_nuReco_better': xstring = 'Reconstructed Neutrino Energy [GeV]' elif plotvar == '_e_CCQE': xstring = 'CCQE Energy [GeV]' else: xstring = plotvar plt.xlabel(xstring,fontsize=20) plt.legend() plt.xticks(list(plt.xticks()[0]) + [binning[0]]) plt.xlim([binning[0],binning[-1]])
def plot_degreeOverlap(db, keynames, save_path, attr_name = 'degOverlapRatio'): plt.clf() plt.figure(figsize = (8, 5)) x = sorted(db[keynames['mog']][attr_name].keys()) y = [db[keynames['mog']][attr_name][xx] for xx in x] plt.plot(x, y, 'b-', lw = 5, label = 'fairyland interaction') x = sorted(db[keynames['mblg']][attr_name].keys()) y = [db[keynames['mblg']][attr_name][xx] for xx in x] plt.plot(x, y, 'r:', lw = 5, label = 'twitter interaction') x = sorted(db[keynames['im']][attr_name].keys()) y = [db[keynames['im']][attr_name][xx] for xx in x] plt.plot(x, y, 'k--', lw = 5, label = 'yahoo interaction') x = sorted(db[keynames['mogF']][attr_name].keys()) y = [db[keynames['mogF']][attr_name][xx] for xx in x] plt.plot(x, y, 'b.', label = 'fairyland ally') x = sorted(db[keynames['mblgF']][attr_name].keys()) y = [db[keynames['mblgF']][attr_name][xx] for xx in x] plt.plot(x, y, 'k*', label = 'twitter ally') plt.grid(True) plt.title('Overlap') plt.xlabel('Fraction of Users ordered by degree (%)') plt.ylabel('Overlap (%)') plt.legend(('fairyland interaction', 'twitter interaction', 'yahoo interaction', 'fairyland ally', 'twitter ally'), loc = 'best') plt.savefig(os.path.join(save_dir, save_path))
def plotDist(subplot, X, Y, label): pylab.grid() pylab.subplot(subplot) pylab.bar(X, Y, 0.05) pylab.ylabel(label) pylab.xticks(arange(len(X)), X) pylab.yticks(arange(0,1,0.1))
def plot_degreeRate(db, keynames, save_path): degRate_x_name = 'degRateDistr_x' degRate_y_name = 'degRateDistr_y' plt.clf() plt.figure(figsize = (8, 5)) plt.subplot(1, 2, 1) plt.plot(db[keynames['mog']][degRate_x_name], db[keynames['mog']][degRate_y_name], 'b-', lw=5, label = 'fairyland') plt.plot(db[keynames['mblg']][degRate_x_name], db[keynames['mblg']][degRate_y_name], 'r:', lw=5, label = 'twitter') plt.plot(db[keynames['im']][degRate_x_name], db[keynames['im']][degRate_y_name], 'k--', lw=5, label = 'yahoo') plt.xscale('log') plt.grid(True) plt.title('interaction') plt.legend(('fairyland', 'twitter', 'yahoo'), loc = 4, prop = {'size': 10}) plt.xlabel('In-degree to Out-degree Ratio') plt.ylabel('CDF') plt.subplot(1, 2, 2) plt.plot(db[keynames['mogF']][degRate_x_name], db[keynames['mogF']][degRate_y_name], 'b-', lw=5, label = 'fairyland') plt.plot(db[keynames['mblgF']][degRate_x_name], db[keynames['mblgF']][degRate_y_name], 'r:', lw=5, label = 'twitter') #plt.plot(db[keynames['imF']][degRate_x_name], db[keynames['imF']][degRate_y_name], 'k--', lw=5, label = 'yahoo') plt.xscale('log') plt.grid(True) plt.title('ally') plt.xlabel('In-degree to Out-degree Ratio') plt.ylabel('CDF') plt.savefig(os.path.join(save_dir, save_path))
def unteraufgabe_d(): n = np.arange(2,21,2) xs = [x02,x04,x06,x08,x10,x12,x14,x16,x18,x20] f = lambda x: np.sin(10*x*np.cos(x)) residuals = np.zeros_like(n,dtype=np.floating) condition = np.ones_like(n,dtype=np.floating) for i, x in enumerate(xs): b = f(x) A = interp_monom(x) alpha = solve(A,b) residuals[i] = norm(np.dot(A,alpha) - b) condition[i] = cond(A) plt.figure() plt.plot(n,residuals,"-o") plt.grid(True) plt.xlabel(r"$n$") plt.ylabel(r"$\|A \alpha - b\|_2$") plt.savefig("residuals.eps") plt.figure() plt.semilogy(n,condition,"-o") plt.grid(True) plt.xlabel(r"$n$") plt.ylabel(r"$\log(\mathrm{cond}(A))$") plt.savefig("condition.eps")
def validate(X_test, y_test, pipe, title, fileName): print('Test Accuracy: %.3f' % pipe.score(X_test, y_test)) y_predict = pipe.predict(X_test) confusion_matrix = np.zeros((9,9)) for p,r in zip(y_predict, y_test): confusion_matrix[p-1,r-1] = confusion_matrix[p-1,r-1] + 1 print (confusion_matrix) confusion_normalized = confusion_matrix.astype('float') / confusion_matrix.sum(axis=1)[:, np.newaxis] print (confusion_normalized) pylab.clf() pylab.matshow(confusion_normalized, fignum=False, cmap='Blues', vmin=0.0, vmax=1.0) ax = pylab.axes() ax.set_xticks(range(len(families))) ax.set_xticklabels(families, fontsize=4) ax.xaxis.set_label_position('top') ax.xaxis.set_ticks_position("top") ax.set_yticks(range(len(families))) ax.set_yticklabels(families, fontsize=4) pylab.title(title) pylab.colorbar() pylab.grid(False) pylab.grid(False) pylab.savefig(fileName, dpi=900)
def testPlotFrequencyDomain(): filename = baseFilename % 0 rawData = dataImport.readADSFile(filename) rawSps = 32000 downSampled = _downSample(rawData, rawSps) downSampledLinear = _downSampleLinearInterpolate(rawData, rawSps) rawTimes = range(len(rawData)) times = [float(x) * rawSps / samplesPerSecond for x in range(len(downSampled))] #pylab.plot(times, downSampled) #pylab.plot(rawTimes, rawData) #pylab.plot(times, downSampledLinear) pylab.show() index = 0 fdat = applyTransformsToWindows(getFFTWindows(downSampled), True)[index] fdatLin = applyTransformsToWindows(getFFTWindows(downSampledLinear), True)[index] #print [str(x) for x in zip(fdat, fdatLin)] frequencies = [i * samplesPerSecond / windowSize for i in range(len(fdat))] pylab.semilogy(frequencies, fdat) pylab.semilogy(frequencies, fdatLin) pylab.grid(True) pylab.show()
def unteraufgabe_c(): f = lambda x: np.sin(10*x*np.cos(x)) [A10,A20] = unteraufgabe_b() b10 = np.zeros_like(x10) b20 = np.zeros_like(x20) alpha10 = np.zeros_like(x10) alpha20 = np.zeros_like(x20) b10 = f(x10) b20 = f(x20) alpha10 = solve(A10,b10) alpha20 = solve(A20,b20) x = np.linspace(0.0, 1.0, 100) pi10 = np.zeros_like(x) pi20 = np.zeros_like(x) pi10 = np.polyval(alpha10,x) pi20 = np.polyval(alpha20,x) plt.figure() plt.plot(x,f(x),"-b",label=r"$f(x)$") plt.plot(x,pi10 ,"-g",label=r"$p_{10}(x)$") plt.plot(x10,b10,"dg") plt.plot(x,pi20 ,"-r",label=r"$p_{20}(x)$") plt.plot(x20,b20,"or") plt.grid(True) plt.xlabel(r"$x$") plt.ylabel(r"$y$") plt.legend() plt.savefig("interpolation.eps")
def Time(self): # ,dimension): # Dimension is unit type as V(olt) W(att), etc plt.plot(self.signalx, self.signaly) plt.xlabel('time [s]') # or sample number plt.ylabel('voltage [mV]') # auto add unit here plt.title(' ') plt.grid(True) plt.show()
def plot(self, fig_number=322): """plot the stored data in figure `fig_number`. Dependencies: `matlabplotlib.pylab` """ from matplotlib import pylab from matplotlib.pylab import (gca, figure, plot, xlabel, grid, semilogy, text, draw, show, subplot, tight_layout, rcParamsDefault, xlim, ylim) def title_(*args, **kwargs): kwargs.setdefault('size', rcParamsDefault['axes.labelsize']) pylab.title(*args, **kwargs) def subtitle(*args, **kwargs): kwargs.setdefault('horizontalalignment', 'center') text(0.5 * (xlim()[1] - xlim()[0]), 0.9 * ylim()[1], *args, **kwargs) def legend_(*args, **kwargs): kwargs.setdefault('framealpha', 0.3) kwargs.setdefault('fancybox', True) kwargs.setdefault('fontsize', rcParamsDefault['font.size'] - 2) pylab.legend(*args, **kwargs) figure(fig_number) dat = self._data # dictionary with entries as given in __init__ if not dat: return try: # a hack to get the presumable population size lambda strpopsize = ' (evaluations / %s)' % str(dat['eval'][-2] - dat['eval'][-3]) except IndexError: strpopsize = '' # plot fit, Delta fit, sigma subplot(221) gca().clear() if dat['fit'][0] is None: # plot is fine with None, but comput- dat['fit'][0] = dat['fit'][1] # tations need numbers # should be reverted later, but let's be lazy assert dat['fit'].count(None) == 0 fmin = min(dat['fit']) imin = dat['fit'].index(fmin) dat['fit'][imin] = max(dat['fit']) + 1 fmin2 = min(dat['fit']) dat['fit'][imin] = fmin semilogy(dat['iter'], [f - fmin if f - fmin > 1e-19 else None for f in dat['fit']], 'c', linewidth=1, label='f-min(f)') semilogy(dat['iter'], [ max((fmin2 - fmin, 1e-19)) if f - fmin <= 1e-19 else None for f in dat['fit'] ], 'C1*') semilogy(dat['iter'], [abs(f) for f in dat['fit']], 'b', label='abs(f-value)') semilogy(dat['iter'], dat['sigma'], 'g', label='sigma') semilogy(dat['iter'][imin], abs(fmin), 'r*', label='abs(min(f))') if dat['more_data']: gca().twinx() plot(dat['iter'], dat['more_data']) grid(True) legend_(*[ [v[i] for i in [1, 0, 2, 3]] # just a reordering for v in gca().get_legend_handles_labels() ]) # plot xmean subplot(222) gca().clear() plot(dat['iter'], dat['xmean']) for i in range(len(dat['xmean'][-1])): text(dat['iter'][0], dat['xmean'][0][i], str(i)) text(dat['iter'][-1], dat['xmean'][-1][i], str(i)) subtitle('mean solution') grid(True) # plot squareroot of eigenvalues subplot(223) gca().clear() semilogy(dat['iter'], dat['D'], 'm') xlabel('iterations' + strpopsize) title_('Axis lengths') grid(True) # plot stds subplot(224) # if len(gcf().axes) > 1: # sca(pylab.gcf().axes[1]) # else: # twinx() gca().clear() semilogy(dat['iter'], dat['stds']) for i in range(len(dat['stds'][-1])): text(dat['iter'][-1], dat['stds'][-1][i], str(i)) title_('Coordinate-wise STDs w/o sigma') grid(True) xlabel('iterations' + strpopsize) _stdout.flush() tight_layout() draw() show() CMAESDataLogger.plotted += 1
"L2Mu23NoVtx_2Cha": 4457, "L2Mu23NoVtx_2Cha_NoL2Matched": 4875, "L2Mu23NoVtx_2Cha_CosmicSeed": 3332, "L2Mu23NoVtx_2Cha_CosmicSeed_NoL2Matched": 3367, #"DoubleL2Mu25NoVtx_2Cha":4227, #"DoubleL2Mu25NoVtx_2Cha_NoL2Matched":4635, #"DoubleL2Mu25NoVtx_2Cha_CosmicSeed":3114, #"DoubleL2Mu25NoVtx_2Cha_CosmicSeed_NoL2Matched":3147, "L2Mu25NoVtx_2Cha_Eta2p4": 4271, "L2Mu25NoVtx_2Cha_CosmicSeed_Eta2p4": 3146, } x = [i for i in range(0, 6)] listm = sorted(myTRGm.items()) # sorted by key, return a list of tuples liste = sorted(myTRGe.items()) xTicks, y = zip(*listm) # unpack a list of pairs into two tuples xTicks, z = zip(*liste) plt.figure(facecolor="white") plt.xticks(x, xTicks) plt.xticks(range(6), xTicks, rotation=90) plt.plot(x, y, 'b*-', label='4mu') plt.plot(x, z, 'r*-', label='2mu2e') plt.title('Double Mu triggers') plt.gca().set_xlabel('Trigger path') plt.gca().set_ylabel('# events') plt.grid(True) legend = plt.gca().legend(loc='upper left', fontsize='large') plt.savefig('dmutrigger.png') plt.show()
def travelTimePlot(min_degree=0, max_degree=360, npoints=1000, phases=None, depth=100, model='iasp91'): """ Basic travel time plotting function. :type min_degree: float, optional :param min_degree: Minimum distance in degree used in plot. Defaults to ``0``. :type max_degree: float, optional :param max_degree: Maximum distance in degree used in plot. Defaults to ``360``. :type npoints: int, optional :param npoints: Number of points to plot. Defaults to ``1000``. :type phases: list of strings, optional :param phases: List of phase names which should be used within the plot. Defaults to all phases if not explicit set. :type depth: float, optional :param depth: Depth in kilometer. Defaults to ``100``. :type model: string, optional :param model: Either ``'iasp91'`` or ``'ak135'`` velocity model. Defaults to ``'iasp91'``. :return: None .. rubric:: Example >>> from obspy.taup.taup import travelTimePlot >>> travelTimePlot(min_degree=0, max_degree=50, phases=['P', 'S', 'PP'], ... depth=120, model='iasp91') #doctest: +SKIP .. plot:: from obspy.taup.taup import travelTimePlot travelTimePlot(min_degree=0, max_degree=50, phases=['P', 'S', 'PP'], depth=120, model='iasp91') """ import matplotlib.pylab as plt data = {} if not phases: phases = AVAILABLE_PHASES for phase in phases: data[phase] = [[], []] degrees = np.linspace(min_degree, max_degree, npoints) # Loop over all degrees. for degree in degrees: tt = getTravelTimes(degree, depth, model) # Mirror if necessary. if degree > 180: degree = 180 - (degree - 180) for item in tt: phase = item['phase_name'] # Check if this phase should be plotted. if phase in data: try: data[phase][1].append(item['time'] / 60.0) data[phase][0].append(degree) except: data[phase][1].append(np.NaN) data[phase][0].append(degree) # Plot and some formatting. for key, value in data.items(): plt.plot(value[0], value[1], '.', label=key) plt.grid() plt.xlabel('Distance (degrees)') plt.ylabel('Time (minutes)') if max_degree <= 180: plt.xlim(min_degree, max_degree) else: plt.xlim(min_degree, 180) plt.legend(numpoints=1) plt.show()
def sub_time_wow(lists_cmd=None, options=None): # time_wow_record=sub_time_wow(lists_cmd,options) # timed/ordered update ratio - WOW # inputs # lists_cmd: n samples x 3 for LBA, size, flags # options: control parameters # plot_fontsize: the figure's font size # plot_figure: >=1: plot the figure; otherwise not; default 1 # save_figure: >=1: save the figures # export_report: >=1: export the figure/data into a ppt # report_name: report name # output_foldername: the output folder name for figures and report; default ='' # offset_time: some trace is not started from zone. in this case. need to find the starting time of first event. # spec_stack=[10,20,30]; # a vector specify the stack distance, for which we can collect the statistical value and output to the ppt file. for very large dataset ; otherwise specify some small numbers # outputs # time_wow_record: structure for statistics of timed WOW # contact [email protected] for questions if hasattr(options, 'plot_fontsize'): plot_fontsize = options.plot_fontsize else: plot_fontsize = 10 if hasattr(options, 'save_figure'): save_figure = options.save_figure else: save_figure = 1 if hasattr(options, 'plot_figure'): plot_figure = options.plot_figure else: plot_figure = 1 # options.access_type=0; # options.drive_max_lba=2*1024^4/512; update_stat = write_update_time(lists_cmd, 0, options) if plot_figure == 1: f_cdf = figure() # hold('on') plot(arange(0, update_stat.idx_size), update_stat.write_ratio, 'r:') plot(arange(0, update_stat.idx_size), update_stat.update_ratio, 'b-') if options.access_type == 0: xlabel('# of write operations') else: if options.access_type == 2: xlabel('# of total operations') ylabel('Percentage of blocks written/updated') title('Write Update CDF (blocks)') legend(('blocks written', 'blocks updated')) grid('on') #set(findall(gcf,'-property','FontSize'),'FontSize',plot_fontsize) savefig('timed_update1.eps') savefig('timed_update1.png') figure() #hold('on') plot(arange(0, update_stat.idx_size), update_stat.write_cmd_ratio, 'r:') plot(arange(0, update_stat.idx_size), update_stat.hit_ratio, 'b-') if options.access_type == 0: xlabel('# of write operations') else: if options.access_type == 2: xlabel('# of total operations') ylabel('Percentage of command written/updated') title('Write Update CDF (commands) ') legend(('commands written', 'commands updated')) grid('on') # set(findall(gcf,'-property','FontSize'),'FontSize',plot_fontsize) savefig('timed_update2.eps') savefig('timed_update2.png') # if options.export_report: # options.section_name = copy('Timed WOW') # generate_ppt(options) # string0=string_generate(cat(cat(arange(1,update_stat.idx_size)).T,update_stat.write_ratio),30) # string0=matlabarray(cat('Write Update CDF (blocks written)=',string0)) # saveppt2(options.report_name,'f',0,'t',string0) # string0=string_generate(cat(cat(arange(1,update_stat.idx_size)).T,update_stat.update_ratio),30) # string0=matlabarray(cat('Write Update CDF (blocks updated)=',string0)) # saveppt2(options.report_name,'f',0,'t',string0) # string0=string_generate(cat(cat(arange(1,update_stat.idx_size)).T,update_stat.write_cmd_ratio),30) # string0=matlabarray(cat('Write Update CDF (cmd written)=',string0)) # saveppt2(options.report_name,'f',0,'t',string0) # string0=string_generate(cat(cat(arange(1,update_stat.idx_size)).T,update_stat.hit_ratio),30) # string0=matlabarray(cat('Write Update CDF (cmd updated)=',string0)) # saveppt2(options.report_name,'f',0,'t',string0) return update_stat
fig, ax = plt.subplots(5, sharex=True, sharey=True, gridspec_kw={'hspace': 0}) ax[0].plot(t, x) ax[0].grid() ax[1].plot(t, x1) ax[1].grid() ax[2].plot(t, x2) ax[2].grid() ax[3].plot(t, x3) ax[3].grid() ax[4].plot(t, x4) ax[4].grid() plt.savefig('Ejemplo1.eps') plt.show() x5 = [] M = int(N / 4) for n in range(M): x5.append(1) for n in range(M): x5.append(-1) for n in range(M): x5.append(1) for n in range(M): x5.append(-1) plt.plot(t, x5) plt.grid() plt.savefig('Ejemplo1Original.eps') plt.show()
Error_test[k] = np.square(y_test - X_test @ w_noreg[:, k]).sum( axis=0) / y_test.shape[0] # OR ALTERNATIVELY: you can use sklearn.linear_model module for linear regression: #m = lm.LinearRegression().fit(X_train, y_train) #Error_train[k] = np.square(y_train-m.predict(X_train)).sum()/y_train.shape[0] #Error_test[k] = np.square(y_test-m.predict(X_test)).sum()/y_test.shape[0] # Display the results for the last cross-validation fold if k == K - 1: figure(k, figsize=(12, 8)) subplot(1, 2, 1) semilogx(lambdas, mean_w_vs_lambda.T[:, 1:], '.-') # Don't plot the bias term xlabel('Regularization factor') ylabel('Mean Coefficient Values') grid() # You can choose to display the legend, but it's omitted for a cleaner # plot, since there are many attributes #legend(attributeNames[1:], loc='best') subplot(1, 2, 2) title('Optimal lambda: 1e{0}'.format(np.log10(opt_lambda))) loglog(lambdas, train_err_vs_lambda.T, 'b.-', lambdas, test_err_vs_lambda.T, 'r.-') xlabel('Regularization factor') ylabel('Squared error (crossvalidation)') legend(['Train error', 'Validation error']) grid() # To inspect the used indices, use these print statements #print('Cross validation fold {0}/{1}:'.format(k+1,K))
def travelTimePlot(min_degree=0, max_degree=360, npoints=1000, phases=None, depth=100, model='iasp91'): """ Basic travel time plotting function. :type min_degree: float, optional :param min_degree: Minimum distance in degree used in plot. Defaults to ``0``. :type max_degree: float, optional :param max_degree: Maximum distance in degree used in plot. Defaults to ``360``. :type npoints: int, optional :param npoints: Number of points to plot. Defaults to ``1000``. :type phases: list of str, optional :param phases: List of phase names which should be used within the plot. Defaults to all phases if not explicit set. :type depth: float, optional :param depth: Depth in kilometer. Defaults to ``100``. :type model: str, optional :param model: Either ``'iasp91'`` or ``'ak135'`` velocity model. Defaults to ``'iasp91'``. :return: None .. rubric:: Example >>> from obspy.taup.taup import travelTimePlot >>> travelTimePlot(min_degree=0, max_degree=50, phases=['P', 'S', 'PP'], ... depth=120, model='iasp91') #doctest: +SKIP .. plot:: from obspy.taup.taup import travelTimePlot travelTimePlot(min_degree=0, max_degree=50, phases=['P', 'S', 'PP'], depth=120, model='iasp91') .. versionchanged:: 0.10.0 Deprecated. """ warnings.warn( "The travelTimePlot() function is deprecated. Please use " "the obspy.taup.TauPyModel class directly.", ObsPyDeprecationWarning, stacklevel=2) import matplotlib.pylab as plt data = {} if not phases: phases = ["ttall"] degrees = np.linspace(min_degree, max_degree, npoints) # Loop over all degrees. for degree in degrees: with warnings.catch_warnings(record=True): tt = getTravelTimes(degree, depth, model, phase_list=phases) # Mirror if necessary. if degree > 180: degree = 180 - (degree - 180) for item in tt: phase = item['phase_name'] if phase not in data: data[phase] = [[], []] data[phase][1].append(item['time'] / 60.0) data[phase][0].append(degree) # Plot and some formatting. for key, value in data.items(): plt.plot(value[0], value[1], '.', label=key) plt.grid() plt.xlabel('Distance (degrees)') plt.ylabel('Time (minutes)') if max_degree <= 180: plt.xlim(min_degree, max_degree) else: plt.xlim(min_degree, 180) plt.legend(numpoints=1) plt.show()
import matplotlib.pylab as plt import pandas as pd # read and plot kernel data = pd.read_csv("kernel.csv", sep=";") plt.plot(data.x, data.phi, label="A5 kernel") plt.grid(linestyle=':') plt.legend() plt.savefig("kernel.png") plt.gcf().clear() # read and plot results data = pd.read_csv("results.csv", sep=";") fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(7, 4)) [ ax1.plot(data.x, data[eps], label=eps) for eps in data.filter(regex=("eps.*")) ] ax1.set_ylim([-2, 0.1]) ax1.grid(linestyle=':') ax1.legend() [ax2.plot(data.x, data[L], label=L) for L in data.filter(regex=("L.*"))] ax2.set_ylim([-0.1, 2]) ax2.grid(linestyle=':') ax2.legend() plt.savefig("results.png") plt.gcf().clear() """ # read and plot cfunc data = pd.read_csv("cfunc.csv", sep=";") plt.plot(data.r,data.c, label="lee-yang c-func")
def plot_combined_surface_densities(combined_data, output_path, simulation_name): # Get the default KS relation for correct IMF def KS(sigma_g, n, A): return A * sigma_g**n # Plot parameters params = { "font.size": 12, "font.family": "Times", "text.usetex": True, "figure.figsize": (5.5, 4), "figure.subplot.left": 0.15, "figure.subplot.right": 0.85, "figure.subplot.bottom": 0.18, "figure.subplot.top": 0.9, "lines.markersize": 2, "lines.linewidth": 2.0, } rcParams.update(params) sigma_SFR = combined_data.SFR_surface_density metals = combined_data.gas_metallicity metals[metals == 0] = 1e-6 metals = np.log10(np.array(metals, dtype="float")) arg_sort = np.argsort(metals) metals = metals[arg_sort[::-1]] sigma_SFR = sigma_SFR[arg_sort[::-1]] for plot in ["gas", "H2"]: # star formation rate surgface density vs surface density fig = plt.figure() ax = plt.subplot(1, 1, 1) plt.grid("True") Sigma_g = np.logspace(-2, 3, 1000) Sigma_star = KS(Sigma_g, 1.4, 1.515e-4) plt.plot( np.log10(Sigma_g), np.log10(Sigma_star), "--", color="grey", label=r"1.51e-4 $\times$ $\Sigma_{\rm g}^{1.4}$", ) Sigma_g = np.logspace(-1, 4, 1000) Sigma_star = KS(Sigma_g, 1.06, 2.511e-4) plt.plot( np.log10(Sigma_g), np.log10(Sigma_star), lw=1, color="green", label=r"2.51e-4 $\times$ $\Sigma_{\rm g}^{1.06}$ (Pessa+ 2021)", linestyle="-", ) if plot == "gas": sigma_gas = combined_data.neutral_gas_surface_density t_gas = combined_data.depletion_time_neutral_gas else: sigma_gas = combined_data.molecular_gas_surface_density t_gas = combined_data.depletion_time_molecular_gas sigma_gas = sigma_gas[arg_sort[::-1]] t_gas = t_gas[arg_sort[::-1]] plt.scatter( sigma_gas, sigma_SFR, c=metals, alpha=0.9, s=10, vmin=-3, vmax=1, cmap="CMRmap_r", edgecolors="none", zorder=2, ) select = np.where((metals > -1.2) & (metals < -0.8))[0] x, y, y_down, y_up = median_relations(sigma_gas[select], sigma_SFR[select]) plt.plot(x, y, "-", lw=2, color="white") plt.plot( x, y, "-", lw=1.5, color="crimson", label="log Z$_{\mathrm{gas}}$/Z$_{\odot}$=-1", ) select = np.where((metals > -0.2) & (metals < 0.2))[0] x, y, y_down, y_up = median_relations(sigma_gas[select], sigma_SFR[select]) plt.plot(x, y, "-", lw=2, color="white") plt.plot( x, y, "-", lw=1.5, color="mediumpurple", label="log Z$_{\mathrm{gas}}$/Z$_{\odot}$=0", ) select = np.where(metals > 0.6)[0] x, y, y_down, y_up = median_relations(sigma_gas[select], sigma_SFR[select]) plt.plot(x, y, "-", lw=2, color="white") plt.plot( x, y, "-", lw=1.5, color="lightblue", label="log Z$_{\mathrm{gas}}$/Z$_{\odot}$=1", ) x, y, y_down, y_up = median_relations(sigma_gas, sigma_SFR) plt.plot(x, y, "-", lw=2, color="white") plt.plot(x, y, "-", lw=1.5, color="grey", label="All") select = np.where(sigma_SFR > -5.5)[0] x, y, y_down, y_up = median_relations(sigma_gas[select], sigma_SFR[select]) plt.plot(x, y, "-", lw=2, color="white") plt.plot(x, y, "-", lw=1.5, color="black", label="star-forming") if plot == "gas": plt.xlabel( "log $\\Sigma_{\\rm HI} + \\Sigma_{\\rm H_2}$ $[{\\rm M_\\odot\\cdot pc^{-2}}]$" ) else: plt.xlabel( "log $\\Sigma_{\\rm H_2}$ $[{\\rm M_\\odot\\cdot pc^{-2}}]$") plt.ylabel( "log $\\Sigma_{\\rm SFR}$ $[{\\rm M_\\odot \\cdot yr^{-1} \\cdot kpc^{-2}}]$" ) plt.xlim(-1.0, 4.0) plt.ylim(-6.0, 1.0) plt.legend( loc=[0.0, 0.5], labelspacing=0.2, handlelength=1, handletextpad=0.2, frameon=False, ) cbar_ax = fig.add_axes([0.87, 0.18, 0.018, 0.5]) cbar_ax.tick_params(labelsize=15) cb = plt.colorbar(ticks=[-3, -2, -1, 0, 1], cax=cbar_ax) cb.set_label(label="log Z$_{\mathrm{gas}}$/Z$_{\odot}$", labelpad=0.5) ax.tick_params(direction="in", axis="both", which="both", pad=4.5) plt.savefig( f"{output_path}/combined_surface_density_{plot}_" + simulation_name + ".png", dpi=200, ) plt.close() # Depletion time vs surface density fig = plt.figure() ax = plt.subplot(1, 1, 1) plt.grid("True") Sigma_g = np.logspace(-1, 4, 1000) Sigma_star = KS(Sigma_g, 1.4, 1.515e-4) plt.plot( np.log10(Sigma_g), np.log10(Sigma_g) - np.log10(Sigma_star) + 6.0, color="red", label="KS law (Kennicutt 98)", linestyle="--", ) plt.scatter( sigma_gas, t_gas, c=metals, alpha=0.9, s=10, vmin=-3, vmax=1, cmap="CMRmap_r", edgecolors="none", zorder=2, ) select = np.where((metals > -1.2) & (metals < -0.8))[0] x, y, y_down, y_up = median_relations(sigma_gas[select], t_gas[select]) plt.plot(x, y, "-", lw=2, color="white") plt.plot( x, y, "-", lw=1.5, color="crimson", label="log Z$_{\mathrm{gas}}$/Z$_{\odot}$=-1", ) select = np.where((metals > -0.2) & (metals < 0.2))[0] x, y, y_down, y_up = median_relations(sigma_gas[select], t_gas[select]) plt.plot(x, y, "-", lw=2, color="white") plt.plot( x, y, "-", lw=1.5, color="mediumpurple", label="log Z$_{\mathrm{gas}}$/Z$_{\odot}$=0", ) select = np.where(metals > 0.6)[0] x, y, y_down, y_up = median_relations(sigma_gas[select], sigma_SFR[select]) plt.plot(x, y, "-", lw=2, color="white") plt.plot( x, y, "-", lw=1.5, color="lightblue", label="log Z$_{\mathrm{gas}}$/Z$_{\odot}$=1", ) x, y, y_down, y_up = median_relations(sigma_gas, t_gas) plt.plot(x, y, "-", lw=2, color="white") plt.plot(x, y, "-", lw=1.5, color="grey", label="All") select = np.where(sigma_SFR > -5.5)[0] x, y, y_down, y_up = median_relations(sigma_gas[select], t_gas[select]) plt.plot(x, y, "-", lw=2, color="white") plt.plot(x, y, "-", lw=1.5, color="black", label="star-forming") if plot == "gas": plt.xlabel( "log $\\Sigma_{\\rm HI} + \\Sigma_{\\rm H_2}$ $[{\\rm M_\\odot\\cdot pc^{-2}}]$" ) plt.ylabel( "log $\\rm t_{gas} = (\\Sigma_{\\rm HI} + \\Sigma_{\\rm H_2})/ \\Sigma_{\\rm SFR}$ $[{\\rm yr }]$" ) else: plt.xlabel( "log $\\Sigma_{\\rm H_2}$ $[{\\rm M_\\odot\\cdot pc^{-2}}]$") plt.ylabel( "log $\\rm t_{H_2} = \\Sigma_{\\rm H_2} / \\Sigma_{\\rm SFR}$ $[{\\rm yr }]$" ) plt.xlim(-1, 4.0) plt.ylim(7, 12) plt.legend( loc=[0.0, 0.5], labelspacing=0.2, handlelength=1, handletextpad=0.2, frameon=False, ) cbar_ax = fig.add_axes([0.87, 0.18, 0.018, 0.5]) cbar_ax.tick_params(labelsize=15) cb = plt.colorbar(ticks=[-3, -2, -1, 0, 1], cax=cbar_ax) cb.set_label(label="log Z$_{\mathrm{gas}}$/Z$_{\odot}$", labelpad=0.5) ax.tick_params(direction="in", axis="both", which="both", pad=4.5) plt.savefig( f"{output_path}/depletion_time_combined_surface_density_{plot}_" + simulation_name + ".png", dpi=200, ) plt.close() ####### fig = plt.figure() ax = plt.subplot(1, 1, 1) plt.grid("True") sigma_gas = combined_data.neutral_gas_surface_density sigma_ratio = combined_data.H2_to_neutral_surface_density_ratio sigma_gas = sigma_gas[arg_sort[::-1]] sigma_ratio = sigma_ratio[arg_sort[::-1]] plt.scatter( sigma_gas, sigma_ratio, c=metals, alpha=0.9, s=5, vmin=-3, vmax=1, cmap="CMRmap_r", edgecolors="none", zorder=2, label="method:grid", ) select = np.where((metals > -1.2) & (metals < -0.8))[0] x, y, y_down, y_up = median_relations(sigma_gas[select], sigma_ratio[select]) plt.plot(x, y, "-", lw=2, color="white") plt.plot( x, y, "-", lw=1.5, color="crimson", label="log Z$_{\mathrm{gas}}$/Z$_{\odot}$=-1", ) select = np.where((metals > -0.2) & (metals < 0.2))[0] x, y, y_down, y_up = median_relations(sigma_gas[select], sigma_ratio[select]) plt.plot(x, y, "-", lw=2, color="white") plt.plot( x, y, "-", lw=1.5, color="mediumpurple", label="log Z$_{\mathrm{gas}}$/Z$_{\odot}$=0", ) select = np.where(metals > 0.6)[0] x, y, y_down, y_up = median_relations(sigma_gas[select], sigma_ratio[select]) plt.plot(x, y, "-", lw=2, color="white") plt.plot( x, y, "-", lw=1.5, color="lightblue", label="log Z$_{\mathrm{gas}}$/Z$_{\odot}$=1", ) x, y, y_down, y_up = median_relations(sigma_gas, sigma_ratio) plt.plot(x, y, "-", lw=2, color="white") plt.plot(x, y, "-", lw=1.5, color="grey", label="All") sigma_gas = combined_data.radii_neutral_gas_surface_density sigma_ratio = combined_data.radii_H2_to_neutral_surface_density_ratio plt.plot( sigma_gas, sigma_ratio, "o", ms=4, alpha=0.5, color="tab:blue", label="method:annuli", ) plt.xlabel( "log $\\Sigma_{\\rm HI} + \\Sigma_{\\rm H_2}$ $[{\\rm M_\\odot\\cdot pc^{-2}}]$" ) plt.ylabel( r"log $\Sigma_{\mathrm{H2}} / (\Sigma_{\mathrm{HI}}+\Sigma_{\mathrm{H2}})$" ) plt.xlim(-1.0, 4.0) plt.ylim(-8.0, 0.5) plt.legend( loc=[0.65, 0.0], labelspacing=0.2, handlelength=1, handletextpad=0.2, frameon=False, ) cbar_ax = fig.add_axes([0.87, 0.18, 0.018, 0.5]) cbar_ax.tick_params(labelsize=15) cb = plt.colorbar(ticks=[-3, -2, -1, 0, 1], cax=cbar_ax) cb.set_label(label="log Z$_{\mathrm{gas}}$/Z$_{\odot}$", labelpad=0.5) ax.tick_params(direction="in", axis="both", which="both", pad=4.5) plt.savefig( f"{output_path}/combined_surface_density_ratios_" + simulation_name + ".png", dpi=200, ) plt.close()
a.ww /= utau2 a.uv /= utau2 a.uw /= utau2 a.vw /= utau2 wind_dir = 180.0 + np.arctan2(a.u, a.v) * 180.0 / np.pi pylab.plot(np.sqrt(np.multiply(a.u, a.u) + np.multiply(a.v, a.v)), a.z, label='|U|') pylab.plot(a.u, a.z, label=r'$U_x$') pylab.plot(a.v, a.z, label=r'$U_y$') pylab.xlabel("Velocity (m/s)") pylab.ylabel("Height (m)") pylab.legend() pylab.grid() pylab.savefig("velmean.pdf") pylab.clf() pylab.plot(a.w, a.z, label=r'$U_z$') pylab.xlabel("Velocity (m/s)") pylab.ylabel("Height (m)") pylab.legend() pylab.grid() pylab.savefig("wmean.pdf") pylab.clf() pylab.plot(wind_dir, a.z, label='wind direction') pylab.xlabel("Wind direction (deg)") pylab.ylabel("Height (m)") #pylab.legend()
shear_strain = np.sqrt(shear_strain_x*shear_strain_x + shear_strain_y*shear_strain_y) ; shear_stress = np.sqrt(shear_stress_x*shear_stress_x + shear_stress_y*shear_stress_y ); shear_stress = shear_stress_x; shear_strain = shear_strain_x; # Configure the figure filename, according to the input filename. outfig=thefile.replace("_","-") outfigname=outfig.replace("h5.feioutput","pdf") # Plot the figure. Add labels and titles. # plt.figure() fig = plt.figure(figsize=(10,10)) # plt.xtitle('axes title', size = 50) plt.plot(normal_strain*h,normal_stress/1000,Linewidth=4) plt.xlabel(r"Penetration $\Delta_n$ $[mm]$") plt.ylabel(r"Normal Stress $\sigma_n$ $[kPa]$") plt.hold(True) # axes = plt.gca() # axes.set_xlim([-7,7]) # axes.set_ylim([-1,1]) outfigname = "Axial_Response.pdf"; # Make space for and rotate the x-axis tick labels fig.autofmt_xdate() plt.grid(linestyle='--', linewidth='0.5', color='k') plt.savefig(outfigname, bbox_inches='tight') # plt.show()
def plot_integrated_surface_densities(sigma_SFR, sigma_gas, sigma_H2, stellar_mass, output_path, simulation_name): # Plot parameters params = { "font.size": 12, "font.family": "Times", "text.usetex": True, "figure.figsize": (5.5, 4), "figure.subplot.left": 0.15, "figure.subplot.right": 0.85, "figure.subplot.bottom": 0.18, "figure.subplot.top": 0.9, "lines.markersize": 4, "lines.linewidth": 2.0, } # Get the default KS relation for correct IMF def KS(sigma_g, n, A): return A * sigma_g**n Sigma_g = np.logspace(-2, 3, 1000) Sigma_star = KS(Sigma_g, 1.4, 1.515e-4) rcParams.update(params) fig = plt.figure() ax = plt.subplot(1, 1, 1) plt.grid("True") plt.plot( np.log10(Sigma_g), np.log10(Sigma_star), "--", color="grey", label=r"1.51e-4 $\times$ $\Sigma_{\rm g}^{1.4}$", ) plt.scatter( sigma_H2, sigma_SFR, c=stellar_mass, alpha=0.9, s=25, vmin=6, vmax=10, cmap="CMRmap_r", edgecolors="none", zorder=2, ) plt.xlabel("log $\\Sigma_{\\rm H_2}$ $[{\\rm M_\\odot\\cdot pc^{-2}}]$") plt.ylabel( "log $\\Sigma_{\\rm SFR}$ $[{\\rm M_\\odot \\cdot yr^{-1} \\cdot kpc^{-2}}]$" ) plt.xlim(-1.0, 4.0) plt.ylim(-6.0, 1.0) plt.legend() cbar_ax = fig.add_axes([0.87, 0.18, 0.018, 0.5]) cbar_ax.tick_params(labelsize=15) cb = plt.colorbar(ticks=[6, 7, 8, 9, 10, 11, 12], cax=cbar_ax) cb.set_label(label="$\log_{10}$ M$_{*}$/M$_{\odot}$", labelpad=0.5) ax.tick_params(direction="in", axis="both", which="both", pad=4.5) plt.savefig(f"{output_path}/surface_density_gas_" + simulation_name + ".png", dpi=200) plt.close() ####### fig = plt.figure() ax = plt.subplot(1, 1, 1) plt.grid("True") plt.plot( np.log10(Sigma_g), np.log10(Sigma_star), "--", color="grey", label=r"1.51e-4 $\times$ $\Sigma_{\rm g}^{1.4}$", ) plt.scatter( sigma_gas, sigma_SFR, c=stellar_mass, alpha=0.9, s=25, vmin=6, vmax=10, cmap="CMRmap_r", edgecolors="none", zorder=2, ) plt.xlabel( "log $\\Sigma_{\\rm HI}+ \\Sigma_{\\rm H_2}$ $[{\\rm M_\\odot\\cdot pc^{-2}}]$" ) plt.ylabel( "log $\\Sigma_{\\rm SFR}$ $[{\\rm M_\\odot \\cdot yr^{-1} \\cdot kpc^{-2}}]$" ) plt.xlim(-1.0, 4.0) plt.ylim(-6.0, 1.0) plt.legend() cbar_ax = fig.add_axes([0.87, 0.18, 0.018, 0.5]) cbar_ax.tick_params(labelsize=15) cb = plt.colorbar(ticks=[6, 7, 8, 9, 10, 11, 12], cax=cbar_ax) cb.set_label(label="$\log_{10}$ M$_{*}$/M$_{\odot}$", labelpad=0.5) ax.tick_params(direction="in", axis="both", which="both", pad=4.5) plt.savefig(f"{output_path}/surface_density_H2_" + simulation_name + ".png", dpi=200) plt.close()
def validation(events, ts=1505287800, prefix="84.205.67.0/24"): """Validate SSL results using traceroute data. Compare SSL results to BGP results and responding IP addresses found in traceroute data. Also plot the results in a graph where node shape stands for SSL results (triangle=zombie, circle=normal) and the color represents the ground truth (red=zombie, green=normal, orange means results from traceroutes and BGP are inconsistent, and gray means unknown)""" # print("Processing %s %s..." % (ts, prefix)) fname = "zombie_paths/graph_%s_%s.txt" % (ts, prefix.replace( "/", "_").replace("-", ":")) G = nx.read_adjlist(fname) use_bgp_data = True ##### Traceroute data ##### ztr = set() ntr = set() for msmid, desc in events.items(): # select only traceroutes for this outbreak if 1800 + int(desc["start"] / 3600) * 3600 == ts and desc["prefix"] == prefix: if desc["nb_traceroutes"] == 0: continue # traceroutes contain only *, the probes' AS has withdrawn the prefix if desc["nb_only_stars"] >= desc["nb_traceroutes"] * 0.75: asn = Counter(map(asnres, desc["prb_ips"])).most_common(1)[0] if asn in G: ntr.add(asn) else: zombie_asn = [(asnres(ip), count) for ip, count in desc["zombie"].items()] normal_asn = [(asnres(ip), count) for ip, count in desc["clean"].items()] zombie_asn_count = defaultdict(int) for asn, count in zombie_asn: zombie_asn_count[asn] += count normal_asn_count = defaultdict(int) for asn, count in normal_asn: normal_asn_count[asn] += count for asn in set( chain(normal_asn_count.keys(), zombie_asn_count.keys())): if zombie_asn_count[asn] > normal_asn_count[asn]: ztr.add(asn) else: ntr.add(asn) # for ip in desc["zombie"]: # asn = asnres(ip) # if asn in G: # ztr.add(asn) # for ip in desc["clean"]: # asn = asnres(ip) # if asn in G: # ntr.add(asn) # Remove ASN 0 from results if "0" in ztr: ztr.remove("0") if "0" in ntr: ntr.remove("0") # print("traceroute conflicting results: {}".format(len(ntr.intersection(ztr))/len(ntr.union(ztr)))) ztr = ztr.difference(ntr) ##### BGP data ##### fname = "zombie_paths/zombies_%s_%s.txt" % (ts, prefix.replace( "/", "_").replace("-", ":")) zbgp = set() nbgp = set() if use_bgp_data: for line in open(fname): asn, zombie = [x for x in line.split()] if asn in G: if int(zombie): zbgp.add(asn) else: nbgp.add(asn) ##### Ground Truth: Merge BGP and traceroute ##### zgt = set() ngt = set() cgt = set() zgt = ztr.union(zbgp) ngt = ntr.union(nbgp) # ASNs labelled both normal and zombies are set as unknown cgt = zgt.intersection(ngt) zgt = zgt.difference(cgt) ngt = ngt.difference(cgt) ##### Esteban's results ##### fname = esteban_results_directory + "/%s_%s/result/classification.txt" % ( ts, prefix.replace("/", "_")) if not os.path.exists(fname): logging.error("Error no classification results: {}".format(fname)) return zpr = set() npr = set() for i, line in enumerate(open(fname)): # skip the header if i == 0: continue cluster, asn = [x.partition(".")[0] for x in line.split()] if int(cluster) == 2: zpr.add(asn) else: npr.add(asn) if len(zpr) == 0: logging.error("G-SSL returned no zombies!") return ##### Validation Results ##### try: os.makedirs("validation/%s_%s/" % (ts, prefix.replace("/", "_"))) except: pass fname = "validation/%s_%s/validation.txt" % (ts, prefix.replace("/", "_")) fi = open(fname, "w") fi.write("%s nodes in total\n" % (len(G))) fi.write("Traceroute: %s zombies, %s normal\n" % (len(ztr), len(ntr))) fi.write("BGP: %s zombies, %s normal\n" % (len(zbgp), len(nbgp))) fi.write("Ground Truth: %s zombies, %s normal, %s conflicting\n" % (len(zgt), len(ngt), len(cgt))) fi.write("Page Rank: %s zombies, %s normal\n" % (len(zpr), len(npr))) # print "Intersection: zombies gt&pr %s" % (len(zgt.intersection(zpr))) # print "Intersection: normal gt&pr %s" % (len(ngt.intersection(npr))) # print "Intersection: unk/zombies gt&pr %s" % (len(cgt.intersection(zpr))) res = """ Ground Truth zombie normal conflict unknown zombie %s %s %s %s normal %s %s %s %s """ % (len(zpr.intersection(zgt)), len( zpr.intersection(ngt)), len(zpr.intersection(cgt)), len(zpr.difference(zgt.union(ngt.union(cgt)))), len(npr.intersection(zgt)), len( npr.intersection(ngt)), len(npr.intersection(cgt)), len(npr.difference(zgt.union(ngt.union(cgt))))) if len(npr.intersection(zgt)) > 10: print("resultats pourri: ", ts, prefix) fi.write(res) fi.close() ### Plot the graph ### # pos = nx.spring_layout(G) pos = nx.kamada_kawai_layout(G) # INPUT Graph plt.figure(figsize=(12, 12)) nx.draw_networkx_nodes(G, pos, nodelist=["12654"], node_color='b', node_size=700) nx.draw_networkx_nodes(G, pos, nodelist=zbgp, node_color='r', node_shape="o", node_size=300) nx.draw_networkx_nodes(G, pos, nodelist=nbgp, node_color='g', node_shape="o", node_size=300) nx.draw_networkx_nodes( G, pos, nodelist=zpr.union(npr).difference(zbgp).difference(nbgp), node_color='gray', node_shape="o", node_size=300) nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5, edge_color="k") plt.grid(False) plt.axis("off") plt.tight_layout() plt.savefig("validation/%s_%s/graph_input.pdf" % (ts, prefix.replace("/", "_"))) nx.draw_networkx_labels(G, pos, {x: x for x in G.nodes()}) plt.savefig("validation/%s_%s/graph_input_labelled.pdf" % (ts, prefix.replace("/", "_"))) # plt.show() plt.close() # OUTPUT Graph and groud truth plt.figure(figsize=(12, 12)) nx.draw_networkx_nodes(G, pos, nodelist=["12654"], node_color='b', node_size=700) nx.draw_networkx_nodes(G, pos, nodelist=zpr.intersection(zgt), node_color='r', node_shape="^", node_size=300) nx.draw_networkx_nodes(G, pos, nodelist=zpr.intersection(ngt), node_color='g', node_shape="^", node_size=300) nx.draw_networkx_nodes(G, pos, nodelist=zpr.intersection(cgt), node_color='orange', node_shape="^", node_size=300) nx.draw_networkx_nodes( G, pos, nodelist=zpr.difference(ngt).difference(zgt).difference(cgt), node_color='gray', node_shape="^", node_size=300) nx.draw_networkx_nodes( G, pos, nodelist=npr.difference(ngt).difference(zgt).difference(cgt), node_color='gray', node_shape="o", node_size=300) nx.draw_networkx_nodes(G, pos, nodelist=npr.intersection(ngt), node_color='g', node_shape="o", node_size=300) nx.draw_networkx_nodes(G, pos, nodelist=npr.intersection(zgt), node_color='r', node_shape="o", node_size=300) nx.draw_networkx_nodes(G, pos, nodelist=npr.intersection(cgt), node_color='orange', node_shape="o", node_size=300) nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5, edge_color="k") plt.grid(False) plt.axis("off") plt.tight_layout() plt.savefig("validation/%s_%s/graph.pdf" % (ts, prefix.replace("/", "_"))) nx.draw_networkx_labels(G, pos, {x: x for x in G.nodes()}) plt.savefig("validation/%s_%s/graph_labelled.pdf" % (ts, prefix.replace("/", "_"))) # plt.show() plt.close() return { "ZZ": len(zpr.intersection(zgt)), "ZN": len(zpr.intersection(ngt)), "ZC": len(zpr.intersection(cgt)), "ZU": len(zpr.difference(zgt.union(ngt.union(cgt)))), "NZ": len(npr.intersection(zgt)), "NN": len(npr.intersection(ngt)), "NC": len(npr.intersection(cgt)), "NU": len(npr.difference(zgt.union(ngt.union(cgt)))) }
plt.savefig("derivative_function.png") # draw gradient map plt.clf() plt.xlim(-2.0, 2.0) plt.ylim(-2.0, 2.0) x0, x1 = np.mgrid[-2.0:2.1:0.25, -2.0:2.1:0.25] x0 = x0.flatten() x1 = x1.flatten() g0, g1 = np.copy(x0), np.copy(x1) for idx in range(x0.size): grad = numerical_gradient(__test_function_2, np.array([x0[idx], x1[idx]])) g0[idx] -= grad[0] g1[idx] -= grad[1] plt.quiver(x0, x1, g0, g1, angles="xy", scale_units="xy", scale=10) plt.grid(which='major',color='lightgray',linestyle='--', linewidth=1, alpha=90) plt.savefig("gradient_map.png") # draw gradient descent plt.clf() x = np.array([-3.0, 4.0]) plt.plot(x[0], x[1], "o", color="steelblue") for _ in range(1000): x = gradient_descent(__test_function_2, x, lr=0.1, step_num=1) plt.plot(x[0], x[1], "o", color="steelblue") n = 100 x = np.linspace(-3.5, 3.5, n) y = np.linspace(-4, 4, n) X, Y = np.meshgrid(x, y) Z = X**2 + Y**2 - 1
colnames = list(comydata.columns) # Convert string into unique integer values. comydata.loc[comydata['ShelveLoc'] == 'Good', 'ShelveLoc'] = 0 comydata.loc[comydata['ShelveLoc'] == 'Bad', 'ShelveLoc'] = 1 comydata.loc[comydata['ShelveLoc'] == 'Medium', 'ShelveLoc'] = 2 comydata.loc[comydata['Urban'] == 'Yes', 'Urban'] = 1 comydata.loc[comydata['Urban'] == 'No', 'Urban'] = 0 comydata.loc[comydata['US'] == 'Yes', 'US'] = 1 comydata.loc[comydata['US'] == 'No', 'US'] = 0 # plot histogram plt.hist(comydata['Urban'], edgecolor='k') plt.grid(axis='y') plt.show() # check skewnee & kurtosis # graph plot comydata['Sales'].skew() comydata['Sales'].kurt() plt.hist(comydata['Sales'], edgecolor='k') sns.distplot(comydata['Sales'], hist=False) plt.boxplot(comydata['Sales']) comydata['CompPrice'].skew() comydata['CompPrice'].kurt() plt.hist(comydata['CompPrice'], edgecolor='k') sns.distplot(comydata['CompPrice'], hist=False) plt.boxplot(comydata['CompPrice'])
def createPlot(curve_log, plot_label, xlist, xlabel, ylabel, \ approx_median, approx_5, approx_95, approx_label, \ max_median, size_max_5, max_95, min_label, \ min_median, size_min_5, min_95, max_label): # starting the plotting # matplotlib.rcParams.update({'font.size': 14}) plt.figure() plt.figure(facecolor='w', edgecolor='k', figsize=(7, 5)) plt.xlabel(xlabel) plt.ylabel(ylabel) # curves if curve_log: approxCV,_ = curve_fit(func2D, np.log(xlist), approx_median) maxCV,_ = curve_fit(func2D, np.log(xlist), max_median) minCV,_ = curve_fit(func2D, np.log(xlist), min_median) approx_5_CV,_ = curve_fit(func2D, np.log(xlist), approx_5) max_5_CV,_ = curve_fit(func2D, np.log(xlist), size_max_5) min_5_CV,_ = curve_fit(func2D, np.log(xlist), size_min_5) approx_95_CV,_ = curve_fit(func2D, np.log(xlist), approx_95) max_95_CV,_ = curve_fit(func2D, np.log(xlist), max_95) min_95_CV,_ = curve_fit(func2D, np.log(xlist), min_95) else: approxCV,_ = curve_fit(func2D, xlist, approx_median) maxCV,_ = curve_fit(func2D, xlist, max_median) minCV,_ = curve_fit(func2D, xlist, min_median) approx_5_CV,_ = curve_fit(func2D, xlist, approx_5) max_5_CV,_ = curve_fit(func2D, xlist, size_max_5) min_5_CV,_ = curve_fit(func2D, xlist, size_min_5) approx_95_CV,_ = curve_fit(func2D, xlist, approx_95) max_95_CV,_ = curve_fit(func2D, xlist, max_95) min_95_CV,_ = curve_fit(func2D, xlist, min_95) xlist = np.array(xlist) # plot the points plt.plot(xlist, max_median, 'o', markersize=4, label=max_label, color='orangered') plt.plot(xlist, approx_median, '*', markersize=4, label=approx_label, color='skyblue') plt.plot(xlist, min_median, 's', markersize=4, label=min_label, color='seagreen') plt.plot(xlist, [x*bound for x in max_median], '^', markersize=4, label="2/3 of Max", color='gold') xlist = np.linspace(xlist[0], xlist[-1], 200) if curve_log: # plot the best fit curves plt.plot(xlist, func2D(np.log(xlist), maxCV[0], maxCV[1], maxCV[2]), '-', color='orangered') plt.plot(xlist, func2D(np.log(xlist), approxCV[0], approxCV[1], approxCV[2]), '-', color='skyblue') plt.plot(xlist, func2D(np.log(xlist), minCV[0], minCV[1], minCV[2]), '-', color='seagreen') plt.plot(xlist, func2D(np.log(xlist), maxCV[0]*bound, maxCV[1]*bound, maxCV[2]*bound), '-', color='gold') # plot the confidence intervals plt.fill_between(xlist, func2D(np.log(xlist), max_5_CV[0], max_5_CV[1], max_5_CV[2]), \ func2D(np.log(xlist), max_95_CV[0], max_95_CV[1], max_95_CV[2]), color='orangered', alpha=.5) plt.fill_between(xlist, func2D(np.log(xlist), approx_5_CV[0], approx_5_CV[1], approx_5_CV[2]), \ func2D(np.log(xlist), approx_95_CV[0], approx_95_CV[1], approx_95_CV[2]), color='skyblue', alpha=.5) plt.fill_between(xlist, func2D(np.log(xlist), min_5_CV[0], min_5_CV[1], min_5_CV[2]), \ func2D(np.log(xlist), min_95_CV[0], min_95_CV[1], min_95_CV[2]), color='seagreen', alpha=.5) plt.fill_between(xlist, func2D(np.log(xlist), max_5_CV[0]*bound, max_5_CV[1]*bound, max_5_CV[2]*bound), \ func2D(np.log(xlist), max_95_CV[0]*bound, max_95_CV[1]*bound, max_95_CV[2]*bound), color='gold', alpha=.5) else: # plot the best fit curves plt.plot(xlist, func2D(xlist, maxCV[0], maxCV[1], maxCV[2]), '-', color='orangered') plt.plot(xlist, func2D(xlist, approxCV[0], approxCV[1], approxCV[2]), '-', color='skyblue') plt.plot(xlist, func2D(xlist, minCV[0], minCV[1], minCV[2]), '-', color='seagreen') plt.plot(xlist, func2D(xlist, maxCV[0]*bound, maxCV[1]*bound, maxCV[2]*bound), '-', color='gold') # plot the confidence intervals plt.fill_between(xlist, func2D(xlist, max_5_CV[0], max_5_CV[1], max_5_CV[2]), \ func2D(xlist, max_95_CV[0], max_95_CV[1], max_95_CV[2]), color='orangered', alpha=.5) plt.fill_between(xlist, func2D(xlist, approx_5_CV[0], approx_5_CV[1], approx_5_CV[2]), \ func2D(xlist, approx_95_CV[0], approx_95_CV[1], approx_95_CV[2]), color='skyblue', alpha=.5) plt.fill_between(xlist, func2D(xlist, min_5_CV[0], min_5_CV[1], min_5_CV[2]), \ func2D(xlist, min_95_CV[0], min_95_CV[1], min_95_CV[2]), color='seagreen', alpha=.5) plt.fill_between(xlist, func2D(xlist, max_5_CV[0]*bound, max_5_CV[1]*bound, max_5_CV[2]*bound), \ func2D(xlist, max_95_CV[0]*bound, max_95_CV[1]*bound, max_95_CV[2]*bound), color='gold', alpha=.5) # plt.plot([100, 1000], [100, 1000000], "--", label="Gradient 4n") if plot_label == 'PREF': plt.xlim(xmin=1, xmax=10) if plot_label == 'SIZE': plt.xlim(xmin=0, xmax=1000) if plot_label == 'TIES': plt.xlim(xmin=0, xmax=0.5) # plt.yscale('log') plt.grid() plt.legend() # plt.legend(loc='upper left') plt.tight_layout() filename = dirName + "/" + plot_label + "_plot.pdf" plt.savefig(filename) plt.close()
def plot_px_history(table, keys, hot_pixels=None, slot=0, mag=None, bgd_class_name='FlightBgd', legend_text="", title_text='Hot'): """ Plot time series of a given ACA pixel value. :param table: table with results of call to centroids() (see centroids.py) :param keys: list containing pixel coordinates, e.g. [(120, 210), (30, 150)] :param slot: slot number :param mag: magnitude :param bgd_class_name: class used for background calculation (see classes.py) """ n = len(keys) ll = 3 * n fig = plt.figure(figsize=(6, ll)) ok1 = table['slot'] == slot ok2 = table['bgd_class_name'] == bgd_class_name ok = ok1 * ok2 if mag is not None: ok3 = table['mag'] == mag ok = ok * ok3 for i, key in enumerate(keys): plt.subplot(n, 1, i + 1) deques = table[ok]['deque_dict'][0] time = table[ok]['time'][0] - table[ok]['time'][0][0] px_vals = [] bgd_vals = [] current_bgd_val = 0 for i, deque in enumerate(deques): if key in deque.keys(): current_px_val = deque[key][-1] if bgd_class_name == 'DynamBgd_Median': current_bgd_val = np.median(deque[key]) elif bgd_class_name == 'DynamBgd_SigmaClip': current_bgd_val = sigma_clip(deque[key]) px_vals.append(current_px_val) bgd_vals.append(current_bgd_val) else: px_vals.append(-1) bgd_vals.append(-1) if legend_text == 'Simulated': plt.plot(table['time'][0] - table['time'][0][0], hot_pixels[key], label=legend_text, color='gray') plt.plot(time, px_vals, label='Sampled', color='slateblue') plt.plot(time, bgd_vals, label="Derived", color='darkorange', lw=2) plt.xlabel('Time (sec)') plt.ylabel('Pixel value') plt.title('{} pixel coordinates = {}'.format(title_text, key)) plt.legend() plt.grid() plt.margins(0.05) plt.subplots_adjust(left=0.05, right=0.99, top=0.9, bottom=0.2, hspace=0.5, wspace=0.3) return
def test_CylMeshEBDipoles(self, plotIt=plotIt): print("Testing CylMesh Electric and Magnetic Dipoles in a wholespace-" " Analytic: J-formulation") sigmaback = 1. mur = 2. freq = 1. skdpth = 500. / np.sqrt(sigmaback * freq) csx, ncx, npadx = 5, 50, 25 csz, ncz, npadz = 5, 50, 25 hx = Utils.meshTensor([(csx, ncx), (csx, npadx, 1.3)]) hz = Utils.meshTensor([(csz, npadz, -1.3), (csz, ncz), (csz, npadz, 1.3)]) # define the cylindrical mesh mesh = Mesh.CylMesh([hx, 1, hz], [0., 0., -hz.sum() / 2]) if plotIt: mesh.plotGrid() # make sure mesh is big enough self.assertTrue(mesh.hz.sum() > skdpth * 2.) self.assertTrue(mesh.hx.sum() > skdpth * 2.) # set up source # test electric dipole src_loc = np.r_[0., 0., 0.] s_ind = Utils.closestPoints(mesh, src_loc, 'Fz') + mesh.nFx de = np.zeros(mesh.nF, dtype=complex) de[s_ind] = 1. / csz de_p = [EM.FDEM.Src.RawVec_e([], freq, de / mesh.area)] dm_p = [EM.FDEM.Src.MagDipole([], freq, src_loc)] # Pair the problem and survey surveye = EM.FDEM.Survey(de_p) surveym = EM.FDEM.Survey(dm_p) prbe = EM.FDEM.Problem3D_h(mesh, sigma=sigmaback, mu=mur * mu_0) prbm = EM.FDEM.Problem3D_e(mesh, sigma=sigmaback, mu=mur * mu_0) # pair problem and survey prbe.pair(surveye) prbm.pair(surveym) # solve fieldsBackE = prbe.fields() fieldsBackM = prbm.fields() rlim = [20., 500.] # lookAtTx = de_p r = mesh.vectorCCx[np.argmin(np.abs(mesh.vectorCCx - rlim[0])):np. argmin(np.abs(mesh.vectorCCx - rlim[1]))] z = 100. # where we choose to measure XYZ = Utils.ndgrid(r, np.r_[0.], np.r_[z]) Pf = mesh.getInterpolationMat(XYZ, 'CC') Zero = sp.csr_matrix(Pf.shape) Pfx, Pfz = sp.hstack([Pf, Zero]), sp.hstack([Zero, Pf]) jn = fieldsBackE[de_p, 'j'] bn = fieldsBackM[dm_p, 'b'] SigmaBack = sigmaback * np.ones((mesh.nC)) Rho = Utils.sdiag(1. / SigmaBack) Rho = sp.block_diag([Rho, Rho]) en = Rho * mesh.aveF2CCV * jn bn = mesh.aveF2CCV * bn ex, ez = Pfx * en, Pfz * en bx, bz = Pfx * bn, Pfz * bn # get analytic solution exa, eya, eza = EM.Analytics.FDEM.ElectricDipoleWholeSpace( XYZ, src_loc, sigmaback, freq, orientation='Z', mu=mur * mu_0) exa = Utils.mkvc(exa, 2) eya = Utils.mkvc(eya, 2) eza = Utils.mkvc(eza, 2) bxa, bya, bza = EM.Analytics.FDEM.MagneticDipoleWholeSpace( XYZ, src_loc, sigmaback, freq, orientation='Z', mu=mur * mu_0) bxa = Utils.mkvc(bxa, 2) bya = Utils.mkvc(bya, 2) bza = Utils.mkvc(bza, 2) print( ' comp, anayltic, numeric, num - ana, (num - ana)/ana' ) print(' ex:', np.linalg.norm(exa), np.linalg.norm(ex), np.linalg.norm(exa - ex), np.linalg.norm(exa - ex) / np.linalg.norm(exa)) print(' ez:', np.linalg.norm(eza), np.linalg.norm(ez), np.linalg.norm(eza - ez), np.linalg.norm(eza - ez) / np.linalg.norm(eza)) print(' bx:', np.linalg.norm(bxa), np.linalg.norm(bx), np.linalg.norm(bxa - bx), np.linalg.norm(bxa - bx) / np.linalg.norm(bxa)) print(' bz:', np.linalg.norm(bza), np.linalg.norm(bz), np.linalg.norm(bza - bz), np.linalg.norm(bza - bz) / np.linalg.norm(bza)) if plotIt is True: # Edipole plt.subplot(221) plt.plot(r, ex.real, 'o', r, exa.real, linewidth=2) plt.grid(which='both') plt.title('Ex Real') plt.xlabel('r (m)') plt.subplot(222) plt.plot(r, ex.imag, 'o', r, exa.imag, linewidth=2) plt.grid(which='both') plt.title('Ex Imag') plt.legend(['Num', 'Ana'], bbox_to_anchor=(1.5, 0.5)) plt.xlabel('r (m)') plt.subplot(223) plt.plot(r, ez.real, 'o', r, eza.real, linewidth=2) plt.grid(which='both') plt.title('Ez Real') plt.xlabel('r (m)') plt.subplot(224) plt.plot(r, ez.imag, 'o', r, eza.imag, linewidth=2) plt.grid(which='both') plt.title('Ez Imag') plt.xlabel('r (m)') plt.tight_layout() # Bdipole plt.subplot(221) plt.plot(r, bx.real, 'o', r, bxa.real, linewidth=2) plt.grid(which='both') plt.title('Bx Real') plt.xlabel('r (m)') plt.subplot(222) plt.plot(r, bx.imag, 'o', r, bxa.imag, linewidth=2) plt.grid(which='both') plt.title('Bx Imag') plt.legend(['Num', 'Ana'], bbox_to_anchor=(1.5, 0.5)) plt.xlabel('r (m)') plt.subplot(223) plt.plot(r, bz.real, 'o', r, bza.real, linewidth=2) plt.grid(which='both') plt.title('Bz Real') plt.xlabel('r (m)') plt.subplot(224) plt.plot(r, bz.imag, 'o', r, bza.imag, linewidth=2) plt.grid(which='both') plt.title('Bz Imag') plt.xlabel('r (m)') plt.tight_layout() self.assertTrue( np.linalg.norm(exa - ex) / np.linalg.norm(exa) < tol_EBdipole) self.assertTrue( np.linalg.norm(eza - ez) / np.linalg.norm(eza) < tol_EBdipole) self.assertTrue( np.linalg.norm(bxa - bx) / np.linalg.norm(bxa) < tol_EBdipole) self.assertTrue( np.linalg.norm(bza - bz) / np.linalg.norm(bza) < tol_EBdipole)
plt.plot(hist.history['loss']) plt.title("loss") plt.subplot(1, 2, 2) plt.title("accuracy") plt.plot(hist.history['acc'], 'b-', label="training") plt.plot(hist.history['val_acc'], 'r:', label="validation") plt.legend() plt.tight_layout() plt.show() number = int(input('몇 번째 학습데이터를 학습완료된 신경망에 넣겠습니까?')) model.predict(X_test[number:number + 1, :]) plt.figure(figsize=(1, 1)) plt.imshow(X_test0[number], cmap=plt.cm.bone_r) plt.grid(False) plt.axis("off") plt.show() model.save('my_model.hdf5') del model from tensorflow.keras.models import load_model model2 = load_model('my_model.hdf5') predictnum = model2.predict_classes(X_test[number:number + 1, :]) print(predictnum) import pyttsx3 engine = pyttsx3.init()
old_pos = self.is_dragged.get_position() new_pos = (old_pos[0] + event.xdata - self.pick_pos[0], old_pos[1] + event.ydata - self.pick_pos[1]) self.is_dragged.set_position(new_pos) self.is_dragged = None p.draw() return True # Usage example from numpy import * # Create arbitrary points and labels x, y = random.normal(5, 2, size=(2, 9)) labels = ["Point %d" % i for i in xrange(x.size)] # trace a scatter plot p.scatter(x, y) p.grid() # add labels and set their picker attribute to True for a, b, l in zip(x, y, labels): p.text(a, b, l, picker=True) # Create the event hendler dragh = DragHandler() p.show() # vim: set et:
def main(): # define parameters (rows, columns, vision, start state, goal state, probability distribution) # comment out either the user option or the hard coded option # user (raw input option) nrows = int(input("Number of Rows? (int) " )) ncols = int(input("Number of Columns? (int) ")) agent_vision = int(input("Agent vision distance? (int) ")) start=[] goal=[] startInp = input("Start Position? X,Y,[north,south,east,west],[center,left,right] ") startInp=startInp.split(",") startInp[0]=int(startInp[0]) startInp[1]=int(startInp[1]) for i in heading: if(startInp[2]==i): startInp[2]=i start=tuple(startInp) goalInp = input("Goal Position? X,Y,[north,south,east,west],[center,left,right] ") goalInp=goalInp.split(",") goalInp[0]=int(goalInp[0]) goalInp[1]=int(goalInp[1]) for i in angle: if(goalInp[2]==i): goalInp[2]=i goal=tuple(goalInp) p1=float(input("Probability of an obstacle in any given location? (float between 0 and 1) ")) p2=1-p1 prob=[p2,p1] # Hard coded option '''nrows = 10 ncols = 10 prob = [0.7, 0.3] start = (0,0,s,c) goal = (9,9,s,c) agent_vision = 5''' # construct state lattice and state graph state_lattice = build_state_lattice(nrows, ncols, prob) state_graph_init = build_state_graph(state_lattice) state_graph_complete = assign_edges(state_lattice, state_graph_init) agent_state_graph = state_graph_complete # agent starts by thinking entire state space is free # in the case that the randomization blocked our start or goal states # we unblock them ;) if(state_lattice[start[0]][start[1]]==1): state_lattice[start[0]][start[1]]=0 if(state_lattice[goal[0]][goal[1]]==1): state_lattice[goal[0]][goal[1]]=0 # define important variables to keep track of agent_location = start # variable to keep track of agent's location agent_path = [] # list to document agent's path total_cost = 0 # total cost of agent's path total_nodes_expanded = 0 # number of nodes expanded in A* search astar_plans = 0 # number of A* plans that the agent makes store_astar_plans = [] # store each A* plan to graph later graph_bool = True # boolean to keep track of whether path to goal was reached - for graphing purposes # the process of making A* plans and maneuvering through the state space while True: if agent_location == goal: print("************************\nAGENT REACHED GOAL STATE\n************************") agent_path.append(agent_location) break # update agent's knowledge based on current location agent_state_graph = update_knowledge(agent_location, agent_state_graph, state_lattice, agent_vision) # make new A* plan based on updated knowledge astar_result = astar_search(agent_location, goal, agent_state_graph, state_lattice, euclidean_distance, return_cost = True, return_nexp = True) if(astar_result == None): # if A* returns None, there is no path to the goal state print("************************\nNO POSSIBLE PATH TO GOAL\n************************") graph_bool = False break # assign A* information to variables path, cost, nodes_expanded = astar_result[0], astar_result[1], astar_result[2] # document A* planned path store_astar_plans.append(path) # update statistics astar_plans += 1 total_cost += cost total_nodes_expanded += nodes_expanded # navigate agent based on current A* plan for state in path: # agent senses blocked nodes right in front of it (the next planned state) if state_lattice[state[0]][state[1]] == 1: # can't go there! break # move agent along path else: agent_location = state agent_path.append(agent_location) # print out results print('AGENT SUMMARY: ') print('Start State: ', start) print('Goal State: ', goal) print('State Space Dimensions: {} x {} units'.format(nrows, ncols)) print('Agent Vision: ', agent_vision) print('*************************************') print('Number of A* plans = ', astar_plans) print('Agent Path: ') for i in range(len(agent_path)): print(agent_path[i]) print('Total Path Cost = ', total_cost) print('Total Number of Nodes Expanded = ', total_nodes_expanded) # graph results # graph state lattice slx0 = [] sly0 = [] slx1 = [] sly1 = [] for ii in range(len(state_lattice)): for jj in range(len(state_lattice[0])): if state_lattice[ii][jj] == 0: slx0.append(ii) sly0.append(jj) elif state_lattice[ii][jj] == 1: slx1.append(ii) sly1.append(jj) plt.plot(slx0, sly0, 'o', color = 'grey', label = "Open Nodes") plt.plot(slx1, sly1, '1', color = 'grey', markersize = 15, label = "Blocked Nodes") # graph A* plans plan_number = 0 color_list = ['b','g','r','c','m','y','turquoise', 'purple'] for plan in store_astar_plans: x = [] y = [] for state in plan: x.append(state[0]) y.append(state[1]) color_choice = color_list[plan_number] plt.plot(x,y, 'o-', color = color_choice, label = 'A* Plan ' + str(plan_number)) plan_number += 1 # graph actual agent path x = [] y = [] agent_path_copy = agent_path[1:len(agent_path)-1] for state in agent_path_copy: x.append(state[0]) y.append(state[1]) plt.plot(x,y,'ko', label = 'Agent Path') # graph start and goal states plt.plot(start[0], start[1], 'k^', label = 'Start', markersize = 12) plt.plot(goal[0], goal[1], 'kD', label = 'Goal', markersize = 10) plt.grid(True) # if there's no path to goal, indicate in graph if graph_bool == False: plt.title("No path to goal", fontsize = 16) # add labels and a legend plt.xlabel("x", fontsize=12) plt.ylabel("y", fontsize=12) plt.legend(loc = 'upper center', bbox_to_anchor = (0.5,1.15), ncol = 6) # show this shit! plt.show()
k += samples_per_bit detected += decision bit_error_rate = manchester_equalizer.calculate_ber( d[samples_per_bit * training:], detected[samples_per_bit * training:]) if printing and not n % 100: print('mu=', mu, ', ber=', bit_error_rate) ber[n] += bit_error_rate # if bit_error_rate == 0 and mu < 1: # # show results # plt.plot(u_, "orange", label="u - noisy input", alpha=0.5) # plt.plot(d, "b", label="d - target") # plt.plot(log_y, "g", label="y - output") # plt.plot(detected, 'red', label='detected bits') # plt.vlines(training * samples_per_bit, colors='red', ymin=-2, ymax=2) # plt.legend() # plt.grid(which='both') # plt.show() ber /= sims plt.plot(mus, ber) plt.grid(which='both') plt.show() df = pd.DataFrame({'mu': mus, 'ber': ber}) df.to_csv(path_or_buf='montecarlo_alpha=1e-2_N=' + str(n_filter) + 'epsilon=' + str(epsilon) + '.csv', index=False)
print('Skewness screen : ', comp['screen'].skew(), '\n\n\n') print('Kurtosis screen : ', comp['screen'].kurt(), '\n\n\n') plt.hist(comp['screen'], edgecolor='k') plt.xlabel('SCREEN') plt.show() sns.distplot(comp['screen'], hist=False) plt.xlabel('SCREEN') plt.show() plt.boxplot(comp['screen']) plt.xlabel('SCREEN') plt.show() # plot graph between price & screen df = pd.crosstab(comp['price'], comp['screen']) df.plot(kind="line", stacked=True) plt.grid(axis="y") plt.show() # speed & screen df = pd.crosstab(comp['speed'], comp['screen']) df.plot(kind="bar", stacked=True) plt.grid(axis="y") plt.show() # hd & screen df = pd.crosstab(comp['hd'], comp['screen']) df.plot(kind="line", stacked=True) plt.grid(axis="y") plt.show() # ram & screen
fig1, ax1 = plt.subplots(tight_layout=True) for b,c in zip(range(len(df.columns)),colours): fig1 = plt.plot(df.iloc[:,b], c, linewidth=1.5, linestyle=':', markersize=3) df['Market IV'] = marketiv ax1 = plt.plot(df['Market IV'], '#00B10B', marker='s', linestyle='', markersize=5) ax1 = plt.plot(df['DD Calibrated'], 'b', linewidth=1.8, linestyle='-', markersize=3) ax1 = plt.legend() ax1 = plt.ylabel('Implied Lognormal Volatility') ax1 = plt.xlabel('Strikes') ax1 = plt.grid(linestyle='--') ax1 = plt.title('Displaced Diffusion Model Calibration') #ax1 = plt.savefig('DD.png', dpi=300,quality=100) # ============================================================================= # # ============================================================================= def SABR(F, K, T, alpha, beta, rho, nu): X = K if F == K: numer1 = (((1 - beta)**2)/24)*alpha*alpha/(F**(2 - 2*beta))
def tangent_line(f, x): d = numerical_gradient(f, x) print(d) y = f(x) - d * x return lambda t: d * t + y if __name__ == '__main__': x0 = np.arange(-2, 2.5, 0.25) x1 = np.arange(-2, 2.5, 0.25) X, Y = np.meshgrid(x0, x1) X = X.flatten() Y = Y.flatten() grad = numerical_gradient(function_2, np.array([X, Y])) plt.figure() plt.quiver(X, Y, -grad[0], -grad[1], angles="xy", color="#666666") #,headwidth=10,scale=40,color="#444444") plt.xlim([-2, 2]) plt.ylim([-2, 2]) plt.xlabel('x0') plt.ylabel('x1') plt.grid() # 눈금 plt.legend() # 범례 plt.draw() plt.show()
for j in range(0, len(start_time) - 1): t1[j] = start_time[j] for i in range(0, len(start_pos_y) - 1): y1[i] = start_pos_y[i] for i in range(0, len(start_pos_x) - 1): x1[i] = start_pos_x[i] import matplotlib.pylab as pp pp.figure(1) pp.subplot(221) pp.plot(t1, y1, 'r-') pp.xlabel('t, c') pp.ylabel('h, m') pp.title('h(t)') pp.grid(True) pp.subplot(222) pp.plot(x1, y1, 'g-') pp.xlabel('x, m') pp.ylabel('y, m') pp.title('XY') pp.grid(True) pp.subplot(223) pp.plot(t1, x1, 'b-') pp.xlabel('t, m') pp.ylabel('x, m') pp.title('x') pp.legend(["x(t)"]) pp.text(7, 75, r'$v_0t$+$at^2/2$')
def show_wf(n, x): plt.title('Wave function:') plt.grid(True) plt.plot(x[0], d1_osc.wf(n,x), "r--")
def main(): # Create images folder Path("Imgs/STEAD").mkdir(parents=True, exist_ok=True) # STEAD dataset path st = '../Data/STEAD/Train_data.hdf5' # Sampling frequency fs = 100 # Number of traces to plot n = 4 # Traces to plot trtp = [] with h5py.File(st, 'r') as h5_file: # Seismic traces group grp = h5_file['earthquake']['local'] # Traces to plot ids # trtp_ids = [0, 1, 2, 3] # Init rng rng = default_rng() # Traces to plot numbers trtp_ids = rng.choice(len(grp), size=n, replace=False) trtp_ids.sort() for idx, dts in enumerate(grp): if idx in trtp_ids: trtp.append(grp[dts][:, 0]) # Sampling frequency fs = 100 # Data len N = len(trtp[0]) # Time axis for signal plot t_ax = np.arange(N) / fs # Frequency axis for FFT plot xf = np.linspace(-fs / 2.0, fs / 2.0 - 1 / fs, N) # Figure to plot pl.figure() # For trace in traces to print for idx, trace in enumerate(trtp): yf = sfft.fftshift(sfft.fft(trace)) gs = gridspec.GridSpec(2, 2) pl.clf() pl.subplot(gs[0, :]) pl.plot(t_ax, trace) pl.title(f'Traza STEAD y espectro #{trtp_ids[idx]}') pl.xlabel('Tiempo [s]') pl.ylabel('Amplitud [-]') pl.grid(True) pl.subplot(gs[1, 0]) pl.plot(xf, np.abs(yf) / np.max(np.abs(yf))) pl.xlabel('Frecuencia [Hz]') pl.ylabel('Amplitud [-]') pl.grid(True) pl.subplot(gs[1, 1]) pl.plot(xf, np.abs(yf) / np.max(np.abs(yf))) pl.xlim(-25, 25) pl.xlabel('Frecuencia [Hz]') pl.ylabel('Amplitud [-]') pl.grid(True) pl.tight_layout() pl.savefig(f'Imgs/STEAD/{trtp_ids[idx]}.png')
def show_images_sum(self, x): y = self.__images_sum_value(x) plt.title('Output:') plt.grid(True) plt.plot(x[0], y)
def show_wf_system(n_max, x): plt.title('Wave functions system:') plt.grid(True) for i in range(n_max+1): plt.plot(x[0], d1_osc.wf(i,x))