def update_design(self): ax = self.ax ax.cla() ax2 = self.ax2 ax2.cla() wp = self.wp ws = self.ws gpass = self.gpass gstop = self.gstop b, a = ss.iirdesign(wp, ws, gpass, gstop, ftype=self.ftype, output='ba') self.a = a self.b = b #b = [1,2]; a = [1,2] #Print this on command line so we can use it in our programs print 'b = ', pylab.array_repr(b) print 'a = ', pylab.array_repr(a) my_w = pylab.logspace(pylab.log10(.1*self.ws[0]), 0.0, num=512) #import pdb;pdb.set_trace() w, h = freqz(b, a, worN=my_w*pylab.pi) gp = 10**(-gpass/20.)#Go from db to regular gs = 10**(-gstop/20.) self.design_line, = ax.plot([.1*self.ws[0], self.ws[0], wp[0], wp[1], ws[1], 1.0], [gs, gs, gp, gp, gs, gs], 'ko:', lw=2, picker=5) ax.semilogx(w/pylab.pi, pylab.absolute(h),lw=2) ax.text(.5,1.0, '{:d}/{:d}'.format(len(b), len(a))) pylab.setp(ax, 'xlim', [.1*self.ws[0], 1.2], 'ylim', [-.1, max(1.1,1.1*pylab.absolute(h).max())], 'xticklabels', []) ax2.semilogx(w/pylab.pi, pylab.unwrap(pylab.angle(h)),lw=2) pylab.setp(ax2, 'xlim', [.1*self.ws[0], 1.2]) ax2.set_xlabel('Normalized frequency') pylab.draw()
def tune_alpha(self, drug_name, alphas=None, N=80, l1_ratio=0.5, n_folds=10, show=True, shuffle=False, alpha_range=[-2.8,0.1]): """Interactive tuning of the model (alpha). This is much faster than :meth:`plot_cindex` but much slower than ElasticNetCV .. plot:: :include-source: from gdsctools import * ic = IC50(gdsctools_data("IC50_v5.csv.gz")) gf = GenomicFeatures(gdsctools_data("genomic_features_v5.csv.gz")) en = GDSCElasticNet(ic, gf) en.tune_alpha(1047, N=40, l1_ratio=0.1) """ if alphas is None: # logspace returns a vector in natural space that guarantees a # uniform spacing in a log space (log10 or ln) # -2.8 to 0.5 means alpha from 1.58e-3 to 3.16 # This is equivalent to log(1.58e-3)=-6.45 to log(3.16)=1.15 in ln # scale a1, a2 = alpha_range alphas = pylab.logspace(a1, a2, N) # Let us now do a CV across difference alphas all_scores = [] for alpha in alphas: scores = self.fit(drug_name, alpha, l1_ratio=l1_ratio, n_folds=n_folds, shuffle=shuffle) all_scores.append(scores) # We can now plot the results that is the mean scores + error enveloppe df = pd.DataFrame(all_scores) # we also identify the max correlation and corresponding alpha maximum = df.mean(axis=1).max() alpha_best = alphas[df.mean(axis=1).argmax()] if show is True: mu = df.mean(axis=1) sigma = df.var(axis=1) pylab.clf() pylab.errorbar(pylab.log(alphas), mu, yerr=sigma, color="gray") pylab.plot(pylab.log(alphas), mu, 'or') pylab.axvline(pylab.log(alpha_best), lw=4, alpha=0.5, color='g') pylab.title("Mean scores (pearson) across alphas for Kfold=%s" % n_folds) pylab.xlabel("ln(alpha)") pylab.ylabel("mean score (pearson)") pylab.grid() results = {"alpha_best":alpha_best, "ln_alpha":pylab.log(alpha_best), "maximum_Rp":maximum} return results
def _do_plot_ldf(self, coincidence, x0, y0, shower_size): x = plt.logspace(-1, 3, 100) y = self.solver.ldf_given_size(x, shower_size) plt.loglog(x, y, label='LDF') r, dens = self.solver.get_ldf_measurements_for_core_position((x0, y0)) plt.loglog(r, dens, 'o', label="signals") plt.legend() plt.xlabel("Core distance [m]") plt.ylabel("Particle density [$m^{-2}$]")
def DFA(data, npoints=None, degree=1, use_median=False): """ computes the detrended fluctuation analysis returns the fluctuation F and the corresponding window length L :args: data (n-by-1 array): the data from which to compute the DFA npoints (int): the number of points to evaluate; if omitted the log(n) will be used degree (int): degree of the polynomial to use for detrending use_median (bool): use median instead of mean fluctuation :returns: F, L: the fluctuation F as function of the window length L """ # max window length: n/4 #0th: compute integral integral = cumsum(data - mean(data)) #1st: compute different window lengths n_samples = npoints if npoints is not None else int(log(len(data))) lengths = sort(array(list(set( logspace(2,log(len(data)/4.),n_samples,base=exp(1)).astype(int) )))) #print lengths all_flucs = [] used_lengths = [] for wlen in lengths: # compute the fluctuation of residuals from a linear fit # according to Kantz&Schreiber, ddof must be the degree of polynomial, # i.e. 1 (or 2, if mean also counts? -> see in book) curr_fluc = [] # rrt = 0 for startIdx in arange(0,len(integral),wlen): pt = integral[startIdx:startIdx+wlen] if len(pt) > 3*(degree+1): resids = pt - polyval(polyfit(arange(len(pt)),pt,degree), arange(len(pt))) # if abs(wlen - lengths[0]) < -1: # print resids[:20] # elif rrt == 0: # print "wlen", wlen, "l0", lengths[0] # rrt += 1 curr_fluc.append(std(resids, ddof=degree+1)) if len(curr_fluc) > 0: if use_median: all_flucs.append(median(curr_fluc)) else: all_flucs.append(mean(curr_fluc)) used_lengths.append(wlen) return array(all_flucs), array(used_lengths)
def ConvergenceMesh(): pl.figure() Roell_list = pl.logspace(pl.log10(0.1), pl.log10(50), 20) tf_list = [] te_list = [] for Roell in Roell_list: ell = 1 / Roell te, tf = find_data(["material.ell", "problem.rho", "problem.hsize"], [ell, 0.1, 1e-3]) te_list.append(te) tf_list.append(tf) pl.loglog(Roell_list, tf_list, "bo-", alpha=0.5, label=r"$h=1\times10^{-3}$") tf_list = [] te_list = [] for Roell in Roell_list: ell = 1 / Roell te, tf = find_data(["material.ell", "problem.rho", "problem.hsize"], [ell, 0.1, 4e-3]) te_list.append(te) tf_list.append(tf) pl.loglog(Roell_list, tf_list, "g*-", alpha=0.5, label=r"$h=2\times10^{-3}$") tf_list = [] te_list = [] for Roell in Roell_list: ell = 1 / Roell te, tf = find_data(["material.ell", "problem.rho", "problem.hsize"], [ell, 0.1, 1e-2]) te_list.append(te) tf_list.append(tf) pl.loglog(Roell_list, tf_list, "r>-", alpha=0.5, label=r"$h=1\times10^{-2}$") pl.xlabel(r"Relative defect size $a/\ell$") pl.ylabel("Remote stress at fracture $\sigma_\infty/\sigma_0$") pl.legend(loc="best") pl.title(r"$\rho=0.1$").set_y(1.04) pl.xlim([9e-2, 1e2]) pl.grid(True) pl.savefig("conv_h.pdf", bbox_inches='tight')
def tune_alpha(self, drug_name, alphas=None, N=100, l1_ratio=0.5, n_folds=10, plot=True): """ .. plot:: an.tune_alpha("1047", N=100, l1_ratio=0.1) an.tune_alpha("1047", N=100, l1_ratio=0.01) an.tune_alpha("1047", N=100, l1_ratio=0.001) an.tune_alpha("1047", N=100, l1_ratio=0.0001) 29, 34, 52, 1014, 1015, 1024, 1036, 1047, 1061 """ # alphas = 10**-linspace(6,1,100) if alphas is None: alphas = pylab.logspace(-5, 0, N) all_scores = [] median_scores = [] for alpha in alphas: scores = self.elastic_net(drug_name, alpha, l1_ratio=l1_ratio, n_folds=n_folds) median_scores.append(np.mean(scores)) all_scores.append(scores) #pylab.plot(pylab.log(alphas), median_scores, '-o') df = pd.DataFrame(all_scores) maximum = df.mean(axis=1).max() alpha_best = alphas[df.mean(axis=1).argmax()] if plot is True: mu = df.mean(axis=1) sigma = df.std(axis=1) pylab.clf() pylab.errorbar(pylab.log(alphas), mu, yerr=sigma) pylab.plot(pylab.log(alphas), mu, 'or') pylab.axvline(pylab.log(alpha_best), lw=4, alpha=0.5, color='g') pylab.title("Mean scores across alphas") pylab.xlabel("alpha") pylab.ylabel("mean score") return alphas, all_scores, maximum, alpha_best
def plot(df, *args, **kw): N = df["count"].sum() deltas_ = df["count"].values[:-1] - df["count"].values[1:] deltas = pl.array([deltas_[0]] + list(pl.amin([deltas_[1:], deltas_[:-1]], axis=0)) + [deltas_[-1]]) dfrac = (deltas + 1e-20) / N def frac_leaked(q): attacked = dfrac * q > (2 * q * df["count"] / N) ** 0.5 N_a = df["count"][attacked].sum() return float(N_a) / N Ns = pl.logspace(0, 15, 100) fracs = pl.array(map(frac_leaked, Ns)) pl.semilogx(Ns, fracs * 100, *args, **kw)
def plot(df, *args, **kw): N = df["count"].sum() deltas_ = df['count'].values[:-1] - df['count'].values[1:] deltas = pl.array([deltas_[0]] + list(pl.amin([deltas_[1:], deltas_[:-1]], axis=0)) + [deltas_[-1]]) dfrac = (deltas + 1e-20) / N def frac_leaked(q): attacked = dfrac * q > (2 * q * df['count'] / N) ** 0.5 N_a = df['count'][attacked].sum() return float(N_a) / N Ns = pl.logspace(0, 15, 100) fracs = pl.array(map(frac_leaked, Ns)) pl.semilogx(Ns, fracs * 100, *args, **kw)
def tune_alpha(self, drug_name, alphas=None, N=100, l1_ratio=0.5, n_folds=10, plot=True): """ .. plot:: an.tune_alpha("1047", N=100, l1_ratio=0.1) an.tune_alpha("1047", N=100, l1_ratio=0.01) an.tune_alpha("1047", N=100, l1_ratio=0.001) an.tune_alpha("1047", N=100, l1_ratio=0.0001) 29, 34, 52, 1014, 1015, 1024, 1036, 1047, 1061 """ # alphas = 10**-linspace(6,1,100) if alphas is None: alphas = pylab.logspace(-5,0,N) all_scores = [] median_scores = [] for alpha in alphas: scores = self.elastic_net(drug_name, alpha, l1_ratio=l1_ratio, n_folds=n_folds) median_scores.append(np.mean(scores)) all_scores.append(scores) #pylab.plot(pylab.log(alphas), median_scores, '-o') df = pd.DataFrame(all_scores) maximum = df.mean(axis=1).max() alpha_best = alphas[df.mean(axis=1).argmax()] if plot is True: mu = df.mean(axis=1) sigma = df.std(axis=1) pylab.clf() pylab.errorbar(pylab.log(alphas), mu, yerr=sigma) pylab.plot(pylab.log(alphas), mu, 'or') pylab.axvline(pylab.log(alpha_best), lw=4, alpha=0.5, color='g') pylab.title("Mean scores across alphas") pylab.xlabel("alpha") pylab.ylabel("mean score") return alphas, all_scores, maximum, alpha_best
def bodeplot(): # denominator and numerator denominator = polymul([1, 0], [1, 16, 100]) numerator = [7.5] numerator = polymul(numerator, [0.2, 1]) numerator = polymul(numerator, [1, 1]) system = signal.lti(numerator, denominator) domain = logspace(-3, 3) omega, magnitude, phase = signal.bode(system, 2*pi*domain) # break frequencies break_frequencies = [1, 5, 10] _, plot = plt.subplots(2, sharex=True) plot[0].semilogx(omega, magnitude) plot[0].vlines(break_frequencies, ymin=min(magnitude), ymax=max(magnitude), colors='C1') plot[0].set_title('Bode Plot') plot[1].semilogx(omega, phase) plot[1].vlines(break_frequencies, ymin=min(magnitude), ymax=max(magnitude), colors='C1')
def advectConv(initial, Func_name, width, order): #parameters for run #--------------------------------------------------------------------------- a = -1. # min x b = 1. # max x steps = [step_lax_fried, step_lax_wendroff] names = ["Lax_friedrich","Lax_Wendroff"] L1 = { } Nx = { } for step,name in zip(steps,names): L1[name] = [ ] Nx[name] = [ ] print "Running method:", name for N_points in pylab.logspace(1,order,20): h = (b-a)/N_points # the step size in x x, dx = pylab.linspace(a, b, N_points+1, retstep = True) t_f = 2/A t_i = 0. k = abs(.5*h/A) #actual integration #---------------------------------------------------------------------------- t = t_i U = pylab.array([initial(xi,width) for xi in x]) while t<= t_f: U = step(U,k/dx) t+= k U_anal = [initial(xi,width) for xi in x] L1[name].append(L1_norm(U, [initial(xi,width) for xi in x], dx)) Nx[name].append(int(N_points)) for name in L1: pylab.loglog(Nx[name], L1[name], '-o', label= name) pylab.title("Convergence rate for %s" % Func_name) pylab.xlabel("Number of points") pylab.ylabel("L1_norm") pylab.legend()
def calcSpatScaling(data, idx, nRadii=None): """ calculates the spatial scaling behavior computes the number of points in a neighbourhood of radius r for each point whose index is given in "indices". data must be an array of NxD - format, N: number of observations, D: system dimension returns: [(radius, N), ... ] to estimate dimension from that: D ~ lim(radius -> 0){ d log(N) / d log(radius) } """ nRadii = data.shape[0] / 100 if nRadii is None else nRadii #for idx in indices: sq_dists = sqrt(sum((data - data[idx, :])**2, axis=1)) radii = logspace(-5, log(max(sq_dists)) + .1, nRadii, base=exp(1)) sq_dists.sort() # this is rather slow; a "manual walk-through would be faster -> implement # if required return vstack([(r, len(find(sq_dists < r))) for r in radii])
def zipf_law(df): # Plot of absolute frequency from pylab import arange, argsort, loglog, logspace, log10, text counts = df.total tokens = df.index ranks = arange(1, len(counts)+1) indices = argsort(-counts) frequencies = counts[indices] fig, ax = plt.subplots(figsize=(8,6)) ax.set_ylim(1,10**6) ax.set_xlim(1,10**6) loglog(ranks, frequencies, marker=".") ax.plot([1,frequencies[0]],[frequencies[0],1],color='r') #ax.set_title("Zipf plot for phrases tokens") ax.set_xlabel("Frequency rank of token") ax.set_ylabel("Absolute frequency of token") ax.grid(True) for n in list(logspace(-0.5, log10(len(counts)-2), 15).astype(int)): dummy = text(ranks[n], frequencies[n], " " + tokens[indices[n]], verticalalignment="bottom", horizontalalignment="left") ax.figure.savefig(figOutputPath / '2_zipf_law.png', format='png') print('Exported 2_zipf_law.png')
def calcSpatScaling(data,idx,nRadii = None): """ calculates the spatial scaling behavior computes the number of points in a neighbourhood of radius r for each point whose index is given in "indices". data must be an array of NxD - format, N: number of observations, D: system dimension returns: [(radius, N), ... ] to estimate dimension from that: D ~ lim(radius -> 0){ d log(N) / d log(radius) } """ nRadii = data.shape[0]/100 if nRadii is None else nRadii #for idx in indices: sq_dists = sqrt(sum((data - data[idx,:])**2,axis=1)) radii = logspace(-5,log(max(sq_dists))+.1, nRadii,base=exp(1)) sq_dists.sort() # this is rather slow; a "manual walk-through would be faster -> implement # if required return vstack([(r,len(find(sq_dists<r))) for r in radii])
def EllipticSlope(): rho_list = [0.5] Roell_list = pl.logspace(pl.log10(0.1), pl.log10(50), 20) markers = ["bo-", "gv-", "r>-"] for i, rho in enumerate(rho_list): tf_list = [] te_list = [] for Roell in Roell_list: ell = 1 / Roell te, tf = find_data( ["material.ell", "problem.rho", "problem.hsize"], [ell, rho, 1e-3]) te_list.append(te) tf_list.append(tf) pl.figure(i) pl.loglog(Roell_list, tf_list, markers[i], label=r"$\rho=%g$" % (rho)) ind1 = 8 ind2 = 5 coeff = pl.polyfit(pl.log(Roell_list[ind1:-ind2]), pl.log(tf_list[ind1:-ind2]), 1) poly = pl.poly1d(coeff) fit = pl.exp(poly(pl.log(Roell_list[ind1:-ind2]))) print("The slope = %.2e" % (coeff[0])) pl.loglog(Roell_list[ind1:-ind2], fit, "k-", linewidth=3.0, alpha=0.2) pl.xlabel(r"Relative defect size $a/\ell$") pl.ylabel("$\sigma/\sigma_0$ at fracture") pl.legend(loc="best") pl.xlim([9e-2, 1e2]) pl.grid(True) pl.savefig("elliptic_rho_" + str(rho).replace(".", "x") + ".pdf", bbox_inches='tight')
import pylab import mpmath as mp import scipy from PyPPL import * from Dispersion_ConstTheta import * # Plasma Dispersion function #for theta in [ 0.033, 0.050, 0.133, 0.15, 0.2 ]: for theta in [ 0.10]: Setup = { 'eta' : 4., 'kx' : 0.0, 'v_te' : mp.sqrt(2.), 'rho_te2' : 1., 'tau' : 1., 'theta' : 0. , 'm_ie' : 400., 'lambda_D2' : 0.} ky_list = pylab.logspace(pylab.log10(0.2), pylab.log10(40.), 101) #ky_list = pylab.linspace(20., 60.,101) Setup['theta'] = theta #ky, gamma, err = getGrowth(ky_list, Setup, disp="Gyro", init= 0.02 + 0.045j) #pylab.semilogx(ky, pylab.imag(gamma), 'b-', label='Gyro') #pylab.plot(ky, pylab.imag(gamma), 'b-', label='Gyro') #ky, gamma, err = getGrowth(ky_list, Setup, disp="Gyro1st", init=0.02+0.045j) #pylab.semilogx(ky[:350], pylab.imag(gamma)[:350], 'g-', label='Gyro $\\mathcal{O}{(1)}$') #ky, gamma, err = getGrowth(ky_list, Setup, disp="Fluid", init = 0.02 + 0.045j) #pylab.semilogx(ky, pylab.imag(gamma), 'r-', label='Fluid ') ky, gamma, err = getGrowth(ky_list, Setup, disp="GyroKin", init=-0.01 + 0.01j) #ky, gamma, err = getGrowth(ky_list, Setup, disp="GyroKin", init= 0.02 + 0.045j) pylab.semilogx(ky, pylab.imag(gamma), 'm-', label='Kinetic') #pylab.plot(ky, pylab.imag(gamma), 'm-', label='Kinetic') pylab.legend(ncol=3, loc='best').draw_frame(0)
def plot(self, bins=100, cmap="hot_r", fontsize=10, Nlevels=4, xlabel=None, ylabel=None, norm=None, range=[], contour=True, **kargs): """plots histogram of mean across replicates versus coefficient variation :param int bins: binning for the 2D histogram :param fontsize: fontsize for the labels :param contour: show some contours :param int Nlevels: must be more than 2 .. plot:: :include-source: :width: 50% >>> from msdas import * >>> r = replicates.ReplicatesYeast(get_yeast_raw_data()) >>> r.drop_na_count(54) # to speed up the plot creation >>> r.hist2d_mu_versus_cv() """ X = self.df[self.df.columns[0]].values Y = self.df[self.df.columns[1]].values if len(X) > 10000: print("Computing 2D histogram. Please wait") pylab.clf() if norm == 'log': from matplotlib import colors res = pylab.hist2d(X, Y, bins=bins, cmap=cmap, norm=colors.LogNorm()) else: res = pylab.hist2d(X, Y, bins=bins, cmap=cmap, range=range) pylab.colorbar() if contour: try: bins1 = bins[0] bins2 = bins[1] except: bins1 = bins bins2 = bins X, Y = pylab.meshgrid(res[1][0:bins1], res[2][0:bins2]) if contour: levels = [ round(x) for x in pylab.logspace( 0, pylab.log10(res[0].max().max()), Nlevels) ] pylab.contour(X, Y, res[0].transpose(), levels[2:], color="g") #pylab.clabel(C, fontsize=fontsize, inline=1) if ylabel == None: ylabel = self.df.columns[1] if xlabel == None: xlabel = self.df.columns[0] pylab.xlabel(xlabel, fontsize=fontsize) pylab.ylabel(ylabel, fontsize=fontsize) pylab.grid(True) return res
def plot_color_vs_mass_hist(): galaxies = mk_galaxy_struc() # Definitions for the axes left, width = 0.1, 0.65 bottom, height = 0.1, 0.65 bottom_h = left_h = left+width+0.02 rect_scatter = [left, bottom, width, height] rect_histx = [left, bottom_h, width, 0.2] rect_histy = [left_h, bottom, 0.2, height] # Add the figures # Mass vs color plot I-H f1 = pyl.figure(1,figsize=(8,8)) f1s1 = f1.add_axes(rect_scatter) f1s2 = f1.add_axes(rect_histx) f1s3 = f1.add_axes(rect_histy) # Mass vs color plot J-H f2 = pyl.figure(2,figsize=(8,8)) f2s1 = f2.add_axes(rect_scatter) f2s2 = f2.add_axes(rect_histx) f2s3 = f2.add_axes(rect_histy) #f2s1 = f2.add_subplot(111) # Mass vs color plot Z-H f3 = pyl.figure(3,figsize=(8,8)) f3s1 = f3.add_axes(rect_scatter) f3s2 = f3.add_axes(rect_histx) f3s3 = f3.add_axes(rect_histy) #f3s1 = f3.add_subplot(111) mass1 = [] color1 = [] mass2 = [] color2 = [] mass3 = [] color3 = [] for i in range(len(galaxies)): # Color vs Mass Plots if galaxies[i].ston_I >30.0: if galaxies[i].Mips >=10.0: f1s1.plot(galaxies[i].Mass,galaxies[i].Imag-galaxies[i].Hmag, c='#FFAB19', marker='o', markersize=9) mass1.append(galaxies[i].Mass) # Get the right mass color1.append(galaxies[i].Imag-galaxies[i].Hmag) # Get the color if galaxies[i].ICD_IH > 0.1: f1s1.plot(galaxies[i].Mass,galaxies[i].Imag-galaxies[i].Hmag, c='None', marker='s', markersize=10) else: f1s1.plot(galaxies[i].Mass,galaxies[i].Imag-galaxies[i].Hmag, c='#196DFF', marker='*') elif 20.0 < galaxies[i].ston_I and galaxies[i].ston_I < 30.0 : f1s1.plot(galaxies[i].Mass,galaxies[i].Imag-galaxies[i].Hmag, c='0.8', marker='s', alpha=0.4) else: f1s1.plot(galaxies[i].Mass,galaxies[i].Imag-galaxies[i].Hmag, c='0.8', marker='.', alpha=0.4) if galaxies[i].ston_Z >30.0: if galaxies[i].Mips >=10.0: f2s1.plot(galaxies[i].Mass,galaxies[i].Zmag-galaxies[i].Hmag, c='#FFAB19', marker='o', markersize=9) mass2.append(galaxies[i].Mass) # Get the right mass color2.append(galaxies[i].Zmag-galaxies[i].Hmag) # Get the color if galaxies[i].ICD_ZH > 0.05: f2s1.plot(galaxies[i].Mass,galaxies[i].Zmag-galaxies[i].Hmag, c='None', marker='s', markersize=10) else: f2s1.plot(galaxies[i].Mass,galaxies[i].Zmag-galaxies[i].Hmag, c='#196DFF', marker='*') elif 20.0 < galaxies[i].ston_Z and galaxies[i].ston_Z < 30.0 : f2s1.plot(galaxies[i].Mass,galaxies[i].Zmag-galaxies[i].Hmag, c='0.8', marker='s', alpha=0.4) else: f2s1.plot(galaxies[i].Mass,galaxies[i].Zmag-galaxies[i].Hmag, c='0.8', marker='.', alpha=0.4) if galaxies[i].ston_J >30.0: if galaxies[i].Mips >=10.0: f3s1.plot(galaxies[i].Mass,galaxies[i].Jmag-galaxies[i].Hmag, c='#FFAB19', marker='o', markersize=9) mass3.append(galaxies[i].Mass) # Get the right mass color3.append(galaxies[i].Jmag-galaxies[i].Hmag) # Get the color if galaxies[i].ICD_JH > 0.03: f3s1.plot(galaxies[i].Mass,galaxies[i].Jmag-galaxies[i].Hmag, c='None', marker='s', markersize=10) else: f3s1.plot(galaxies[i].Mass,galaxies[i].Jmag-galaxies[i].Hmag, c='#196DFF', marker='*') elif 20.0 < galaxies[i].ston_J and galaxies[i].ston_J < 30.0 : f3s1.plot(galaxies[i].Mass,galaxies[i].Jmag-galaxies[i].Hmag, c='0.8', marker='s', alpha=0.4) else: f3s1.plot(galaxies[i].Mass,galaxies[i].Jmag-galaxies[i].Hmag, c='0.8', marker='.', alpha=0.4) ############ # FIGURE 1 # ############ pyl.figure(1) f1s1.set_xscale('log') f1s1.set_xlim(3e7,1e12) f1s1.set_ylim(0,4.5) f1s1.set_xlabel(r"$Log_{10}(M_{\odot})$",fontsize=20) f1s1.set_ylabel("$(I-H)_{Observed}$",fontsize=20) f1s1.tick_params(axis='both',pad=7) binsx = pyl.logspace(7, 12) binsy = pyl.linspace(f1s1.get_ylim()[0], f1s1.get_ylim()[1] + 0.25) f1s2.hist(mass1, bins=binsx) f1s2.set_xlim( f1s1.get_xlim() ) f1s2.tick_params(labelbottom='off') f1s2.set_xscale('log') f1s3.hist(color1, bins=binsy, orientation='horizontal') f1s3.set_ylim( f1s1.get_ylim() ) f1s3.tick_params(labelleft='off') pyl.savefig('color_vs_mass_hist_IH.eps') ############ # FIGURE 2 # ############ pyl.figure(2) f2s1.set_xscale('log') f2s1.set_xlim(3e7,1e12) f2s1.set_xlabel(r"$Log_{10}(M_{\odot})$",fontsize=20) f2s1.set_ylabel("$(Z-H)_{Observed}$",fontsize=20) f2s1.tick_params(axis='both',pad=7) binsx = pyl.logspace(7, 12) binsy = pyl.linspace(f2s1.get_ylim()[0], f2s1.get_ylim()[1] + 0.25) f2s2.hist(mass2, bins=binsx) f2s2.set_xlim( f2s1.get_xlim() ) f2s2.tick_params(labelbottom='off') f2s2.set_xscale('log') f2s3.hist(color2, bins=binsy, orientation='horizontal') f2s3.set_ylim( f2s1.get_ylim() ) f2s3.tick_params(labelleft='off') pyl.savefig('color_vs_mass_hist_ZH.eps') ############ # FIGURE 3 # ############ pyl.figure(3) f3s1.set_xscale('log') f3s1.set_xlim(3e7,1e12) f3s1.set_ylim(-0.5,2) f3s1.set_xlabel(r"$Log_{10}(M_{\odot})$",fontsize=20) f3s1.set_ylabel("$(J-H)_{Observed}$",fontsize=20) f3s1.tick_params(axis='both',pad=7) binsx = pyl.logspace(7, 12) binsy = pyl.linspace(f3s1.get_ylim()[0], f3s1.get_ylim()[1] + 0.25) f3s2.hist(mass3, bins=binsx) f3s2.set_xlim( f3s1.get_xlim() ) f3s2.tick_params(labelbottom='off') f3s2.set_xscale('log') f3s3.hist(color3, bins=binsy, orientation='horizontal') f3s3.set_ylim( f3s1.get_ylim() ) f3s3.tick_params(labelleft='off') pyl.savefig('color_vs_mass_hist_JH.eps') pyl.show()
#!/usr/bin/env python import pandas as pd import pylab as pl df = pd.DataFrame.from_csv("surnames.csv", header=1) N = df["count"].sum() deltas_ = df["count"].values[:-1] - df["count"].values[1:] deltas = pl.array([deltas_[0]] + list(pl.amin([deltas_[1:], deltas_[:-1]], axis=0)) + [deltas_[-1]]) dfrac = (deltas + 1e-20) / N def frac_leaked(q): attacked = dfrac * q > (2 * q * df["count"] / N) ** 0.5 N_a = df["count"][attacked].sum() return float(N_a) / N Ns = pl.logspace(0, 15, 100) fracs = pl.array(map(frac_leaked, Ns)) pl.semilogx(Ns, fracs * 100) pl.xlabel("Number of queries") pl.ylabel("% of surnames revealed") pl.yticks(range(0, 110, 10)) pl.grid(True) pl.show()
from pylab import logspace, loglog, log10 from pyhalo import Cosmology from math import pi,sin from scipy.integrate import quad # Parameters Delta_c = 180 M = 1e13 c = 1 C = Cosmology() r_h = ( 3*M / (4*pi*2.78e11*C.om_0) / Delta_c ) ** (1./3.) ks = logspace(-2,2,100) y = 0 * ks for i in range(len(ks)): k = ks[i] core = lambda r: 4*pi*r**2 / ( r*c/r_h * (1+r*c/r_h)**2 ) * sin(k*r) / (k*r) x = quad(core,0,10*r_h) y[i] = x[0] / M y = y / y[0] loglog(ks,y)
def plot_invtransformed_tail(f, vt): from pylab import loglog, show, logspace X = logspace(1, 50, 1000) Y = f(vt.var_change(X)) loglog(X, Y)
#File Handling Errors except: print(f'Unable to Open/Process fitting.dat') sys.exit() def g(t,A = 1.05,B = -0.105): return A*(sp.jn(2,t)) + B*t t = data[:,0] Y = data[:,1:] true_y = g(t) #################################################### #Part3 - Plotting the data obtained sigma = pl.logspace(-1,-3,9) #The Standard Deviations of noise fig = pl.figure(0) pl.title('Plot of Data') pl.plot(t,pl.c_[Y,true_y]) pl.xlabel(r'$t$') pl.legend(list(sigma) + ['true value']) pl.grid(True) #pl.savefig('dataplot.png') pl.show() pl.close(fig) #################################################### #Part4 - Plotting the true value fig = pl.figure(0) pl.title('Plot of True value')
import pylab import mpmath as mp import scipy from Dispersion_ConstTheta import * for m_ie in [ 0. ]: Setup = { 'eta' : 6., 'kx' : 0.0, 'v_te' : 1., 'rho_te2' : 1., 'tau' : 1., 'theta' : 0.01 , 'm_ie' : m_ie, 'lambda_D2' : 0.} ky_list = pylab.logspace(-1, 1.3, 101) disp="Gyro1stKin" if m_ie == 0. : disp ="Gyro1st" ky, gamma, res = getGrowth(ky_list, Setup, disp=disp) pylab.semilogx(ky, pylab.imag(gamma), label='$m_ie=%.3f$' % m_ie) pylab.legend(ncol=1, loc='best').draw_frame(0) pylab.ylim((-0.01,0.1)) #pylab.xlim((0.,2.0)) pylab.xlabel("Poloidal Wavenumber $k_y/\\rho_{te}$") pylab.ylabel("Growthrate $\\gamma_L [\\nu_{te}/L_T]$") pylab.savefig("Dispersion_Nakata.pdf", bbox_inches='tight') pylab.savefig("Dispersion_Nakata.png", bbox_inches='tight')
# In[167]: def perlin_covariance_corr(delta,N=1000000,bound=1): ts = bound*pl.rand(N) tds = ts+delta ps = [p(t) for t in ts] pds = [p(td) for td in tds] #cov = pl.mean([pp*pd for pp,pd in zip(ps,pds)]) cov = pl.mean([(pp-pd)**2 for pp,pd in zip(ps,pds)]) corr = pl.mean([pp*pd for pp,pd in zip(ps,pds)]) return cov, corr # In[157]: deltas = pl.logspace(-8,1,46) # In[168]: cv_stats = [perlin_covariance_corr(d) for d in deltas] # In[169]: zip(deltas,cv_stats) # In[170]: [(d,cov/d) for (d,(cov,corr)) in zip(deltas,cv_stats)]
def smith(smithR=1, chart_type='z', draw_labels=False, border=False, ax=None, ref_imm=1.0, draw_vswr=None): ''' plots the smith chart of a given radius Parameters ----------- smithR : number radius of smith chart chart_type : ['z','y','zy', 'yz'] Contour type. Possible values are * *'z'* : lines of constant impedance * *'y'* : lines of constant admittance * *'zy'* : lines of constant impedance stronger than admittance * *'yz'* : lines of constant admittance stronger than impedance draw_labels : Boolean annotate real and imaginary parts of impedance on the chart (only if smithR=1) border : Boolean draw a rectangular border with axis ticks, around the perimeter of the figure. Not used if draw_labels = True ax : matplotlib.axes object existing axes to draw smith chart on ref_imm : number Reference immittance for center of Smith chart. Only changes labels, if printed. draw_vswr : list of numbers, Boolean or None draw VSWR circles. If True, default values are used. ''' ##TODO: fix this function so it doesnt suck if ax == None: ax1 = plb.gca() else: ax1 = ax # contour holds matplotlib instances of: pathes.Circle, and lines.Line2D, which # are the contours on the smith chart contour = [] # these are hard-coded on purpose,as they should always be present rHeavyList = [0, 1] xHeavyList = [1, -1] #TODO: fix this # these could be dynamically coded in the future, but work good'nuff for now if not draw_labels: rLightList = plb.logspace(3, -5, 9, base=.5) xLightList = plb.hstack([ plb.logspace(2, -5, 8, base=.5), -1 * plb.logspace(2, -5, 8, base=.5) ]) else: rLightList = plb.array([0.2, 0.5, 1.0, 2.0, 5.0]) xLightList = plb.array( [0.2, 0.5, 1.0, 2.0, 5.0, -0.2, -0.5, -1.0, -2.0, -5.0]) # vswr lines if isinstance(draw_vswr, (tuple, list)): vswrVeryLightList = draw_vswr elif draw_vswr is True: # use the default I like vswrVeryLightList = [1.5, 2.0, 3.0, 5.0] else: vswrVeryLightList = [] # cheap way to make a ok-looking smith chart at larger than 1 radii if smithR > 1: rMax = (1. + smithR) / (1. - smithR) rLightList = plb.hstack([plb.linspace(0, rMax, 11), rLightList]) if chart_type.startswith('y'): y_flip_sign = -1 else: y_flip_sign = 1 # draw impedance and/or admittance both_charts = chart_type in ('zy', 'yz') # loops through Verylight, Light and Heavy lists and draws circles using patches # for analysis of this see R.M. Weikles Microwave II notes (from uva) superLightColor = dict(ec='whitesmoke', fc='none') veryLightColor = dict(ec='lightgrey', fc='none') lightColor = dict(ec='grey', fc='none') heavyColor = dict(ec='black', fc='none') # vswr circules verylight for vswr in vswrVeryLightList: radius = (vswr - 1.0) / (vswr + 1.0) contour.append(Circle((0, 0), radius, **veryLightColor)) # impedance/admittance circles for r in rLightList: center = (r / (1. + r) * y_flip_sign, 0) radius = 1. / (1 + r) if both_charts: contour.insert( 0, Circle((-center[0], center[1]), radius, **superLightColor)) contour.append(Circle(center, radius, **lightColor)) for x in xLightList: center = (1 * y_flip_sign, 1. / x) radius = 1. / x if both_charts: contour.insert( 0, Circle((-center[0], center[1]), radius, **superLightColor)) contour.append(Circle(center, radius, **lightColor)) for r in rHeavyList: center = (r / (1. + r) * y_flip_sign, 0) radius = 1. / (1 + r) contour.append(Circle(center, radius, **heavyColor)) for x in xHeavyList: center = (1 * y_flip_sign, 1. / x) radius = 1. / x contour.append(Circle(center, radius, **heavyColor)) # clipping circle clipc = Circle([0, 0], smithR, ec='k', fc='None', visible=True) ax1.add_patch(clipc) #draw x and y axis ax1.axhline(0, color='k', lw=.1, clip_path=clipc) ax1.axvline(1 * y_flip_sign, color='k', clip_path=clipc) ax1.grid(0) # Set axis limits by plotting white points so zooming works properly ax1.plot(smithR * npy.array([-1.1, 1.1]), smithR * npy.array([-1.1, 1.1]), 'w.', markersize=0) ax1.axis('image') # Combination of 'equal' and 'tight' if not border: ax1.yaxis.set_ticks([]) ax1.xaxis.set_ticks([]) for loc, spine in ax1.spines.items(): spine.set_color('none') if draw_labels: #Clear axis ax1.yaxis.set_ticks([]) ax1.xaxis.set_ticks([]) for loc, spine in ax1.spines.items(): spine.set_color('none') # Make annotations only if the radius is 1 if smithR is 1: #Make room for annotation ax1.plot(npy.array([-1.25, 1.25]), npy.array([-1.1, 1.1]), 'w.', markersize=0) ax1.axis('image') #Annotate real part for value in rLightList: # Set radius of real part's label; offset slightly left (Z # chart, y_flip_sign == 1) or right (Y chart, y_flip_sign == -1) # so label doesn't overlap chart's circles rho = (value - 1) / (value + 1) - y_flip_sign * 0.01 if y_flip_sign is 1: halignstyle = "right" else: halignstyle = "left" ax1.annotate(str(value * ref_imm), xy=(rho * smithR, 0.01), xytext=(rho * smithR, 0.01), ha=halignstyle, va="baseline") #Annotate imaginary part radialScaleFactor = 1.01 # Scale radius of label position by this # factor. Making it >1 places the label # outside the Smith chart's circle for value in xLightList: #Transforms from complex to cartesian S = (1j * value - 1) / (1j * value + 1) S *= smithR * radialScaleFactor rhox = S.real rhoy = S.imag * y_flip_sign # Choose alignment anchor point based on label's value if ((value == 1.0) or (value == -1.0)): halignstyle = "center" elif (rhox < 0.0): halignstyle = "right" else: halignstyle = "left" if (rhoy < 0): valignstyle = "top" else: valignstyle = "bottom" #Annotate value ax1.annotate(str(value * ref_imm) + 'j', xy=(rhox, rhoy), xytext=(rhox, rhoy), ha=halignstyle, va=valignstyle) #Annotate 0 and inf ax1.annotate('0.0', xy=(-1.02, 0), xytext=(-1.02, 0), ha="right", va="center") ax1.annotate('$\infty$', xy=(radialScaleFactor, 0), xytext=(radialScaleFactor, 0), ha="left", va="center") # annotate vswr circles for vswr in vswrVeryLightList: rhoy = (vswr - 1.0) / (vswr + 1.0) ax1.annotate(str(vswr), xy=(0, rhoy * smithR), xytext=(0, rhoy * smithR), ha="center", va="bottom", color='grey', size='smaller') # loop though contours and draw them on the given axes for currentContour in contour: cc = ax1.add_patch(currentContour) cc.set_clip_path(clipc)
def plot(self, bins=100, cmap="hot_r", fontsize=10, Nlevels=4, xlabel=None, ylabel=None, norm=None, range=None, normed=False, colorbar=True, contour=True, grid=True, **kargs): """plots histogram of mean across replicates versus coefficient variation :param int bins: binning for the 2D histogram (either a float or list of 2 binning values). :param cmap: a valid colormap (defaults to hot_r) :param fontsize: fontsize for the labels :param int Nlevels: must be more than 2 :param str xlabel: set the xlabel (overwrites content of the dataframe) :param str ylabel: set the ylabel (overwrites content of the dataframe) :param norm: set to 'log' to show the log10 of the values. :param normed: normalise the data :param range: as in pylab.Hist2D : a 2x2 shape [[-3,3],[-4,4]] :param contour: show some contours (default to True) :param bool grid: Show unerlying grid (defaults to True) If the input is a dataframe, the xlabel and ylabel will be populated with the column names of the dataframe. """ X = self.df[self.df.columns[0]].values Y = self.df[self.df.columns[1]].values if len(X) > 10000: print("Computing 2D histogram. Please wait") pylab.clf() if norm == 'log': from matplotlib import colors res = pylab.hist2d(X, Y, bins=bins, normed=normed, cmap=cmap, norm=colors.LogNorm()) else: res = pylab.hist2d(X, Y, bins=bins, cmap=cmap, normed=normed, range=range) if colorbar is True: pylab.colorbar() if contour: try: bins1 = bins[0] bins2 = bins[1] except: bins1 = bins bins2 = bins X, Y = pylab.meshgrid(res[1][0:bins1], res[2][0:bins2]) if contour: if res[0].max().max() < 10 and norm == 'log': pylab.contour(X, Y, res[0].transpose(), color="g") else: levels = [round(x) for x in pylab.logspace(0, pylab.log10(res[0].max().max()), Nlevels)] pylab.contour(X, Y, res[0].transpose(), levels[2:], color="g") #pylab.clabel(C, fontsize=fontsize, inline=1) if ylabel is None: ylabel = self.df.columns[1] if xlabel is None: xlabel = self.df.columns[0] pylab.xlabel(xlabel, fontsize=fontsize) pylab.ylabel(ylabel, fontsize=fontsize) if grid is True: pylab.grid(True) return res
def tf_idf(self): """ Normalize the frequency of stock name in the articles""" print "Initiating the word frequency test..." list_of_prepositions = [u'above', u'about', u'across', u'against',u'The', u'is',u'an', u'along', u'among', u'around', u'at', u'before', u'behind', u'below', u'beneath', u'beside', u'between', u'beyond', u'by', u'during', u'except', u'for', u'from',u'in', u'inside', u'into',u'like',u'near',u'of', u'off', u'on',u'since',u'to', u'toward', u'through',u'under', u'until', u'up', u'upon', u'with', u'within', u'the', u'a', u'and', u'for'] try: #Zipf Distribution to assess threshold paragraphs = " ".join(self.targeted_paragraphs) words = paragraphs.split() frequency = Counter(x for x in words if x not in list_of_prepositions) counts = array(frequency.values()) tokens = frequency.keys() ranks = arange(1, len(counts)+1) indices = argsort(-counts) frequencies = counts[indices] loglog(ranks, frequencies, marker=".") title("Zipf plot for Combined Article Paragraphs") xlabel("Frequency Rank of Token") ylabel("Absolute Frequency of Token") grid(True) for n in list(logspace(-0.5, log10(len(counts)-1), 20).astype(int)): dummy = text(ranks[n], frequencies[n], " " + tokens[indices[n]], verticalalignment="bottom", horizontalalignment="left") #plt.plot(np.unique(ranks), np.poly1d(np.polyfit(ranks, frequencies, 10))(np.unique(ranks))) slope=np.polyfit(ranks, frequencies, 0) for value in slope: print value zipf_threshold = value ## NEED TO ADD- FITTED LINE. Due to an error in the value of threshold its currently not in-use while paragraph extraction.## except Exception as e: print "Error occurred during Zipf Distribution: " + str(e) #Inverse-document Frequency document_size = self.result_scan_web["article_count"] document_success = len(self.article_url) try: idf = math.log(float(document_size)/float(document_success)) except Exception as e: print "No Successful Articles in this webpage: " + str(e) #Term Frequency list_total_count = [] for paragraph in self.targeted_paragraphs: words = paragraph.split() word_frequency = Counter(x for x in words if x not in list_of_prepositions) stock_frequency = word_frequency[self.stock_name] list_total_count.append(stock_frequency) total_count = sum(list_total_count) print "TOTAL WORD COUNT:" , total_count print "COUNT BEFORE:" print "urls = " , len(self.article_url) list_fail_values = [] for paragraph in self.targeted_paragraphs: words = paragraph.split() word_frequency = Counter(x for x in words if x not in list_of_prepositions) stock_frequency = word_frequency[self.stock_name] ticker_symbol_frequency = word_frequency[self.stock_id] print "TERM FREQUENCY: ", stock_frequency print "DIVISION: " , (float(stock_frequency)/float(total_count)) try: tf_idf_weight = (float(stock_frequency)/float(total_count)) * float(idf) except Exception as e: print "Error ocurred during division. total_count is zero, meaning no successful articles: " + str(e) print "TF-IDF-WEIGHT = " , tf_idf_weight if tf_idf_weight <= 0.30: # Gives the articles that lie within the 30th percentile of success. index = self.targeted_paragraphs.index(paragraph) self.targeted_paragraphs.remove(paragraph) url_value = self.article_url[index] title_value = self.article_title[index] fail_dict = {'url': url_value , 'title' : title_value} list_fail_values.append(fail_dict) print "IRRELEVANT ARTICLE DETECTED..." print "DELETING " , url_value del self.article_url[index] del self.article_title[index] else: pass print "COUNT AFTER: " print "urls = " , len(self.article_url) print "FAILED ARTICLES: " print "# " , len(list_fail_values) print "articles:" , list_fail_values #titles_in_fail = {d['title'] for d in list_fail_values if 'title' in d} #self.json_results[:] = [d for d in self.json_results if d.get('title') not in titles_in_fail] self.json_results[:] = [i for i in self.json_results if i not in list_fail_values] self.results_tone_analyzer["successful_articles"] = self.json_results print " ----------------------------" print "Number of Successful Articles = " , len(self.article_url) print "SUCCESSFUL URLs: " , for article in self.article_url: print article print " ----------------------------"
data = loadtxt('w_spectra.dat') w = transpose(data[:,1:]) zLevels = range(1,51,1) dz = 8.0 del data if __name__=="__main__": import matplotlib.pyplot as p with open('wSpectrumPeakWavenumber','w') as wPeakFile: wPeakFile.write('iz wSpectrumPeakWavenumber'+'\n') for z in range(size(zLevels)): wPeakFile.write(str(z+1)+' '+str(w[z,:].argmax())+'\n') print logspace(-7,3,11) #Make spectra plots at each level for z in range(size(zLevels)): p.figure() p.loglog(wavenumber,u[z,:],label='U') p.loglog(wavenumber,v[z,:],label='V') p.loglog(wavenumber,w[z,:],label='W') km5by3 = 200.0*wavenumber**(-5.0/3.0) p.loglog(wavenumber, km5by3,'k--',label='km5by3') p.loglog(w[z,:].argmax() * ones(11), logspace(-7,3,11),'k') # p.xlim(0,0.01) p.title('z = '+str((z+0.5)*dz)+'m') p.xlabel('k (in 1/m') p.ylabel('Amplitude') p.savefig('z'+str(z)+'_Spectra.png')
def _parseNewInput(self,config): r'''Function reading the input file and setting the :self.Parameters: acordingly. ''' self.Parameters['oldInputFormat'] = False self.Parameters['saveDir'] = config.get('Main','save dir') self.Parameters['dataDir'] = config.get('Main','data dir') self.Parameters['flatFieldFile'] = config.get('Main','flat field') try: self.Parameters['maskFile'] = config.get('Main','mask') except: print 'Mask not set in the config file' self.Parameters['defaultMaskFile'] = config.get('Main','default mask') self.Parameters['q1'] = config.getfloat('Main','q1') self.Parameters['q2'] = config.getfloat('Main','q2') self.Parameters['qs'] = config.getfloat('Main','qs') self.Parameters['dq'] = config.getfloat('Main','dq') self.Parameters['outPrefix'] = config.get('Main','sample name') self.Parameters['wavelength'] = config.getfloat('Main','wavelength') self.Parameters['cenx'] = config.getfloat('Main','cenx') self.Parameters['ceny'] = config.getfloat('Main','ceny') self.Parameters['pixSize'] = config.getfloat('Main','pix') self.Parameters['sdDist'] = config.getfloat('Main','sddist') if config.has_option('Main','mode'): self.Parameters['mode'] = config.get('Main','mode') else: self.Parameters['mode'] = 'XSVS' # Assuming default XSVS data mode if self.Parameters['mode'] == 'XSVS': secList = config.sections() secList.remove('Main') exposureList = numpy.sort(secList) self.Parameters['exposureList'] = exposureList for i in xrange(len(exposureList)): exposure = exposureList[i] currExpParams = {} currExpParams['dataSuf'] = config.get(exposure,'data suffix') currExpParams['dataPref'] = config.get(exposure,'data prefix') currExpParams['n1'] = config.getint(exposure,'first data file') currExpParams['n2'] = config.getint(exposure,'last data file') currExpParams['expTime'] = config.getfloat(exposure,'exp time') self.Parameters['exposureParams'][exposure] = currExpParams elif self.Parameters['mode'] == 'XPCS': expParams = {} self.Parameters['exposureList'] = ['Exp_bins'] expParams['dataSuf'] = config.get('Exp_bins','data suffix') expParams['dataPref'] = config.get('Exp_bins','data prefix') expParams['n1'] = config.getint('Exp_bins','first data file') expParams['n2'] = config.getint('Exp_bins','last data file') expParams['expTime'] = config.getfloat('Exp_bins','exp time') expParams['binStart'] = config.getfloat('Exp_bins','bin start') expParams['binStop'] = config.getfloat('Exp_bins','bin stop') expParams['binStep'] = config.getint('Exp_bins','bin step') self.Parameters['exposureParams']['Exp_bins'] = expParams # Generate different exposures by binning frames #fileBins = range(expParams['binStart'], # expParams['binStop'],expParams['binStep']) fileBins = [int(x) for x in pylab.logspace(expParams['binStart'], expParams['binStop'], expParams['binStep'])] exposureList = range(len(fileBins)) for ii in xrange(len(fileBins)): exposureLabel = 'Exp_%d' % ii exposureList[ii] = exposureLabel currExpParams = {} currExpParams['dataSuf'] = expParams['dataSuf'] currExpParams['dataPref'] = expParams['dataPref'] currExpParams['n1'] = expParams['n1'] currExpParams['n2'] = expParams['n2'] currExpParams['expTime'] = expParams['expTime'] * fileBins[ii] currExpParams['img_to_bin'] = fileBins[ii] self.Parameters['exposureParams'][exposureLabel] = currExpParams self.Parameters['exposureList'] = exposureList
def smith(smithR=1, chart_type = 'z',ax=None): ''' plots the smith chart of a given radius Parameters ----------- smithR : number radius of smith chart chart_type : ['z','y'] Contour type. Possible values are * *'z'* : lines of constant impedance * *'y'* : lines of constant admittance ax : matplotlib.axes object existing axes to draw smith chart on ''' ##TODO: fix this function so it doesnt suck if ax == None: ax1 = plb.gca() else: ax1 = ax # contour holds matplotlib instances of: pathes.Circle, and lines.Line2D, which # are the contours on the smith chart contour = [] # these are hard-coded on purpose,as they should always be present rHeavyList = [0,1] xHeavyList = [1,-1] #TODO: fix this # these could be dynamically coded in the future, but work good'nuff for now rLightList = plb.logspace(3,-5,9,base=.5) xLightList = plb.hstack([plb.logspace(2,-5,8,base=.5), -1*plb.logspace(2,-5,8,base=.5)]) # cheap way to make a ok-looking smith chart at larger than 1 radii if smithR > 1: rMax = (1.+smithR)/(1.-smithR) rLightList = plb.hstack([ plb.linspace(0,rMax,11) , rLightList ]) if chart_type is 'y': y_flip_sign = -1 else: y_flip_sign = 1 # loops through Light and Heavy lists and draws circles using patches # for analysis of this see R.M. Weikles Microwave II notes (from uva) for r in rLightList: center = (r/(1.+r)*y_flip_sign,0 ) radius = 1./(1+r) contour.append( Circle( center, radius, ec='grey',fc = 'none')) for x in xLightList: center = (1*y_flip_sign,1./x) radius = 1./x contour.append( Circle( center, radius, ec='grey',fc = 'none')) for r in rHeavyList: center = (r/(1.+r)*y_flip_sign,0 ) radius = 1./(1+r) contour.append( Circle( center, radius, ec= 'black', fc = 'none')) for x in xHeavyList: center = (1*y_flip_sign,1./x) radius = 1./x contour.append( Circle( center, radius, ec='black',fc = 'none')) # clipping circle clipc = Circle( [0,0], smithR, ec='k',fc='None',visible=True) ax1.add_patch( clipc) #draw x and y axis ax1.axhline(0, color='k', lw=.1, clip_path=clipc) ax1.axvline(1*y_flip_sign, color='k', clip_path=clipc) ax1.grid(0) #set axis limits ax1.axis('equal') ax1.axis(smithR*npy.array([-1., 1., -1., 1.])) # loop though contours and draw them on the given axes for currentContour in contour: cc=ax1.add_patch(currentContour) cc.set_clip_path(clipc)
# script to generate data files for the least squares assignment from pylab import linspace, meshgrid, logspace, dot, plot, xlabel, ylabel, ones, randn, diag, title, grid, savetxt, show, c_ import scipy.special as sp N = 101 # no of data points k = 9 # no of sets of data with varying noise # generate the data points and add noise t = linspace(0, 10, N) # t vector y = 1.05 * sp.jv(2, t) - 0.105 * t # f(t) vector Y = meshgrid(y, ones(k), indexing="ij")[0] # make k copies scl = logspace(-1, -3, k) # noise stdev n = dot(randn(N, k), diag(scl)) # generate k vectors yy = Y + n # add noise to signal # shadow plot plot(t, yy) xlabel("t", size=20) ylabel("f(t)+n", size=20) title("Plot of the data to be fitted") grid(True) savetxt("fitting.dat", c_[t, yy]) # write out matrix to file show()
pylab.plot(Vo[0],Vi,label=r'$V_{in}$') display(1,Vo[0],Vo[1],r't$\rightarrow$',r'$V\rightarrow$') def highpass(R1,R3,C1,C2,G,Vi): ''' High pass filter ''' s=symbols('s') A=Matrix([[0,0,1,-1/G],[-1/(1+1/(s*R3*C2)),1,0,0],[0,-G,G,1],[-s*C1-s*C2-1/R1,s*C2,0,1/R1]]) b=Matrix([0,0,0,-Vi*s*C1]) V = A.inv()*b return (A,b,V) # Magnitude response of the high pass filter A,b,V = highpass(10000,10000,1e-9,1e-9,1.586,1) Vo = V[3] H = sympy_to_lti(Vo) w=pylab.logspace(0,8,801) ss=1j*w hf=lambdify(s,Vo,'numpy') v=hf(ss) pylab.loglog(w,abs(v),lw=2) pylab.xlabel(r'$w\rightarrow$') pylab.ylabel(r'$|H(jw)|\rightarrow$') pylab.grid(True) pylab.show() # response for damped sinusoids t = np.linspace(0,10,1000) Vi = np.multiply(np.multiply(np.exp(-0.5*t),np.sin(2*np.pi*t)),np.heaviside(t,0.5)) Vo = sp.lsim(H,Vi,T=t) pylab.figure(2) pylab.plot(Vo[0],Vi,label=r'$V_{in}$')
return sp.lti(nm, dm) #--------------- impulse response s = symbols("s") A, b, V = lowpass(1e4, 1e4, 1e-9, 1e-9, 1.586, 1000, 1) Vo = V[3].evalf() H1 = get_lti(Vo) x, t = sp.impulse(H1, None, npm.linspace(0, 10**-3, 10000)) p.plot(x, t) p.title("time domain impulse response") p.xlabel("time") p.ylabel("h(t)") p.grid(True) #p.show() w = p.logspace(0, 8, 801) ss = 1j * w hf = lambdify(s, Vo, 'numpy') v = hf(ss) p.loglog(w, abs(v), lw=2) p.xlabel("frequency") p.ylabel("H(jw)") p.grid(True) p.title("impulse response in frequency domain") #p.show() #------------------step response A, b, V = lowpass(1e4, 1e4, 1e-9, 1e-9, 1.586, 1000, 1 / s) Vo = V[3] pprint(Vo) X1 = get_lti(Vo) t, x = sp.impulse(X1, None, npm.linspace(0, 10**-3, 10000))
def Circular(): fig = pl.figure() ax = fig.add_subplot(111) ax.set_xscale("log") ax.set_yscale("log") ax.set_xlim([9e-2, 1e2]) # Elastic limit Roell_list = pl.logspace(pl.log10(0.1), pl.log10(50), 20) ax.plot([Roell_list[0], Roell_list[-1]], [1 / 3, 1 / 3], "k", linewidth=3.0, alpha=0.2) # Numerical results tf_list = [] te_list = [] for Roell in Roell_list: ell = 1 / Roell te, tf = find_data(["material.ell", "problem.rho", "problem.hsize"], [ell, 1, 1e-3]) te_list.append(te) tf_list.append(tf) ax.plot(Roell_list, tf_list, "bo-") # label="Num." ind = int(len(Roell_list) / 2.5) coeff = pl.polyfit(pl.log(Roell_list[ind:-ind]), pl.log(tf_list[ind:-ind]), 1) poly = pl.poly1d(coeff) fit = pl.exp(poly(pl.log(Roell_list[ind:-ind]))) print("The slope = %.2e" % (coeff[0])) pl.loglog(Roell_list[ind:-ind], fit, "k-", linewidth=3.0, alpha=0.2) # Experimental results E = 3e3 sigc = 72 Gc = 290e-3 ell = 3 / 8 * Gc * E / sigc**2 print ell ell = 26e-3 data = pl.loadtxt("literature/exp.csv", delimiter=",") Roell_exp = data[:, 0] / (2 * ell) Roell_exp[0] = Roell_list[0] sig_center = (pl.amin(data[:, 1:], 1) + pl.amax(data[:, 1:], 1)) / 2 err1 = -(pl.amin(data[:, 1:], 1) - sig_center) / sigc err2 = (pl.amax(data[:, 1:], 1) - sig_center) / sigc pl.errorbar(Roell_exp, sig_center / sigc, yerr=[err1, err2], label="Exp.", fmt="g.") # Numerical results from C. Kuhn # data = loadtxt("literature/Kuhn.csv", delimiter=",") # # ell = 0.00885 # Roell_Kuhn = data[:, 0]/ell # ax.plot(Roell_Kuhn, data[:, 1], "r>-", label="Kuhn") pl.ylim([1.0 / 4.0, 1.1]) pl.xlabel("Relative hole size $R/\ell$") pl.ylabel("$\sigma/\sigma_0$ at fracture") pl.legend(loc="best") pl.savefig("circular_tf.pdf", bbox_inches='tight')
import pylab as pyl import os import sys curdir = os.getcwd() data_dict = {} #dictionary of files n_range_LU = pyl.logspace(1, 3, num=3) n_range_tridiag = pyl.logspace(1, 4, num=4) for n in n_range_tridiag: #loop through different n's with open(curdir + "/data/dderiv_u_c++_n%d_tridiag.dat" % (int(n)), 'r') as infile: full_file = infile.read() #read entire file into text lines = full_file.split('\n') #separate by EOL-characters lines = lines[:-1] #remove last line (empty line) keys = lines.pop(0).split(', ') #use top line as keys for dictionary dict_of_content = {} for i, key in zip(range(len(keys)), keys): #loop over keys, create approp. arrays dict_of_content[key] = [] #empty list for j in range(len( lines)): #loop though the remaining lines of the data-set line = lines[j].split(', ') #split the line into string-lists word = line[ i] # append the correct value to the correct list with the correct key try: word = float(word) #check if value can be float except ValueError: #word cannot be turned to number print word sys.exit(
def plot(self, bins=100, cmap="hot_r", fontsize=10, Nlevels=4, xlabel=None, ylabel=None, norm=None, range=None, contour=True, **kargs): """plots histogram of mean across replicates versus coefficient variation :param int bins: binning for the 2D histogram :param fontsize: fontsize for the labels :param contour: show some contours :param int Nlevels: must be more than 2 :param range: as in pylab.hist2d : a 2x2 shape [[-3,3],[-4,4]] .. plot:: :include-source: :width: 50% >>> from msdas import * >>> r = replicates.ReplicatesYeast(get_yeast_raw_data()) >>> r.drop_na_count(54) # to speed up the plot creation >>> r.hist2d_mu_versus_cv() """ X = self.df[self.df.columns[0]].values Y = self.df[self.df.columns[1]].values if len(X) > 10000: print("Computing 2D histogram. Please wait") pylab.clf() if norm == 'log': from matplotlib import colors res = pylab.hist2d(X, Y, bins=bins, cmap=cmap, norm=colors.LogNorm()) else: res = pylab.hist2d(X, Y, bins=bins, cmap=cmap, range=range) pylab.colorbar() if contour: try: bins1 = bins[0] bins2 = bins[1] except: bins1 = bins bins2 = bins X, Y = pylab.meshgrid(res[1][0:bins1], res[2][0:bins2]) if contour: levels = [round(x) for x in pylab.logspace(0, pylab.log10(res[0].max().max()),Nlevels)] pylab.contour(X, Y, res[0].transpose(), levels[2:], color="g") #pylab.clabel(C, fontsize=fontsize, inline=1) if ylabel == None: ylabel = self.df.columns[1] if xlabel == None: xlabel = self.df.columns[0] pylab.xlabel(xlabel, fontsize=fontsize) pylab.ylabel(ylabel, fontsize=fontsize) pylab.grid(True) return res
def lowpass(R1, R2, C1, C2, G, Vi): A = Matrix([[0, 0, 1, -1 / G], [(-1) / (1 + s * R2 * C2), 1, 0, 0], [0, -G, G, 1], [((-1) / (R1)) - (1 / R2) - s * C1, 1 / R2, 0, s * C1]]) b = Matrix([0, 0, 0, Vi / R1]) V = A.inv() * b return (A, b, V) #Obtaining output voltage, H(jw) graph for the low pass filter and plotting A, b, V = lowpass(10000, 10000, 1e-9, 1e-9, 1.586, 1) Vo = V[3] w = py.logspace(0, 8, 801) ss = 1j * w hf = lambdify(s, Vo, 'numpy') v = hf(ss) plt.figure(0) py.loglog(w, abs(v), lw=2) py.title( 'Bode plot of the step response of the output voltage \n for the low pass filter using matrices' ) py.xlabel('frequency (omega)') py.ylabel('H') py.grid(True) py.show() #Getting impulse response of the low pass filter
V = A.inv() * b return (A, b, V) def highpass(R1, R3, C1, C2, G, Vi): A = Matrix([[1, -G, 0, 0], [-1, -G, G, 0], [0, 0, s * C2 + (1 / R3), -C2 * s], [-1 / R1, 0, -C2 * s, s * (C1 + C2) + 1 / R1]]) b = Matrix([0, 0, 0, s * C1 * Vi]) V = A.inv() * b return (A, b, V) A, b, V = lowpass(10000, 10000, 1e-11, 1e-11, 1.586, 1) Vo = V[3] ww = p.logspace(0, 8, 801) ss = 1j * ww hf = lambdify(s, Vo, 'numpy') v = hf(ss) # Transfer Function Of Lowpass Filter p.figure(0) p.title("Transfer Function Of Lowpass Filter") p.loglog(ww, abs(v), lw=2) # Step Response of Lowpass Filter p.figure(1) p.title("Step Response of Lowpass Filter") Y = sympy_to_lti(Vo) t1 = p.linspace(0, 0.05, 1000) t, x = sp.step(Y, None, t1) p.plot(x, t) # Output of Lowpass Filter
# Script To Generate Data Files For The Least Squares Assignment from pylab import c_, diag, dot, grid, linspace, logspace, meshgrid, ones, plot, randn, savetxt, show, title, xlabel, ylabel import scipy.special as sp N = 101 # Number Of Data Points k = 9 # Number Of Sets Of Data With Varying Noise # Generating The Data Points And Adding Noise t = linspace(0, 10, N) # Vector t f = 1.05 * sp.jv(2, t) - 0.105 * t # Vector f(t) func = meshgrid(f, ones(k), indexing='ij')[0] # Generating Signal scl = logspace(-1, -3, k) # Noise noise = dot(randn(N, k), diag(scl)) # Generating k Vectors y = func + noise # Adding Noise To The Signal # Shadow Plot plot(t, y) # Ploting Time And Signal With Noise xlabel(r'$t$', size=20) # X-axis -> Time ylabel(r'$f(t)+n$', size=20) # Y-axis -> Signal With Noise title(r'Plot Of The Data To Be Fitted') # Title grid(True) # Show Grid # Write Out The Matrix Into A File (fitting.dat) savetxt("fitting.dat", c_[t, y]) show()
#!/usr/bin/env python import pandas as pd import pylab as pl df = pd.read_csv("surnames.csv", header=1) N = df["count"].sum() deltas_ = df['count'].values[:-1] - df['count'].values[1:] deltas = pl.array([deltas_[0]] + list(pl.amin([deltas_[1:], deltas_[:-1]], axis=0)) + [deltas_[-1]]) dfrac = (deltas + 1e-20) / N def frac_leaked(q): attacked = dfrac * q > (2 * q * df['count'] / N)**0.5 N_a = df['count'][attacked].sum() return float(N_a) / N Ns = pl.logspace(0, 15, 100) fracs = pl.array(map(frac_leaked, Ns)) pl.semilogx(Ns, fracs * 100) pl.xlabel("Number of queries") pl.ylabel("% of surnames revealed") pl.yticks(range(0, 110, 10)) pl.grid(True) pl.show()
def plot_fit(directory, file_, title_, units, f, par, out, fig, residuals, xlimp, XYfun, Xscale, Yscale, Xlab, Ylab, X, Y, dX, dY): """ Parameters ---------- Returns ------- """ gs = gridspec.GridSpec(4, 1) gne = figure(fig + "_1") if (fig == file_): clf() if residuals == True: ax1 = gne.add_subplot(gs[:-1, :]) setp(ax1.get_xticklabels(), visible=False) #subplot(211) title(title_) if Xscale == "log": xscale("log") if Yscale == "log": yscale("log") errorbar(X, Y, dY, dX, fmt=",", ecolor="black", capsize=0.5) if residuals == False: xlabel(Xlab) ylabel(Ylab) xlima = array(xlimp) / 100 if out == True: X_ol, Y_ol, dX_ol, dY_ol, smin, smax = _outlier_( directory, file_, units, X, XYfun) else: smin = min(X) smax = max(X) if Xscale == "log": l = logspace(log10(smin) * xlima[0], log10(smax * xlima[1]), 1000) else: l = linspace(smin * xlima[0], smax * xlima[1], 1000) grid(b=True) plot(l, f(l, *par), "red") if out == True: outlier = errorbar(X_ol, Y_ol, dY_ol, dX_ol, fmt="g^", ecolor="black", capsize=0.5) legend([outlier], ['outlier'], loc="best") if residuals == True: # if out==True: # these commented lines are useless # cause the flag "out" is already passed to "_residuals" as an argument _residuals(fig, gne, gs, ax1, f, par, out, X, dX, Xlab, Xscale, Y, dY, X_ol, Y_ol, dY_ol) # _residuals(fig, gne, gs, ax1, f, par, out, X, dX, Xlab, Xscale, Y, dY) savefig(directory + "grafici/fit_" + fig + ".pdf") savefig(directory + "grafici/fit_" + fig + ".png")
def Elliptic(): rho_list = pl.logspace(-1, 0, 2) Roell_list = pl.logspace(pl.log10(0.1), pl.log10(50), 20) markers = ["bo-", "gv-", "r>-"] # Elastic limit pl.plot([Roell_list[0], Roell_list[-1]], [1 / 3, 1 / 3], "k", linewidth=3.0, alpha=0.2) for i, rho in enumerate(rho_list): tf_list = [] te_list = [] for Roell in Roell_list: ell = 1 / Roell te, tf = find_data( ["material.ell", "problem.rho", "problem.hsize"], [ell, rho, 1e-3]) te_list.append(te) tf_list.append(tf) pl.savetxt("Rolist%s.txt" % i, Roell_list) pl.savetxt("tf_list%s.txt" % i, tf_list) pl.savetxt("te_list%s.txt" % i, te_list) pl.figure(1) pl.loglog(Roell_list, tf_list, markers[i], label=r"$\rho=%g$" % (rho)) pl.savefig("elliptic_tf_%s.pdf" % i) pl.figure(2) pl.loglog(Roell_list, te_list, markers[i], label=r"$\rho=%g$" % (rho)) pl.savefig("elliptic_te_%s.pdf" % i) if near(rho, 0.1): pl.figure(1) ind = 12 coeff = pl.polyfit(pl.log(Roell_list[ind:]), pl.log(tf_list[ind:]), 1) poly = pl.poly1d(coeff) fit = pl.exp(poly(pl.log(Roell_list[ind:]))) print("The slope = %.2e" % (coeff[0])) pl.loglog(Roell_list[ind:], fit, "k-", linewidth=3.0, alpha=0.2) pl.figure(1) pl.xlabel(r"Relative defect size $a/\ell$") pl.ylabel("$\sigma/\sigma_0$ at fracture") pl.legend(loc="best") pl.xlim([9e-2, 1e2]) pl.grid(True) pl.savefig("elliptic_tf.pdf") pl.figure(2) pl.xlabel(r"Relative defect size $a/\ell$") pl.ylabel("$\sigma/\sigma_0$ at loss of elasticity") pl.legend(loc="best") pl.xlim([9e-2, 1e2]) pl.grid(True) pl.savefig("elliptic_te.pdf") pl.figure(3) rho_list = pl.linspace(0.1, 1, 10) te_list = [] for i, rho in enumerate(rho_list): te, tf = find_data(["material.ell", "problem.rho", "problem.hsize"], [1.0, rho, 1e-3]) te_list.append(te) pl.plot(rho_list, te_list, "o", label="Num.") pl.savetxt("rho_list.txt", rho_list) pl.savetxt("rho_te_list.txt", te_list) rho_list = pl.linspace(0.1, 1, 1000) pl.plot(rho_list, rho_list / (rho_list + 2), "k", label="Theo.", linewidth=3.0, alpha=0.2) pl.xlabel(r"Ellipticity $\rho$") pl.ylabel("$\sigma/\sigma_0$ at loss of elasticity") pl.legend(loc="best") pl.grid(True) pl.savefig("elliptic_te_rho.pdf", bbox_inches='tight')
print("b = {0} +/- {1}".format( pyl.mean(samples[:, 1]), pyl.std(samples[:, 1]))) print("s = {0} +/- {1}".format( pyl.mean(samples[:, 2]), pyl.std(samples[:, 2]))) xl = pyl.linspace(0.8, 2.4) # plot crediable region m, b = samples.T[:2] yfit = m[:, None] * xl + b[:, None] # This creates individual points mu = yfit.mean(0) sig = yfit.std(0) # 2sigma confidence pyl.fill_between(xl, mu - sig, mu + sig, color='lightgray', zorder=0) pyl.plot(xl, mu, '-k', label='Fit', zorder=0) # add the Rykoff2012 relation x = pyl.logspace(0.8, 2.4) lny = 1.48 + 1.06 * pyl.log(x / 60.) y = pyl.exp(lny) * 1e14 / 0.7 ax.plot( pyl.log10(x), pyl.log10(y), ls=':', c='k', zorder=0, label='Rykoff+2012') # add the Farahi2016 relation lny = 0.44 + 1.31 * pyl.log(x / 30.) y = pyl.exp(lny) * 1e14 ax.plot( pyl.log10(x),
def tune_alpha(self, drug_name, alphas=None, N=80, l1_ratio=0.5, kfolds=10, show=True, shuffle=False, alpha_range=[-2.8, 0.1], randomize_Y=False): """Interactive tuning of the model (alpha). This is much faster than :meth:`plot_cindex` but much slower than :meth:`runCV`. .. plot:: :include-source: from gdsctools import * ic = IC50(gdsctools_data("IC50_v5.csv.gz")) gf = GenomicFeatures(gdsctools_data("genomic_features_v5.csv.gz")) en = GDSCElasticNet(ic, gf) en.tune_alpha(1047, N=40, l1_ratio=0.1) """ if alphas is None: # logspace returns a vector in natural space that guarantees a # uniform spacing in a log space (log10 or ln) # -2.8 to 0.5 means alpha from 1.58e-3 to 3.16 # This is equivalent to log(1.58e-3)=-6.45 to log(3.16)=1.15 in ln # scale a1, a2 = alpha_range alphas = pylab.logspace(a1, a2, N) # Let us now do a CV across difference alphas all_scores = [] for alpha in alphas: scores = self.fit(drug_name, alpha, l1_ratio=l1_ratio, kfolds=kfolds, shuffle=shuffle, randomize_Y=randomize_Y) all_scores.append(scores) # We can now plot the results that is the mean scores + error enveloppe df = pd.DataFrame(all_scores) # we also identify the max correlation and corresponding alpha maximum = df.mean(axis=1).max() alpha_best = alphas[df.mean(axis=1).argmax()] if show is True: mu = df.mean(axis=1) sigma = df.var(axis=1) pylab.clf() pylab.errorbar(pylab.log(alphas), mu, yerr=sigma, color="gray") pylab.plot(pylab.log(alphas), mu, 'or') pylab.axvline(pylab.log(alpha_best), lw=4, alpha=0.5, color='g') pylab.title("Mean scores (pearson) across alphas for Kfold=%s" % kfolds) pylab.xlabel("ln(alpha)") pylab.ylabel("mean score (pearson)") pylab.grid() results = { "alpha_best": alpha_best, "ln_alpha": pylab.log(alpha_best), "maximum_Rp": maximum } return results
def smith(smithR=1, chart_type = 'z', draw_labels = False, border=False, ax=None, ref_imm = 1.0, draw_vswr=None): ''' plots the smith chart of a given radius Parameters ----------- smithR : number radius of smith chart chart_type : ['z','y','zy', 'yz'] Contour type. Possible values are * *'z'* : lines of constant impedance * *'y'* : lines of constant admittance * *'zy'* : lines of constant impedance stronger than admittance * *'yz'* : lines of constant admittance stronger than impedance draw_labels : Boolean annotate real and imaginary parts of impedance on the chart (only if smithR=1) border : Boolean draw a rectangular border with axis ticks, around the perimeter of the figure. Not used if draw_labels = True ax : matplotlib.axes object existing axes to draw smith chart on ref_imm : number Reference immittance for center of Smith chart. Only changes labels, if printed. draw_vswr : list of numbers, Boolean or None draw VSWR circles. If True, default values are used. ''' ##TODO: fix this function so it doesnt suck if ax == None: ax1 = plb.gca() else: ax1 = ax # contour holds matplotlib instances of: pathes.Circle, and lines.Line2D, which # are the contours on the smith chart contour = [] # these are hard-coded on purpose,as they should always be present rHeavyList = [0,1] xHeavyList = [1,-1] #TODO: fix this # these could be dynamically coded in the future, but work good'nuff for now if not draw_labels: rLightList = plb.logspace(3,-5,9,base=.5) xLightList = plb.hstack([plb.logspace(2,-5,8,base=.5), -1*plb.logspace(2,-5,8,base=.5)]) else: rLightList = plb.array( [ 0.2, 0.5, 1.0, 2.0, 5.0 ] ) xLightList = plb.array( [ 0.2, 0.5, 1.0, 2.0 , 5.0, -0.2, -0.5, -1.0, -2.0, -5.0 ] ) # vswr lines if isinstance(draw_vswr, (tuple,list)): vswrVeryLightList = draw_vswr elif draw_vswr is True: # use the default I like vswrVeryLightList = [1.5, 2.0, 3.0, 5.0] else: vswrVeryLightList = [] # cheap way to make a ok-looking smith chart at larger than 1 radii if smithR > 1: rMax = (1.+smithR)/(1.-smithR) rLightList = plb.hstack([ plb.linspace(0,rMax,11) , rLightList ]) if chart_type.startswith('y'): y_flip_sign = -1 else: y_flip_sign = 1 # draw impedance and/or admittance both_charts = chart_type in ('zy', 'yz') # loops through Verylight, Light and Heavy lists and draws circles using patches # for analysis of this see R.M. Weikles Microwave II notes (from uva) superLightColor = dict(ec='whitesmoke', fc='none') veryLightColor = dict(ec='lightgrey', fc='none') lightColor = dict(ec='grey', fc='none') heavyColor = dict(ec='black', fc='none') # vswr circules verylight for vswr in vswrVeryLightList: radius = (vswr-1.0) / (vswr+1.0) contour.append( Circle((0, 0), radius, **veryLightColor)) # impedance/admittance circles for r in rLightList: center = (r/(1.+r)*y_flip_sign,0 ) radius = 1./(1+r) if both_charts: contour.insert(0, Circle((-center[0], center[1]), radius, **superLightColor)) contour.append(Circle(center, radius, **lightColor)) for x in xLightList: center = (1*y_flip_sign,1./x) radius = 1./x if both_charts: contour.insert(0, Circle( (-center[0], center[1]), radius, **superLightColor)) contour.append(Circle(center, radius, **lightColor)) for r in rHeavyList: center = (r/(1.+r)*y_flip_sign,0 ) radius = 1./(1+r) contour.append(Circle(center, radius, **heavyColor)) for x in xHeavyList: center = (1*y_flip_sign,1./x) radius = 1./x contour.append(Circle(center, radius, **heavyColor)) # clipping circle clipc = Circle( [0,0], smithR, ec='k',fc='None',visible=True) ax1.add_patch( clipc) #draw x and y axis ax1.axhline(0, color='k', lw=.1, clip_path=clipc) ax1.axvline(1*y_flip_sign, color='k', clip_path=clipc) ax1.grid(0) # Set axis limits by plotting white points so zooming works properly ax1.plot(smithR*npy.array([-1.1, 1.1]), smithR*npy.array([-1.1, 1.1]), 'w.', markersize = 0) ax1.axis('image') # Combination of 'equal' and 'tight' if not border: ax1.yaxis.set_ticks([]) ax1.xaxis.set_ticks([]) for loc, spine in ax1.spines.items(): spine.set_color('none') if draw_labels: #Clear axis ax1.yaxis.set_ticks([]) ax1.xaxis.set_ticks([]) for loc, spine in ax1.spines.items(): spine.set_color('none') # Make annotations only if the radius is 1 if smithR is 1: #Make room for annotation ax1.plot(npy.array([-1.25, 1.25]), npy.array([-1.1, 1.1]), 'w.', markersize = 0) ax1.axis('image') #Annotate real part for value in rLightList: # Set radius of real part's label; offset slightly left (Z # chart, y_flip_sign == 1) or right (Y chart, y_flip_sign == -1) # so label doesn't overlap chart's circles rho = (value - 1)/(value + 1) - y_flip_sign*0.01 if y_flip_sign is 1: halignstyle = "right" else: halignstyle = "left" ax1.annotate(str(value*ref_imm), xy=(rho*smithR, 0.01), xytext=(rho*smithR, 0.01), ha = halignstyle, va = "baseline") #Annotate imaginary part radialScaleFactor = 1.01 # Scale radius of label position by this # factor. Making it >1 places the label # outside the Smith chart's circle for value in xLightList: #Transforms from complex to cartesian S = (1j*value - 1) / (1j*value + 1) S *= smithR * radialScaleFactor rhox = S.real rhoy = S.imag * y_flip_sign # Choose alignment anchor point based on label's value if ((value == 1.0) or (value == -1.0)): halignstyle = "center" elif (rhox < 0.0): halignstyle = "right" else: halignstyle = "left" if (rhoy < 0): valignstyle = "top" else: valignstyle = "bottom" #Annotate value ax1.annotate(str(value*ref_imm) + 'j', xy=(rhox, rhoy), xytext=(rhox, rhoy), ha = halignstyle, va = valignstyle) #Annotate 0 and inf ax1.annotate('0.0', xy=(-1.02, 0), xytext=(-1.02, 0), ha = "right", va = "center") ax1.annotate('$\infty$', xy=(radialScaleFactor, 0), xytext=(radialScaleFactor, 0), ha = "left", va = "center") # annotate vswr circles for vswr in vswrVeryLightList: rhoy = (vswr-1.0) / (vswr+1.0) ax1.annotate(str(vswr), xy=(0, rhoy*smithR), xytext=(0, rhoy*smithR), ha="center", va="bottom", color='grey', size='smaller') # loop though contours and draw them on the given axes for currentContour in contour: cc=ax1.add_patch(currentContour) cc.set_clip_path(clipc)
def plot(self, bins=100, cmap="hot_r", fontsize=10, Nlevels=4, xlabel=None, ylabel=None, norm=None, range=None, normed=False, colorbar=True, contour=True, grid=True, **kargs): """plots histogram of mean across replicates versus coefficient variation :param int bins: binning for the 2D histogram (either a float or list of 2 binning values). :param cmap: a valid colormap (defaults to hot_r) :param fontsize: fontsize for the labels :param int Nlevels: must be more than 2 :param str xlabel: set the xlabel (overwrites content of the dataframe) :param str ylabel: set the ylabel (overwrites content of the dataframe) :param norm: set to 'log' to show the log10 of the values. :param normed: normalise the data :param range: as in pylab.Hist2D : a 2x2 shape [[-3,3],[-4,4]] :param contour: show some contours (default to True) :param bool grid: Show unerlying grid (defaults to True) If the input is a dataframe, the xlabel and ylabel will be populated with the column names of the dataframe. """ X = self.df[self.df.columns[0]].values Y = self.df[self.df.columns[1]].values if len(X) > 10000: print("Computing 2D histogram. Please wait") pylab.clf() if norm == 'log': from matplotlib import colors res = pylab.hist2d(X, Y, bins=bins, density=normed, cmap=cmap, norm=colors.LogNorm()) else: res = pylab.hist2d(X, Y, bins=bins, cmap=cmap, density=normed, range=range) if colorbar is True: pylab.colorbar() if contour: try: bins1 = bins[0] bins2 = bins[1] except: bins1 = bins bins2 = bins X, Y = pylab.meshgrid(res[1][0:bins1], res[2][0:bins2]) if contour: if res[0].max().max() < 10 and norm == 'log': pylab.contour(X, Y, res[0].transpose()) else: levels = [ round(x) for x in pylab.logspace( 0, pylab.log10(res[0].max().max()), Nlevels) ] pylab.contour(X, Y, res[0].transpose(), levels[2:]) #pylab.clabel(C, fontsize=fontsize, inline=1) if ylabel is None: ylabel = self.df.columns[1] if xlabel is None: xlabel = self.df.columns[0] pylab.xlabel(xlabel, fontsize=fontsize) pylab.ylabel(ylabel, fontsize=fontsize) if grid is True: pylab.grid(True) return res
def plot_color_vs_mass_hist(): galaxies = mk_galaxy_struc() # Definitions for the axes left, width = 0.1, 0.65 bottom, height = 0.1, 0.65 bottom_h = left_h = left + width + 0.02 rect_scatter = [left, bottom, width, height] rect_histx = [left, bottom_h, width, 0.2] rect_histy = [left_h, bottom, 0.2, height] # Add the figures # Mass vs color plot I-H f1 = pyl.figure(1, figsize=(8, 8)) f1s1 = f1.add_axes(rect_scatter) f1s2 = f1.add_axes(rect_histx) f1s3 = f1.add_axes(rect_histy) # Mass vs color plot J-H f2 = pyl.figure(2, figsize=(8, 8)) f2s1 = f2.add_axes(rect_scatter) f2s2 = f2.add_axes(rect_histx) f2s3 = f2.add_axes(rect_histy) #f2s1 = f2.add_subplot(111) # Mass vs color plot Z-H f3 = pyl.figure(3, figsize=(8, 8)) f3s1 = f3.add_axes(rect_scatter) f3s2 = f3.add_axes(rect_histx) f3s3 = f3.add_axes(rect_histy) #f3s1 = f3.add_subplot(111) mass1 = [] color1 = [] mass2 = [] color2 = [] mass3 = [] color3 = [] for i in range(len(galaxies)): # Color vs Mass Plots if galaxies[i].ston_I > 30.0: if galaxies[i].Mips >= 10.0: f1s1.plot(galaxies[i].Mass, galaxies[i].Imag - galaxies[i].Hmag, c='#FFAB19', marker='o', markersize=9) mass1.append(galaxies[i].Mass) # Get the right mass color1.append(galaxies[i].Imag - galaxies[i].Hmag) # Get the color if galaxies[i].ICD_IH > 0.1: f1s1.plot(galaxies[i].Mass, galaxies[i].Imag - galaxies[i].Hmag, c='None', marker='s', markersize=10) else: f1s1.plot(galaxies[i].Mass, galaxies[i].Imag - galaxies[i].Hmag, c='#196DFF', marker='*') elif 20.0 < galaxies[i].ston_I and galaxies[i].ston_I < 30.0: f1s1.plot(galaxies[i].Mass, galaxies[i].Imag - galaxies[i].Hmag, c='0.8', marker='s', alpha=0.4) else: f1s1.plot(galaxies[i].Mass, galaxies[i].Imag - galaxies[i].Hmag, c='0.8', marker='.', alpha=0.4) if galaxies[i].ston_Z > 30.0: if galaxies[i].Mips >= 10.0: f2s1.plot(galaxies[i].Mass, galaxies[i].Zmag - galaxies[i].Hmag, c='#FFAB19', marker='o', markersize=9) mass2.append(galaxies[i].Mass) # Get the right mass color2.append(galaxies[i].Zmag - galaxies[i].Hmag) # Get the color if galaxies[i].ICD_ZH > 0.05: f2s1.plot(galaxies[i].Mass, galaxies[i].Zmag - galaxies[i].Hmag, c='None', marker='s', markersize=10) else: f2s1.plot(galaxies[i].Mass, galaxies[i].Zmag - galaxies[i].Hmag, c='#196DFF', marker='*') elif 20.0 < galaxies[i].ston_Z and galaxies[i].ston_Z < 30.0: f2s1.plot(galaxies[i].Mass, galaxies[i].Zmag - galaxies[i].Hmag, c='0.8', marker='s', alpha=0.4) else: f2s1.plot(galaxies[i].Mass, galaxies[i].Zmag - galaxies[i].Hmag, c='0.8', marker='.', alpha=0.4) if galaxies[i].ston_J > 30.0: if galaxies[i].Mips >= 10.0: f3s1.plot(galaxies[i].Mass, galaxies[i].Jmag - galaxies[i].Hmag, c='#FFAB19', marker='o', markersize=9) mass3.append(galaxies[i].Mass) # Get the right mass color3.append(galaxies[i].Jmag - galaxies[i].Hmag) # Get the color if galaxies[i].ICD_JH > 0.03: f3s1.plot(galaxies[i].Mass, galaxies[i].Jmag - galaxies[i].Hmag, c='None', marker='s', markersize=10) else: f3s1.plot(galaxies[i].Mass, galaxies[i].Jmag - galaxies[i].Hmag, c='#196DFF', marker='*') elif 20.0 < galaxies[i].ston_J and galaxies[i].ston_J < 30.0: f3s1.plot(galaxies[i].Mass, galaxies[i].Jmag - galaxies[i].Hmag, c='0.8', marker='s', alpha=0.4) else: f3s1.plot(galaxies[i].Mass, galaxies[i].Jmag - galaxies[i].Hmag, c='0.8', marker='.', alpha=0.4) ############ # FIGURE 1 # ############ pyl.figure(1) f1s1.set_xscale('log') f1s1.set_xlim(3e7, 1e12) f1s1.set_ylim(0, 4.5) f1s1.set_xlabel(r"$Log_{10}(M_{\odot})$", fontsize=20) f1s1.set_ylabel("$(I-H)_{Observed}$", fontsize=20) f1s1.tick_params(axis='both', pad=7) binsx = pyl.logspace(7, 12) binsy = pyl.linspace(f1s1.get_ylim()[0], f1s1.get_ylim()[1] + 0.25) f1s2.hist(mass1, bins=binsx) f1s2.set_xlim(f1s1.get_xlim()) f1s2.tick_params(labelbottom='off') f1s2.set_xscale('log') f1s3.hist(color1, bins=binsy, orientation='horizontal') f1s3.set_ylim(f1s1.get_ylim()) f1s3.tick_params(labelleft='off') pyl.savefig('color_vs_mass_hist_IH.eps') ############ # FIGURE 2 # ############ pyl.figure(2) f2s1.set_xscale('log') f2s1.set_xlim(3e7, 1e12) f2s1.set_xlabel(r"$Log_{10}(M_{\odot})$", fontsize=20) f2s1.set_ylabel("$(Z-H)_{Observed}$", fontsize=20) f2s1.tick_params(axis='both', pad=7) binsx = pyl.logspace(7, 12) binsy = pyl.linspace(f2s1.get_ylim()[0], f2s1.get_ylim()[1] + 0.25) f2s2.hist(mass2, bins=binsx) f2s2.set_xlim(f2s1.get_xlim()) f2s2.tick_params(labelbottom='off') f2s2.set_xscale('log') f2s3.hist(color2, bins=binsy, orientation='horizontal') f2s3.set_ylim(f2s1.get_ylim()) f2s3.tick_params(labelleft='off') pyl.savefig('color_vs_mass_hist_ZH.eps') ############ # FIGURE 3 # ############ pyl.figure(3) f3s1.set_xscale('log') f3s1.set_xlim(3e7, 1e12) f3s1.set_ylim(-0.5, 2) f3s1.set_xlabel(r"$Log_{10}(M_{\odot})$", fontsize=20) f3s1.set_ylabel("$(J-H)_{Observed}$", fontsize=20) f3s1.tick_params(axis='both', pad=7) binsx = pyl.logspace(7, 12) binsy = pyl.linspace(f3s1.get_ylim()[0], f3s1.get_ylim()[1] + 0.25) f3s2.hist(mass3, bins=binsx) f3s2.set_xlim(f3s1.get_xlim()) f3s2.tick_params(labelbottom='off') f3s2.set_xscale('log') f3s3.hist(color3, bins=binsy, orientation='horizontal') f3s3.set_ylim(f3s1.get_ylim()) f3s3.tick_params(labelleft='off') pyl.savefig('color_vs_mass_hist_JH.eps') pyl.show()
def smith(smithR=1, chart_type = 'z', draw_labels = False, border=False, ax=None): ''' plots the smith chart of a given radius Parameters ----------- smithR : number radius of smith chart chart_type : ['z','y'] Contour type. Possible values are * *'z'* : lines of constant impedance * *'y'* : lines of constant admittance draw_labels : Boolean annotate real and imaginary parts of impedance on the chart (only if smithR=1) border : Boolean draw a rectangular border with axis ticks, around the perimeter of the figure. Not used if draw_labels = True ax : matplotlib.axes object existing axes to draw smith chart on ''' ##TODO: fix this function so it doesnt suck if ax == None: ax1 = plb.gca() else: ax1 = ax # contour holds matplotlib instances of: pathes.Circle, and lines.Line2D, which # are the contours on the smith chart contour = [] # these are hard-coded on purpose,as they should always be present rHeavyList = [0,1] xHeavyList = [1,-1] #TODO: fix this # these could be dynamically coded in the future, but work good'nuff for now if not draw_labels: rLightList = plb.logspace(3,-5,9,base=.5) xLightList = plb.hstack([plb.logspace(2,-5,8,base=.5), -1*plb.logspace(2,-5,8,base=.5)]) else: rLightList = plb.array( [ 0.2, 0.5, 1.0, 2.0, 5.0 ] ) xLightList = plb.array( [ 0.2, 0.5, 1.0, 2.0 , 5.0, -0.2, -0.5, -1.0, -2.0, -5.0 ] ) # cheap way to make a ok-looking smith chart at larger than 1 radii if smithR > 1: rMax = (1.+smithR)/(1.-smithR) rLightList = plb.hstack([ plb.linspace(0,rMax,11) , rLightList ]) if chart_type is 'y': y_flip_sign = -1 else: y_flip_sign = 1 # loops through Light and Heavy lists and draws circles using patches # for analysis of this see R.M. Weikles Microwave II notes (from uva) for r in rLightList: center = (r/(1.+r)*y_flip_sign,0 ) radius = 1./(1+r) contour.append( Circle( center, radius, ec='grey',fc = 'none')) for x in xLightList: center = (1*y_flip_sign,1./x) radius = 1./x contour.append( Circle( center, radius, ec='grey',fc = 'none')) for r in rHeavyList: center = (r/(1.+r)*y_flip_sign,0 ) radius = 1./(1+r) contour.append( Circle( center, radius, ec= 'black', fc = 'none')) for x in xHeavyList: center = (1*y_flip_sign,1./x) radius = 1./x contour.append( Circle( center, radius, ec='black',fc = 'none')) # clipping circle clipc = Circle( [0,0], smithR, ec='k',fc='None',visible=True) ax1.add_patch( clipc) #draw x and y axis ax1.axhline(0, color='k', lw=.1, clip_path=clipc) ax1.axvline(1*y_flip_sign, color='k', clip_path=clipc) ax1.grid(0) #set axis limits ax1.axis('equal') ax1.axis(smithR*npy.array([-1.1, 1.1, -1.1, 1.1])) if not border: ax1.yaxis.set_ticks([]) ax1.xaxis.set_ticks([]) for loc, spine in ax1.spines.iteritems(): spine.set_color('none') if draw_labels: #Clear axis ax1.yaxis.set_ticks([]) ax1.xaxis.set_ticks([]) for loc, spine in ax1.spines.iteritems(): spine.set_color('none') #Will make annotations only if the radius is 1 and it is the impedance smith chart if smithR is 1 and y_flip_sign is 1: #Make room for annotation ax1.axis(smithR*npy.array([-1., 1., -1.2, 1.2])) #Annotate real part for value in rLightList: rho = (value - 1)/(value + 1) ax1.annotate(str(value), xy=((rho-0.12)*smithR, 0.01*smithR), \ xytext=((rho-0.12)*smithR, 0.01*smithR)) #Annotate imaginary part deltax = plb.array([-0.17, -0.14, -0.06, 0., 0.02, -0.2, -0.2, -0.08, 0., 0.03]) deltay = plb.array([0., 0.03, 0.01, 0.02, 0., -0.02, -0.06, -0.09, -0.08, -0.05]) for value, dx, dy in zip(xLightList, deltax, deltay): #Transforms from complex to cartesian and adds a delta to x and y values rhox = (-value**2 + 1)/(-value**2 - 1) * smithR * y_flip_sign + dx rhoy = (-2*value)/(-value**2 - 1) * smithR + dy #Annotate value ax1.annotate(str(value) + 'j', xy=(rhox, rhoy), xytext=(rhox, rhoy)) #Annotate 0 and inf ax1.annotate('0.0', xy=(-1.15, -0.02), xytext=(-1.15, -0.02)) ax1.annotate('$\infty$', xy=(1.02, -0.02), xytext=(1.02, -0.02)) # loop though contours and draw them on the given axes for currentContour in contour: cc=ax1.add_patch(currentContour) cc.set_clip_path(clipc)
print " proton ky : " , ky , " " , complex(Disp(omega,kp,b,eta, 1.) ) print " electron ky : " , ky , " " , complex(mp.sqrt(m_ie)*Disp(omega,kp,b,eta,m_ie) ) """ #print " electron ky : " , ky , " " , complex(Disp(omega,kp * mp.sqrt(m_ie), b/m_ie, eta/mp.sqrt(m_ie) ) + 1. - Gamma0(b/m_ie)) return (pylab.array(ky_list), pylab.array(results), pylab.array(residuum)) #for theta in [ 0.033, 0.050, 0.133, 0.15, 0.2 ]: for theta in [ 0.10]: Setup = { 'eta' : 4., 'kx' : 0.0, 'v_te' : mp.sqrt(2.), 'rho_te2' : 1., 'tau' : 1., 'theta' : 0. , 'm_ie' : 100., 'lambda_D2' : 0.} ky_list = pylab.logspace(pylab.log10(0.2), pylab.log10(10.), 51) #ky_list = pylab.linspace(20., 60.,101) Setup['theta'] = theta ky, gamma, err = getGrowth(ky_list, Setup, disp="Gyro", init= 0.02 + 0.045j) pylab.semilogx(ky, pylab.imag(gamma), 'b-', label='Gyro') #pylab.plot(ky, pylab.imag(gamma), 'b-', label='Gyro') #ky, gamma, err = getGrowth(ky_list, Setup, disp="Gyro1st", init=0.02+0.045j) #pylab.semilogx(ky[:350], pylab.imag(gamma)[:350], 'g-', label='Gyro $\\mathcal{O}{(1)}$') #ky, gamma, err = getGrowth(ky_list, Setup, disp="Fluid", init = 0.02 + 0.045j) #pylab.semilogx(ky, pylab.imag(gamma), 'r-', label='Fluid ') #ky, gamma, err = getGrowth(ky_list, Setup, disp="GyroKin", init=-0.01 + 0.01j) #ky, gamma, err = getGrowth(ky_list, Setup, disp="GyroKin", init= 0.02 + 0.045j)