def plot_channel(ax, c, clusters, cluster_p_values, plot_type, full=False): for i_c, (start, stop) in enumerate(clusters): if start / n_times == c: start -= c * n_times stop -= c * n_times if cluster_p_values[i_c] <= 0.05: h = ax.axvspan(times[start], times[stop - 1], color='r', alpha=0.3) else: ax.axvspan(times[start], times[stop - 1], color=(0.3, 0.3, 0.3), alpha=0.3) pl.axhline(y=0, linewidth=1, color="black") if plot_type == "data": hf = ax.plot(times, -1 * means0[c], "r", times, -1 * means1[c], "g") if not full: pl.text(-0.035, ydata_scale * .9, ydata_scale_txt) pl.legend(hf, (cond_names[0], cond_names[1]), loc="upper right") elif plot_type == "f": hf = ax.plot(times, T_obs[c], 'g') pl.vlines(x=xt, ymin=ymarks * -1, ymax=ymarks) pl.vlines(x=xt2, ymin=np.array([0]), ymax=ymarks2, linewidth=1) pl.hlines(ydata_scale, xmark * -1, xmark) pl.xlim([0, times[lent - 1]]) return hf
def plot_matrices(cov, prec, title, subject_n=0): """Plot covariance and precision matrices, for a given processing. """ # Put zeros on the diagonal, for graph clarity. size = prec.shape[0] prec[range(size), range(size)] = 0 span = max(abs(prec.min()), abs(prec.max())) title = "{0:d} {1}".format(subject_n, title) # Display covariance matrix pl.figure() pl.imshow(cov, interpolation="nearest", vmin=-1, vmax=1, cmap=pl.cm.get_cmap("bwr")) pl.hlines([(pl.ylim()[0] + pl.ylim()[1]) / 2], pl.xlim()[0], pl.xlim()[1]) pl.vlines([(pl.xlim()[0] + pl.xlim()[1]) / 2], pl.ylim()[0], pl.ylim()[1]) pl.colorbar() pl.title(title + " / covariance") # Display precision matrix pl.figure() pl.imshow(prec, interpolation="nearest", vmin=-span, vmax=span, cmap=pl.cm.get_cmap("bwr")) pl.hlines([(pl.ylim()[0] + pl.ylim()[1]) / 2], pl.xlim()[0], pl.xlim()[1]) pl.vlines([(pl.xlim()[0] + pl.xlim()[1]) / 2], pl.ylim()[0], pl.ylim()[1]) pl.colorbar() pl.title(title + " / precision")
def PlotTemp2(md_list, th=2): """ Second function (and main) to analyze the results of the activation threshold""" hold = {} #empty dictionary for md in md_list: hold[md.experiment] = [[0], [0]] + color[md.experiment] for md in md_list: p = md.CalcProb(th=th) hold[md.experiment][0] += [md.data_other['Time']] hold[md.experiment][1] += [p] ### This 'plot' is only to get the label right for room temp. plot(0, 0, '-', marker='.', markersize=1, color='blue', linewidth=2) for experiment in hold: plot( hold[experiment][0], hold[experiment][1], '-',\ marker=hold[experiment][3], markersize=5,\ color=hold[experiment][2], linewidth=2, label=hold[experiment][4]) ylabel(r"$P( E <= %d | Y)$" % (th)) xlabel(r"$min$") hlines(0, -1, 91) vlines(0, -0.1, 1.1) xlim((-1, 91)) ylim((-0.1, 1.1)) axis([-1, 20, -0.1, 1.1]) legend() return hold
def test_cl(): bins_l = np.int64(np.linspace(10.,3000,100)) bins_u = bins_l[1:] -1 bins_l = bins_l[0:len(bins_l)-1] binner = jc_utils.binner(bins_l,bins_u) del bins_l,bins_u import pylab as pl pl.ioff() from matplotlib.backends.backend_pdf import PdfPages stats_len = jc_utils.stats(binner.Nbins()) for i,idx in enumerate_progress(xrange(nsims),label = 'test_cl::collecting cls'): sim_cl_len = lib_cmb_unl.map2cl(lib_cmb_len.get_sim(idx)) stats_len.add(binner.bin_that(np.arange(len(sim_cl_len)),sim_cl_len)) camb_binned = binner.bin_that(np.arange(len(cl_len)),cl_len) camb_unl_binned = binner.bin_that(np.arange(len(cl_unl)),cl_unl) pp = PdfPages(path_to_figs+'/lenclvscamb.pdf') pl.figure() pl.title('len Cl vs CAMB, ' +str(nsims) + ' sims.') pl.plot(binner.bin_centers(),stats_len.mean()/camb_binned -1.,label = 'sim/camb -1.,100 bins, res ' + str(HD_res)) pl.xlabel('$\ell$') pl.ylim(-0.05,0.05) pl.hlines([-0.001,0.001],np.min(binner.bins_l),np.max(binner.bins_r),linestyles='--',color = 'grey') pl.legend(frameon = False) pp.savefig() pl.figure() pl.title('cl_len / cl_unlCAMB, ' +str(nsims) + ' sims.') pl.plot(binner.bin_centers(),stats_len.mean()/camb_unl_binned -1.,label = 'sim/camb_unl -1.,binned, res ' + str(HD_res)) pl.plot(binner.bin_centers(),camb_binned/camb_unl_binned -1.,label = 'camb_len/camb_unl -1.,binned.') pl.xlabel('$\ell$') pl.legend(frameon = False) pp.savefig() pp.close() pl.close()
def centroidSuband(filter=None): """ This code calcualte the centroid change in each subband. """ xceng1,yceng1 = centroidChangeFP(filter=filter,suband = 1) xceng2,yceng2 = centroidChangeFP(filter=filter,suband = 2) xceng3,yceng3 = centroidChangeFP(filter=filter,suband = 3) xceng4,yceng4 = centroidChangeFP(filter=filter,suband = 4) xceng5,yceng5 = centroidChangeFP(filter=filter,suband = 5) r = np.sqrt(xceng1**2 + yceng1**2) pl.figure(figsize=(10,7)) pl.subplot(2,1,1) pl.plot(r,(xceng2-xceng1)*1000./15.,'b.',label='sub2 - sub1') pl.plot(r,(xceng3-xceng1)*1000./15.,'r.',label='sub3 - sub1') pl.plot(r,(xceng4-xceng1)*1000./15.,'g.',label='sub4 - sub1') pl.plot(r,(xceng5-xceng1)*1000./15.,'c.',label='sub5 - sub1') pl.legend(loc='lower left') pl.hlines(0,0,300,color='k',linestyle='dashed') pl.xlim(0,300) pl.xlabel('distance to the FP center (mm)') pl.ylabel('x centroid difference (pixel)') pl.title('Centroid Change for subands of filter: '+filter) pl.subplot(2,1,2) pl.plot(r,(yceng2-yceng1)*1000./15.,'b.',label='sub2 - sub1') pl.plot(r,(yceng3-yceng1)*1000./15.,'r.',label='sub3 - sub1') pl.plot(r,(yceng4-yceng1)*1000./15.,'g.',label='sub4 - sub1') pl.plot(r,(yceng5-yceng1)*1000./15.,'c.',label='sub5 - sub1') pl.legend(loc='lower left') pl.hlines(0,0,300,color='k',linestyle='dashed') pl.xlim(0,300) pl.xlabel('distance to the FP center (mm)') pl.ylabel('y centroid difference (pixel)') return xceng1, yceng1, xceng2, yceng2,xceng3,yceng3,xceng4,yceng4,xceng5,yceng5
def plotT(x, y, plt): plt.scatter(x, y) plt.vlines(x, [0], y) plt.ylim((min(y)-abs(min(y)*0.1)),max(y)+max(y)*0.1) plt.hlines(0, x[0]-1, x[x.shape[0]-1]+1) plt.xlim(x[0]-1,x[x.shape[0]-1]+1) plt.grid()
def simulation(recipe, curvNo, noIndicators): worker = recipe.getWorker("ThicknessModeller") simulation = worker.plugCalcAbsorption.getResult() worker = recipe.getWorker("AddColumn") table = worker.plugCompute.getResult( subscriber=TextSubscriber("Add Column")) thickness = table[u"thickness"] index = curvNo2Index(table[u"pixel"], curvNo) worker = recipe.getWorker("MRA Exp") minimaPos = worker.plugMra.getResult()[r'\lambda_{min}'].inUnitsOf( simulation.dimensions[1]) maximaPos = worker.plugMra.getResult()[r'\lambda_{max}'].inUnitsOf( simulation.dimensions[1]) visualizer = ImageVisualizer(simulation, False) ordinate = simulation.dimensions[1].data if not noIndicators: pylab.hlines(thickness.data[index], ordinate.min(), ordinate.max(), label="$%s$" % minimaPos.shortname) abscissae = simulation.dimensions[0].data pylab.vlines(minimaPos.data[:, index], abscissae.min(), abscissae.max(), label="$%s$" % minimaPos.shortname) pylab.vlines(maximaPos.data[:, index], abscissae.min(), abscissae.max(), label="$%s$" % maximaPos.shortname)
def Orion_PVDiagrams( filename="OMC1_TSPEC_H2S1_cube.fits", restwavelength=2.1218313 * u.um, cm=pl.cm.hot, start_fignum=0, min_valid=1e-16, displaymax=None, hlcolor="k", linename="H2 S(1) 1-0", dosave=True, ): cube = fits.getdata(filename) header = fits.getheader(filename) wavelength = ((-header["CRPIX3"] + np.arange(header["NAXIS3"]) + 1) * header["CD3_3"] + header["CRVAL3"]) * u.AA velocity = wavelength.to("km/s", u.doppler_optical(restwavelength)) nvel = len(velocity) def make_pv(startx=196, starty=130, endx=267, endy=388, npts=250): pvd = np.empty([nvel, npts]) for ii, (x, y) in enumerate(zip(np.linspace(startx, endx, npts), np.linspace(starty, endy, npts))): pvd[:, ii] = cube[:, y, x] return pvd for ii, (ex, ey) in enumerate(outflow_endpoints): dx = ex - sourceI[0] dy = ey - sourceI[1] angle = np.arctan2(dy, dx) cdelt = np.abs(header["CDELT1"] / np.cos(angle)) * 3600 npts = (dx ** 2 + dy ** 2) ** 0.5 # pixels are in FITS units pv = make_pv(endx=ex - 1, endy=ey - 1, startx=sourceI[0] - 1, starty=sourceI[1] - 1, npts=npts) fignum = start_fignum + ii / 3 pl.figure(fignum) if ii % 3 == 0: pl.clf() ax = pl.subplot(3, 1, ii % 3 + 1) vmin, vmax = velocity.min().value, velocity.max().value pv[pv < 0] = np.nanmin(pv) pv[pv < min_valid] = min_valid pl.imshow( np.log10(pv), extent=[0, npts * cdelt, vmin, vmax], aspect=np.abs(cdelt) / 20 * (npts / 100), cmap=cm, vmax=displaymax, origin="lower", ) pl.hlines(0, 0, npts * cdelt, color=hlcolor, linestyle="--") ax.set_xlabel('Offset (")') ax.set_ylabel("Velocity (km s$^{-1}$)") ax.set_title(linename + " Outflow Trace %i" % ii) ax.set_ylim(-200, 200) if dosave and ii % 3 == 2 or ii == len(outflow_endpoints) - 1: name = linename.replace(" ", "_").replace("(", "_").replace(")", "_") name = "".join([l for l in name if l in (string.ascii_letters + string.digits + "_-")]) figname = name + "_%i.png" % fignum pl.savefig(figname.replace("__", "_"))
def plot_T1_Hct(par_dict, Hct_sol, sO2=0.5, T1=1.5): R1ery0 = par_dict['R1ery0'] R1plas = par_dict['R1plas'] r1dHb = par_dict['r1_prime_dHb'] Hct_axis = np.arange(0, 1.001, 0.001) xtemp = np.zeros([2, len(Hct_axis)]) xtemp[0, :] = Hct_axis xtemp[1, :] = sO2 T1s = 1000 / calc_R1(xtemp, R1plas, R1ery0, r1dHb) plt.xlabel('hematocrit (Hct)', fontsize=16) plt.ylabel('$T_1$ relaxation time (ms)', fontsize=16) plt.plot(Hct_axis, T1s, lw=2) plt.ylim([0.95 * np.min(T1s), 1.05 * np.max(T1s)]) plt.xlim([0, 1]) plt.hlines(1000 * T1, 0, 1, linestyle='dashed') plt.vlines(Hct_sol, 0.95 * np.min(T1s), 1.05 * np.max(T1s), linestyle='dashed') return
def plot_ge( name_plot ): # distance between axes and ticks pl.rcParams['xtick.major.pad']='8' pl.rcParams['ytick.major.pad']='8' # set latex font pl.rc('text', usetex=True) pl.rc('font', **{'family': 'serif', 'serif': ['Computer Modern'], 'size': 20}) pl.close('all') fig = pl.figure(figsize=(10.0, 5.0)) ax = fig.add_subplot(111) fig.suptitle('GE, Janaury-February 2007', fontsize=20, fontweight='bold') den = 0.008 N_max_day = 50 sel_side = (df_ge.side==1) & (df_ge.day_trade_n < N_max_day) df_ge_buy = df_ge[sel_side] pl.hlines(df_ge_buy.day_trade_n, df_ge_buy.mm_s, df_ge_buy.mm_e, linestyles='solid', lw= pl.array(df_ge_buy.eta/den), color='blue', alpha=0.3) sel_side = (df_ge.side==-1) & (df_ge.day_trade_n < N_max_day) df_ge_sell = df_ge[sel_side] pl.hlines(df_ge_sell.day_trade_n, df_ge_sell.mm_s, df_ge_sell.mm_e, linestyles='solid', lw= pl.array(df_ge_sell.eta/den), color='red', alpha=0.3) ax.set_xlim([0,390]) ax.set_ylim([N_max_day,-1]) ax.set_aspect('auto') ax.set_xlabel('Trading minute') ax.set_ylabel('Trading day') pl.subplots_adjust(bottom=0.15) pl.savefig("../plot/" + name_plot + ".pdf")
def plot_samples(S, axis_list=None): pl.scatter(S[:, 0], S[:, 1], s=2, marker='o', linewidths=0, zorder=10) if axis_list is not None: colors = [(0, 0.6, 0), (0.6, 0, 0)] for color, axis in zip(colors, axis_list): axis /= axis.std() x_axis, y_axis = axis # Trick to get legend to work pl.plot(0.1 * x_axis, 0.1 * y_axis, linewidth=2, color=color) # pl.quiver(x_axis, y_axis, x_axis, y_axis, zorder=11, width=0.01, pl.quiver(0, 0, x_axis, y_axis, zorder=11, width=0.01, scale=6, color=color) pl.hlines(0, -3, 3) pl.vlines(0, -3, 3) pl.xlim(-3, 3) pl.ylim(-3, 3) pl.xlabel('x') pl.ylabel('y')
def plot_one_ppc(model, t): """ plot data and posterior predictive check :Parameters: - `model` : data.ModelData - `t` : str, data type of 'i', 'r', 'f', 'p', 'rr', 'm', 'X', 'pf', 'csmr' """ stats = model.vars[t]['p_pred'].stats() if stats == None: return pl.figure() pl.title(t) x = model.vars[t]['p_obs'].value.__array__() y = x - stats['quantiles'][50] yerr = [stats['quantiles'][50] - pl.atleast_2d(stats['95% HPD interval'])[:,0], pl.atleast_2d(stats['95% HPD interval'])[:,1] - stats['quantiles'][50]] pl.errorbar(x, y, yerr=yerr, fmt='ko', mec='w', capsize=0, label='Obs vs Residual (Obs - Pred)') pl.xlabel('Observation') pl.ylabel('Residual (observation-prediction)') pl.grid() l,r,b,t = pl.axis() pl.hlines([0], l, r) pl.axis([l, r, y.min()*1.1 - y.max()*.1, -y.min()*.1 + y.max()*1.1])
def fwhm_whisker_des_plot(stampImgList=None, bkgList=None, whkSex=None, fwhmSex=None, sigma=1.1 / scale, dimmfwhm=None): whk, fwhm = get_fwhm_whisker_list(stampImgList, bkgList, sigma=sigma) whk = list(whk.T) fwh = list(fwhm.T) fwh.append(fwhmSex) whk.append(whkSex) pl.figure(figsize=(15, 10)) pl.subplot(2, 1, 1) pl.boxplot(whk) pl.hlines(0.2, 0, 4, linestyle='solid', color='g') pl.ylim(np.median(whk[2]) - 0.3, np.median(whk[2]) + 0.6) pl.grid() pl.xticks(np.arange(1, 4), ['whisker_Wmoments', 'whisker_Amoments', 'whisker_sx']) if dimmfwhm != None: pl.title('DIMM Seeing FWHM: ' + str(round(dimmfwhm, 3)) + '(arcsec) sqrt(DIMM fwhm^2 + 0.55^2): ' + str(round(np.sqrt(dimmfwhm**2 + 0.55**2), 3))) pl.subplot(2, 1, 2) pl.boxplot(fwh) pl.ylim(0, np.median(fwh[5]) + 2) pl.grid() pl.hlines(0.9, 0, 7, linestyle='solid', color='g') pl.xticks(np.arange(1, 7), [ 'fwhm_weighted', 'fwhm_Amoments', 'fwhm_moffat', 'fwhm_gauss', 'fwhm_sech2', 'fwhm_sx' ]) return '-----done !----'
def chunked_timing(X, Y, axis=1, metric="euclidean", **kwargs): sizes = [20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000, 200000] t0 = time.time() original(X, Y, axis=axis, metric=metric, **kwargs) t1 = time.time() original_timing = t1 - t0 chunked_timings = [] for batch_size in sizes: print("batch_size: %d" % batch_size) t0 = time.time() chunked(X, Y, axis=axis, metric=metric, batch_size=batch_size, **kwargs) t1 = time.time() chunked_timings.append(t1 - t0) import pylab as pl pl.semilogx(sizes, chunked_timings, '-+', label="chunked") pl.hlines(original_timing, sizes[0], sizes[-1], color='k', label="original") pl.grid() pl.xlabel("batch size") pl.ylabel("execution time (wall clock)") pl.title("%s %d / %d (axis %d)" % ( str(metric), X.shape[0], Y.shape[0], axis)) pl.legend() pl.savefig("%s_%d_%d_%d" % (str(metric), X.shape[0], Y.shape[0], axis)) pl.show()
def scatter_force_error(configs, ref_configs, force_name='force', force_ref_name='force', *plot_args, **plot_kwargs): """ Make a scatter plot of force errors between Atoms sequences `config` and `ref_configs` """ ref_force = np.hstack(getattr(ref_configs, force_ref_name)) ref_force = ref_force.reshape(ref_force.size, order='F') force = np.hstack(getattr(configs, force_name)) force = force.reshape(force.size, order='F') s = scatter(abs(ref_force), abs(ref_force - force), *plot_args, **plot_kwargs) xlim(0, abs(ref_force).max()) ylim(0, abs(ref_force - force).max()) xlabel('Reference forces / eV/A') ylabel('Force error / eV/A') rms_error = (((force - ref_force)**2).mean())**0.5 hlines(rms_error, 0, abs(ref_force).max(), lw=2, color='r') return s
def generate_preprocessing_mito_fig(self, mito_filtered_cell_dict, key): # mito threshold boundaries mito_col = np.where( mito_filtered_cell_dict[key].obs['percent_mito'] < self.output_summary[key]['thrsh_mito'], 'grey', 'r') # Scatter plot mito_scatter = plt.scatter(mito_filtered_cell_dict[key].obs['n_counts'], mito_filtered_cell_dict[key].obs['percent_mito'],\ s=1, c=mito_col) # Red lines plt.hlines(y=self.output_summary[key]['thrsh_mito'], xmin=-1, xmax=50000, color='red') # plt.text(50000,self.output_summary[key]['thrsh_mito']+1, s='Mito Threshold: ' + str(self.output_summary[key]['thrsh_mito'])) legend_elements = [ Line2D([0], [0], color='r', lw=1, label='Mito Threshold: {0:.2f}'.format( round(self.output_summary[key]['thrsh_mito'], 2))) ] plt.legend(handles=legend_elements, loc='upper right') plt.xlabel('n_counts', fontsize=18) plt.ylabel('percent_mito', fontsize=16) if self.output_dir: plt.savefig(self.output_dir[0] + "/" + key + "/preprocessing_figures/" + key + "_percent_mito_vs_n_counts") plt.close() else: plt.savefig(key + "/preprocessing_figures/" + key + "_percent_mito_vs_n_counts") plt.close() plt.close()
def depth_graph(): #filenames filename_png = os.getcwd() + '/' + str(args.output_folder) + '/depth_insertion.png' filename_svg = os.getcwd() + '/' + str(args.output_folder) + '/depth_insertion.svg' #create figure fig = plt.figure(figsize=(8, 6.2)) #plot data ax = fig.add_subplot(111) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.set_xlim(0, nb_atom_per_protein) for t in ["basic","polar","hydrophobic","backbone"]: tmp_z = np.zeros(nb_atom_per_protein) tmp_z[type_pos[t]] = z_part[type_pos[t]] plt.bar(np.arange(0,nb_atom_per_protein), tmp_z, color = res_colour[t], label = t) fontP.set_size("small") ax.legend(prop=fontP) plt.hlines(0, 0, nb_atom_per_protein,) plt.xlabel('sequence') plt.ylabel('z distance to leaflet') #save figure fig.savefig(filename_png) fig.savefig(filename_svg) plt.close() return
def plot_var(filename, color): nc = netCDF4.Dataset(filename) try: v = nc.variables[name] except: print "Cannot find '%s' in '%s'. Exiting..." % (name, filename) import sys sys.exit(1) unit_system = udunits2.System() time_units_input = udunits2.Unit(unit_system, nc.variables['time'].units) time_units_years = udunits2.Unit(unit_system, "years since 2012-1-1") c = udunits2.Converter((time_units_input, time_units_years)) print "Converting time from '%s' to '%s'" % (time_units_input, time_units_years) time_bounds = c(nc.variables['time_bounds'][:]) time_min = time_bounds[:,0] time_max = time_bounds[:,1] hlines(numpy.squeeze(v[:]), time_min, time_max, color=color, label=filename) xlabel("time (years)") ylabel(v.units) title(v.long_name) return time_bounds.min(), time_bounds.max(), v[:].min(), v[:].max()
def showEnergies(em, alphabet="ACGT", nSeqs=inf, fig=None): #according to logo standard seqLen, nBases = em.shape if nBases != len(alphabet): raise Exception("Need %d alphabet" % len(alphabet)) if nBases == 4: colors = ["#00cc00", "#0000cc", "#ffb300", "#cc0000"] else: colors = matplotlib.cm.jet( arange(1, nBases + 1, dtype=float) / (nBases + 1)) fontprop = FontProperties(family="monospace", stretch="condensed", weight="bold", size="medium") em = em - mean(em, 1)[:, newaxis] print em sem = argsort(em, 0) if fig == None: fig = pylab.figure(figsize=(8, 3)) def addletter(let, x, y, height, color, alpha=1): text = TextPath((0, 0), let, size=1, prop=fontprop) bbox = text.get_extents() tx0, ty0 = bbox.min tw, th = bbox.width, bbox.height trans = Affine2D.identity() \ .translate(-tx0,-ty0) \ .scale(0.9/tw,height/th) \ .translate(x,y) t = trans.transform_path(text) pylab.gca().add_patch(PathPatch(t, fc=color, ec='none', alpha=alpha)) for n, row in enumerate(em): pos = arange(nBases)[row > 0][argsort(row[row > 0])] neg = arange(nBases)[row < 0][argsort(row[row < 0])[::-1]] hpos = 0 for i in pos: addletter(alphabet[i], n + 0.5, hpos, row[i], colors[i]) hpos += row[i] hpos = 0 for i in neg: addletter(alphabet[i], n + 0.5, hpos + row[i], -row[i], colors[i], alpha=0.5) hpos += row[i] pylab.hlines(0, 0, seqLen + 0.5, colors='k') pylab.xticks(arange(seqLen) + 1) #pylab.ylabel('Bits') pylab.xlim(0.5, seqLen + 0.5) #pylab.ylim(0,max(sum(heights,1))) #pylab.ylim(0,log2(nBases)) return fig
def draw_fit(rl, pct): """Draw sigmoid for psychometric rl: x values pct: y values Fxn draws the curve """ def sig(x, A, x0, k, y0): return A / (1 + np.exp(-k*(x-x0))) + y0 def sig2(x, x0, k): return 1. / (1+np.exp(-k*(x-x0))) pl.xlabel('R-L stimuli') pl.ylabel('p(choose R)') pl.xlim([rl.min()-1, rl.max()+1]) pl.ylim([-0.05, 1.05]) popt,pcov = curve_fit(sig, rl, pct) # stretch and yshift are free params popt2,pcov2 = curve_fit(sig2, rl, pct) # stretch and yshift are fixed x = np.linspace(rl.min(), rl.max(), 200) y = sig(x, *popt) y2 = sig2(x, *popt2) pl.vlines(0,0,1,linestyles='--') pl.hlines(0.5,rl.min(),rl.max(),linestyles='--') pl.plot(x,y) #pl.plot(x,y2) return popt
def statistics(df, keys=None, plot=False): data = {} for key in keys: try: df_meas = new_sample(df[key]) dt = find_meas_period(df_meas) stddev = pl.sqrt(df_meas.var()) mean = df_meas.mean() variance = stddev**2 noise_power = variance * dt except Exception: df_meas = 0 dt = 0 stddev = 0 var = 0 mean = 0 noise_power = 0 variance = 0 data[key + '_stddev'] = stddev data[key + '_variance'] = variance data[key + '_mean'] = mean data[key + '_dt'] = dt data[key + '_noise_power'] = noise_power if plot: pl.figure() pl.title(key + ' statistics') df[key].plot(alpha=0.5) pl.hlines(mean, df.index[0], df.index[-1], 'k') pl.hlines([mean + stddev, mean - stddev], df.index[0], df.index[-1], 'r') return data
def plot(self): import pylab as pl ax = pl.gca() pl.hlines(self.tops, self.left, self.right, linestyles='dashed', colors='blue') pl.hlines(self.tops + self.heights, self.left, self.right, linestyles='dashed', colors='green') pl.vlines(self.lefts, self.top, self.bottom, linestyles='dashed', colors='blue') pl.vlines(self.lefts + self.widths, self.top, self.bottom, linestyles='dashed', colors='green') for box in self.rectangles: t, l, b, r = box patch = pl.Rectangle((l, t), r - l, b - t, color='blue', fill=True, alpha=0.5) ax.add_patch(patch) pass
def __init__(self, n, handicap=0): self.welcome() self.n = n self.handicap = handicap self.board = [np.zeros((self.n, self.n))] self.f, self.ax = pylab.subplots(figsize=(8, 9)) self.ax._label = 'main' pylab.subplots_adjust(bottom=0.2) self.f.set_facecolor('tan') pylab.axes(axisbg='tan') #pylab.grid(ls='-', zorder=0) pylab.vlines(np.arange(self.n - 1), 0, self.n - 1, zorder=-1) pylab.hlines(np.arange(self.n - 1), 0, self.n - 1, zorder=-1) pylab.xticks(np.arange(self.n)) pylab.yticks(np.arange(self.n)) pylab.xlim(-0.5, self.n - 0.5) pylab.ylim(-0.5, self.n - 0.5) self.turn = 0 self.marker = 1 # 1 = black, -1 = white self.score = [[0, 0]] # Captured stones (negative is bad) self.territory = [0, 0] # Enclosed territory (positive is good)
def figOne(N,mus = [.2,.5,.8],variances=np.square([.1,.1,.1])): D = sampleData(mus,variances,N) ff.niceGraph() pl.xlim(0,1.5) c005Inference = makeInferenceForPlotting(N,0.01,D=D) c05Inference = makeInferenceForPlotting(N,1.,D=D) c5Inference = makeInferenceForPlotting(N,5.,D=D) c50Inference = makeInferenceForPlotting(N,10.,D=D) plotTrain(D,mus,variances,xBottom=.048) for d in range(len(D)): pl.text(D[d], .044, '*',fontsize=14) pl.hlines(0.045,0,1.5,lw=1.,linestyle=":") plotInference(D,c005Inference[1],c005Inference[2],xBottom=0,colour="#0000FF",alpha=.75) plotInference(D,c05Inference[1],c05Inference[2],xBottom=.01,colour="#EAAF0F",alpha=.75) plotInference(D,c5Inference[1],c5Inference[2],xBottom=.02,colour="#66CD00",alpha=.7) plotInference(D,c50Inference[1],c50Inference[2],xBottom=.03,colour="#FF1493",alpha=.65) pl.text(-.17,0+.00005,r'$\alpha=.01$',size=11) pl.text(-.15,0.01+.00005,r'$\alpha=1$',size=11) pl.text(-.15,0.02+.00005,r'$\alpha=5$',size=11) pl.text(-.1605,0.03+.00005,r'$\alpha=10$',size=11) pl.text(0.3,.04,'Inferred Categories',size=11) pl.text(0.2,.056,'True Underlying Categories',size=11) pl.text(-.12,.045,r'$x_i$',size=11) pl.xlabel(r'$f$',size=11) return D
def lum_incl_plot(): global ell, modes, colors, bfile, base, par, mag, freqs, incl, static_i, fixed_observer, observer_i, mass, vel for i in range(len(modes)): #plt.plot([freqs[i],0],[freqs[i],mag[i][0,2]/base]) #plt.plot([[freqs[i],0],[freqs[i],1]]) tmp = [] for j in range(len(incl)): if fixed_observer == True: tmp.append((m_mag[i][j][4] - base[static_i[observer_i]]) / base[static_i[observer_i]]) else: tmp.append((m_mag[i][j][4] - base[j]) / base[j]) plt.plot(incl, (np.array(tmp))) plt.text(incl[0] + 2, np.abs(np.array(tmp))[0], r"$\ell$=" + str(c_modes[i].split()[0])) plt.hlines(0, 0, 90) plt.xlabel(r"Inclination (deg)") plt.ylabel(r"$\Delta L/L$") if (fixed_observer == True): plt.title(r"M=" + mass + ", V=" + vel + " - $L$ fixed at $i$=" + str(static_i[observer_i])) else: plt.title(r"M=" + mass + ", V=" + vel + " - $L$ observer") plt.grid()
def plot_force_error(configs, ref_configs, force_name='force', force_ref_name='force', *plot_args, **plot_kwargs): """ Plot force error between Atoms sequences `configs` and `ref_configs` """ ref_force = np.hstack(getattr(ref_configs, force_ref_name)) ref_force = ref_force.reshape(ref_force.size, order='F') force = np.hstack(getattr(configs, force_name)) force = force.reshape(force.size, order='F') plot(abs(force - ref_force), *plot_args, **plot_kwargs) xlim(0, len(force)) if hasattr(ref_configs, 'config_type'): ct = list( np.hstack([[at.config_type] * 3 * at.n for at in ref_configs])) label_axes_with_config_types(ct) names = sorted(set(ct)) for name in names: start = ct.index(name) stop = len(ct) - ct[::-1].index(name) this_force = force[start:stop] this_ref_force = ref_force[start:stop] rms_error = ((this_force - this_ref_force)**2).mean()**0.5 hlines(rms_error, start, stop, lw=3, color='r')
def diffplot_t_of_c(density=4.5, columns=np.linspace(12,15), temperatures=[25,50,75,100,125,150]): grid_exp = np.empty([len(columns), len(temperatures)]) grid_ML = np.empty([len(columns), len(temperatures)]) for icol, column in enumerate(ProgressBar(columns)): for item, temperature in enumerate(temperatures): constraints,mf,density,column,temperature = make_model(density=density, temperature=temperature, column=column) grid_exp[icol,item] = constraints['expected_temperature'] grid_ML[icol,item] = constraints['temperature_chi2'] pl.figure(1).clf() for ii,(tem,color) in enumerate(zip(temperatures,('r','g','b','c','m','orange'))): pl.plot(columns, grid_exp[:,ii], color=color) pl.plot(columns, grid_ML[:,ii], '--', color=color) pl.hlines(tem, columns.min(), columns.max(), label='T={0}K'.format(tem), color=color) pl.plot([], 'k', label='Expectation Value') pl.plot([], 'k--', label='Maximum Likelihood') pl.xlabel("log N(H$_2$CO) [cm$^{-2}$]") pl.ylabel("Temperature (K)") pl.legend(loc='best', fontsize=14) pl.figure(2).clf() for ii,(tem,color) in enumerate(zip(temperatures,('r','g','b','c','m','orange'))): pl.plot(columns, (grid_exp[:,ii]-tem)/tem, color=color, label='T={0}K'.format(tem)) pl.plot(columns, (grid_ML[:,ii]-tem)/tem, '--', color=color) pl.plot([], 'k', label='Expectation Value') pl.plot([], 'k--', label='Maximum Likelihood') pl.xlabel("log N(H$_2$CO) [cm$^{-2}$]") pl.ylabel("Fractional Difference\n(recovered-input)/input") pl.legend(loc='best', fontsize=14) pl.ylim(-0.5,0.5) pl.grid() return columns, grid_exp, grid_ML
def centroidChangeband(side=None): """ This code calculate the centroid change of stars at different positions of the FP as the band filter changes """ Nccd = len(side) xmmg = np.zeros(Nccd) ymmg = np.zeros(Nccd) xceng = np.zeros(Nccd) yceng = np.zeros(Nccd) xmmr = np.zeros(Nccd) ymmr = np.zeros(Nccd) xcenr = np.zeros(Nccd) ycenr = np.zeros(Nccd) xmmi = np.zeros(Nccd) ymmi = np.zeros(Nccd) xceni = np.zeros(Nccd) yceni = np.zeros(Nccd) xmmz = np.zeros(Nccd) ymmz = np.zeros(Nccd) xcenz = np.zeros(Nccd) ycenz = np.zeros(Nccd) ccdname = [] for i in range(Nccd): print i xmmg[i],ymmg[i],xceng[i],yceng[i] = centroidChange(ccd=side[i], filter='g') xmmr[i],ymmr[i],xcenr[i],ycenr[i] = centroidChange(ccd=side[i], filter='r') xmmi[i],ymmi[i],xceni[i],yceni[i] = centroidChange(ccd=side[i], filter='i') xmmz[i],ymmz[i],xcenz[i],ycenz[i] = centroidChange(ccd=side[i], filter='z') ccdname.append(side[i][0]) xrg = xcenr - xceng xig = xceni - xceng xzg = xcenz - xceng yrg = ycenr - yceng yig = yceni - yceng yzg = ycenz - yceng pl.subplot(2,1,1) pl.plot(xrg*1000./15.,'b.',label='r-band vs. g-band') pl.plot(xig*1000./15.,'r.',label='i-band vs. g-band') pl.plot(xzg*1000./15.,'g.',label='z-band vs. g-band') pl.xticks(np.arange(Nccd),ccdname) pl.xlabel('CCD position') pl.ylabel('x centroid difference (Pixels)') pl.legend(loc='best') pl.hlines(0,-1,31,linestyle='dashed',colors='k') pl.xlim(-1,31) pl.ylim(-1.5,1.5) pl.subplot(2,1,2) pl.plot(yrg*1000./15.,'b.',label='r-band vs. g-band') pl.plot(yig*1000./15.,'r.',label='i-band vs. g-band') pl.plot(yzg*1000./15.,'g.',label='z-band vs. g-band') pl.xticks(np.arange(Nccd),ccdname) pl.xlabel('CCD position') pl.ylabel('y centroid difference (Pixels)') pl.legend(loc='best') pl.hlines(0,-1,31,linestyle='dashed',colors='k') pl.xlim(-1,31) pl.ylim(-1.5,1.5) return '--- done!---'
def plot_benchmark1(): """Plot various quantities obtained for varying values of alpha.""" parameters = dict(n_var=200, n_tasks=5, density=0.15, tol=1e-2, # max_iter=50, min_samples=100, max_samples=150) cache_dir = get_cache_dir(parameters, output_dir=output_dir) gt = get_ground_truth(cache_dir) gt['precisions'] = np.dstack(gt['precisions']) emp_covs, n_samples = empirical_covariances(gt['signals']) n_samples /= n_samples.sum() alpha = [] objective = [] log_likelihood = [] ll_penalized = [] sparsity = [] kl = [] true_covs = np.empty(gt['precisions'].shape) for k in range(gt['precisions'].shape[-1]): true_covs[..., k] = np.linalg.inv(gt['precisions'][..., k]) for out in iter_outputs(cache_dir): alpha.append(out['alpha']) objective.append(- out['objective'][-1]) ll, llpen = group_sparse_scores(out['precisions'], n_samples, true_covs, out['alpha']) log_likelihood.append(ll) ll_penalized.append(llpen) sparsity.append(1. * (out['precisions'][..., 0] != 0).sum() / out['precisions'].shape[0] ** 2) kl.append(distance(out['precisions'], gt['precisions'])) gt["true_sparsity"] = (1. * (gt['precisions'][..., 0] != 0).sum() / gt['precisions'].shape[0] ** 2) title = (("n_var: {n_var}, n_tasks: {n_tasks}, " + "true sparsity: {true_sparsity:.2f} " + "\ntol: {tol:.2e} samples: {min_samples}-{max_samples}").format( true_sparsity=gt["true_sparsity"], **parameters)) plot(alpha, objective, label="objective", title=title) plot(alpha, log_likelihood, label="log-likelihood", new_figure=False) plot(alpha, ll_penalized, label="penalized L-L", new_figure=False) plot(alpha, sparsity, label="sparsity", title=title) pl.hlines(gt["true_sparsity"], min(alpha), max(alpha)) plot(alpha, kl, label="distance", title=title) pl.show()
def myPlot(X,fun,X0,funp,c1,c2): p.figure(figsize=(10,6)) F=do(f,X) p.plot(X0,funp,c1+'o-',lw=2,) p.vlines(X0,0,funp,linestyle='dotted') p.hlines(0,0,1) p.xticks(X0,['$x_{%s}$'%i for i in range(len(X0))],fontsize='large') p.yticks([]) p.ylabel('$f(x)$',fontsize='large') p.axis([X0[0],X0[-1],0,F.max()+0.1])
def plot_peak(self, x, peaks, properties): plt.plot(x) plt.plot(peaks, x[peaks], "x") plt.vlines(x=peaks, ymin=x[peaks] - properties["prominences"], ymax=x[peaks], color="C1") plt.hlines(y=properties["width_heights"], xmin=properties["left_ips"], xmax=properties["right_ips"], color="C1") plt.show()
def density_graph_charges(): #filenames filename_svg = os.getcwd() + '/' + str( args.output_folder) + '/density_profile_charges.svg' filename_png = os.getcwd() + '/' + str( args.output_folder) + '/density_profile_charges.png' #create figure fig = plt.figure(figsize=(8, 6.2)) fig.suptitle("Charge density profile along z") #plot data ax = fig.add_subplot(111) plt.plot(bins_labels, charge_density_stats["avg"] / float(np.average(vols)), color='k', linewidth=2) plt.vlines(lower_avg, min(charge_density_stats["avg"] / float(np.average(vols))), max(charge_density_stats["avg"] / float(np.average(vols))), linestyles='dashed') plt.vlines(upper_avg, min(charge_density_stats["avg"] / float(np.average(vols))), max(charge_density_stats["avg"] / float(np.average(vols))), linestyles='dashed') plt.vlines(0, min(charge_density_stats["avg"] / float(np.average(vols))), max(charge_density_stats["avg"] / float(np.average(vols))), linestyles='dashdot') plt.hlines(0, min(bins_labels), max(bins_labels)) plt.xlabel('z distance to bilayer center [$\AA$]') plt.ylabel('average charge density [$e.\AA^{-3}$]') #save figure ax.set_xlim(min(bins_labels), max(bins_labels)) #ax.set_ylim(min_density_charges, max_density_charges) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.xaxis.set_major_locator(MaxNLocator(nbins=10)) ax.yaxis.set_major_locator(MaxNLocator(nbins=7)) ax.xaxis.labelpad = 20 ax.yaxis.labelpad = 20 plt.setp(ax.xaxis.get_majorticklabels(), fontsize="small") plt.setp(ax.yaxis.get_majorticklabels(), fontsize="small") plt.subplots_adjust(top=0.9, bottom=0.15, left=0.15, right=0.85) fig.savefig(filename_png) fig.savefig(filename_svg) plt.close() return
def plot_comparison(self, target_rate, kwargs): """Call plot_curves for various cutoff methods.""" xlim = kwargs.get('xlim') ylim = kwargs.get('ylim') s = kwargs.get('s',1) pylab.clf() # tar = str(target_rate) # print (tar) # result_set.writelines(target_rate) result_set.write(str('WOO')) result_set.write(str(target_rate)+"\n") print('WOO', target_rate) opt_point = self.data.two_sided_optimum(target_rate) pylab.subplot(121) demog_label = ('cutoffs', self.data.demographic_cutoffs(target_rate, True), dict(marker='v',label='Demography', color='orange', s=70)) self.plot_curves([ # demog_label, ]) pylab.legend(loc='lower right') pylab.title("Per-group ROC curve\nclassifying %(success_people)s using %(score)s" % self.labels, **titlekws) if xlim and ylim: pylab.hlines(ylim[0], xlim[0], xlim[1], linestyle='-', linewidth=1) pylab.vlines(xlim[1], ylim[0], ylim[1], linestyle='-', linewidth=1) pylab.hlines(ylim[1], xlim[0], xlim[1], linestyle='-', linewidth=1) pylab.vlines(xlim[0], ylim[0], ylim[1], linestyle='-', linewidth=1) pylab.plot([0,1],[0,1], lw=1,color='k', linestyle='-') pylab.subplot(122) # a = 10 print('Demog:', self.data.demographic_cutoffs(target_rate, True)) result_set.write(str(('Demog:', self.data.demographic_cutoffs(target_rate, True)))+"\n") print('Opportunity:', self.data.opportunity_cutoffs(target_rate, True)) result_set.write(str(('Opportunity:', self.data.opportunity_cutoffs(target_rate, True)))+"\n") self.plot_curves([('cutoffs', self.data.profit_cutoffs(target_rate), dict(marker='^',label='Max profit', s=70*s)), ('cutoffs', self.data.fixed_cutoffs(target_rate, True), dict(label='Single threshold', marker='o', color='g',s=100)), # demog_label, ('y', self.data.get_best_opportunity(target_rate), dict(marker='x',label='Opportunity', s=130*s, color='purple')), ('xy', ([opt_point[1]], [opt_point[0]]), dict(marker='+', label='Equal odds', s=180*s, color='brown', zorder=4, linewidth=3)), ], regular_labels=False) pylab.legend(loc='lower right', scatterpoints=1, fontsize='small') pylab.title("Zoomed in view", **titlekws) pylab.tight_layout() pylab.plot([0,1],[0,1], lw=1,color='k', linestyle='-') pylab.xlim(xlim) pylab.ylim(ylim) result_set.flush();
def plot_facade_cuts(self): facade_sig = self.facade_edge_scores.sum(0) facade_cuts = find_facade_cuts( facade_sig, dilation_amount=self.facade_merge_amount) mu = np.mean(facade_sig) sigma = np.std(facade_sig) w = self.rectified.shape[1] pad = 10 gs1 = pl.GridSpec(5, 5) gs1.update(wspace=0.5, hspace=0.0) # set the spacing between axes. pl.subplot(gs1[:3, :]) pl.imshow(self.rectified) pl.vlines(facade_cuts, *pl.ylim(), lw=2, color='black') pl.axis('off') pl.xlim(-pad, w + pad) pl.subplot(gs1[3:, :], sharex=pl.gca()) pl.fill_between(np.arange(w), 0, facade_sig, lw=0, color='red') pl.fill_between(np.arange(w), 0, np.clip(facade_sig, 0, mu + sigma), color='blue') pl.plot(np.arange(w), facade_sig, color='blue') pl.vlines(facade_cuts, facade_sig[facade_cuts], pl.xlim()[1], lw=2, color='black') pl.scatter(facade_cuts, facade_sig[facade_cuts]) pl.axis('off') pl.hlines(mu, 0, w, linestyle='dashed', color='black') pl.text(0, mu, '$\mu$ ', ha='right') pl.hlines( mu + sigma, 0, w, linestyle='dashed', color='gray', ) pl.text(0, mu + sigma, '$\mu+\sigma$ ', ha='right') pl.xlim(-pad, w + pad)
def fwhm_whisker_plot(stampImgList=None,bkgList=None,sigma=1.1/scale): whk,fwhm = get_fwhm_whisker_list(stampImgList,bkgList,sigma=sigma) whk=list(whk.T) fwh=list(fwhm.T) pl.figure(figsize=(7,5)) pl.boxplot(whk) pl.hlines(0.2,0,3,linestyle='solid',color='g') pl.ylim(0.,.4) pl.xticks(np.arange(1,3),['whisker_Wmoments','whisker_Amoments']) pl.figure(figsize=(12,5)) pl.boxplot(fwh) pl.ylim(0.4,1.5) pl.hlines(0.9,0,6,linestyle='solid',color='g') pl.xticks(np.arange(1,6),['fwhm_weighted', 'fwhm_Amoments','fwhm_moffat', 'fwhm_gauss','fwhm_sech2']) return '-----done !----'
def plot_encoded(t, u, s, fig_title='', file_name=''): """ Plot a time-encoded signal. Parameters ---------- t : ndarray of floats Times (in s) at which the original signal was sampled. u : ndarray of floats Signal samples. s : ndarray of floats Intervals between encoded signal spikes. fig_title : string Plot title. file_name : string File in which to save the plot. Notes ----- The spike times (i.e., the cumulative sum of the interspike intervals) must all occur within the interval `t-min(t)`. """ dt = t[1] - t[0] cs = np.cumsum(s) if cs[-1] >= max(t) - min(t): raise ValueError('some spike times occur outside of signal' 's support') p.clf() p.gcf().canvas.set_window_title(fig_title) p.axes([0.125, 0.3, 0.775, 0.6]) p.vlines(cs + min(t), np.zeros(len(cs)), u[np.asarray(cs / dt, int)], 'b') p.hlines(0, 0, max(t), 'r') p.plot(t, u, hold=True) p.xlabel('t (s)') p.ylabel('u(t)') p.title(fig_title) p.gca().set_xlim(min(t), max(t)) a = p.axes([0.125, 0.1, 0.775, 0.1]) p.plot(cs + min(t), np.zeros(len(s)), 'ro') a.set_yticklabels([]) p.xlabel('%d spikes' % len(s)) p.gca().set_xlim(min(t), max(t)) p.draw_if_interactive() if file_name: p.savefig(file_name)
def replot(d, w=2, column=0, color='b'): global tvec axi = axit[column] if len(tvec) != len(d[0][1]): tvec = h.Vector(len(d[0][1])).indgen(h.dt) for ax in axi: ax.clear() for ax in axi: ax.set_ylim(-120, 50) for ax, d1 in zip(axi, d): ax.plot(tvec, d1[1], linewidth=w, color=color) ax.set_axis_off() # https://matplotlib.org/users/text_props.html if column == 0: ax.text(0, 0, '%d%%' % d1[0], fontsize=14, ha='right', va='top') plt.vlines(600, 0, 50) plt.hlines(0, 550, 600)
def plot(mode): """ plot range """ xmin, xmax, ymin, ymax = (-2, 2, -1, 3) fig = pl.figure() fig.subplots_adjust(left=0.15) ax = pl.subplot(1,1,1) interval = 0.5 offset = 0.05 """ move ticks""" pl.xticks(offset + np.arange(xmin, xmax+1, interval), np.arange(xmin, xmax+interval+1, interval)) pl.yticks(offset + np.arange(ymin, ymax+1, interval), np.arange(ymin, ymax+interval+1, interval)) pl.ylim([ymin,ymax]) """ axis """ pl.hlines([0], xmin, xmax, linestyles="dashed") pl.vlines([0], ymin, ymax, linestyles="dashed") """ label """ pl.xlabel("x", style='italic', fontsize=25) pl.ylabel("l'(x)", style='italic', fontsize=25) """ title """ pl.title(mode, fontdict={'size':28}) X = np.linspace(xmin, xmax, 256, endpoint=True) """ plot funcitons """ if mode == "(b)": pl.plot(X, exp(X), "--r", linewidth=5) pl.plot(X, hinge(X), "-b", linewidth=5) #pl.plot(X, logistic(X), linewidth=3, color="y") elif mode == "(a)": pl.plot(X, sigmoid(X), "-b", linewidth=5) pl.plot(X, ramp(X), "--r", linewidth=5) for i,item in enumerate(ax.get_xticklabels()): fontsize = 20 item.set_fontsize(fontsize) for i,item in enumerate(ax.get_yticklabels()): fontsize = 20 item.set_fontsize(fontsize) pl.show()
def plot_encoded(t, u, s, fig_title='', file_name=''): """ Plot a time-encoded signal. Parameters ---------- t : ndarray of floats Times (in s) at which the original signal was sampled. u : ndarray of floats Signal samples. s : ndarray of floats Intervals between encoded signal spikes. fig_title : string Plot title. file_name : string File in which to save the plot. Notes ----- The spike times (i.e., the cumulative sum of the interspike intervals) must all occur within the interval `t-min(t)`. """ dt = t[1]-t[0] cs = np.cumsum(s) if cs[-1] >= max(t)-min(t): raise ValueError('some spike times occur outside of signal''s support') p.clf() p.gcf().canvas.set_window_title(fig_title) p.axes([0.125, 0.3, 0.775, 0.6]) p.vlines(cs+min(t), np.zeros(len(cs)), u[np.asarray(cs/dt, int)], 'b') p.hlines(0, 0, max(t), 'r') p.plot(t, u, hold=True) p.xlabel('t (s)') p.ylabel('u(t)') p.title(fig_title) p.gca().set_xlim(min(t), max(t)) a = p.axes([0.125, 0.1, 0.775, 0.1]) p.plot(cs+min(t), np.zeros(len(s)), 'ro') a.set_yticklabels([]) p.xlabel('%d spikes' % len(s)) p.gca().set_xlim(min(t), max(t)) p.draw_if_interactive() if file_name: p.savefig(file_name)
def plot_pair(self, target): """Plots performance with raw=True and raw=False in two subplots.""" pylab.clf() pylab.figure(figsize=(10, 5)) pylab.subplot(121) self.plot_performance(raw=True) pylab.hlines(target * 100, self.data.cdfs.index.min(), self.data.cdfs.index.max(), linewidth=1, colors='k') pylab.subplot(122) self.plot_performance() pylab.hlines(target * 100, 0, 100, linewidth=1, colors='k') pylab.tight_layout() pylab.savefig(FIGURE_DIR + 'credit_performance.svg') pylab.show()
def plot_lightcurve(self, show=False, save=False): """ plot the lightcurve for a given star """ mean = np.mean(self.m) std = np.std(self.m) plt.hlines(mean, min(self.t), max(self.t), linestyle='--') plt.ylim(mean + std * 3, mean - std * 3) plt.xlim(min(self.t), max(self.t)) plt.grid() plt.title(self.starid + ' = star #' + str(self['tab'])) plt.xlabel('days') plt.ylabel('mag') plt.scatter(self.t, self.m, edgecolor='none') plt.plot(self.t, self.m, 'gray') plt.minorticks_on()
def ex1_2_2(): oldX = changeLen([1, -2, 4, 6, -5, 8, 10], -20, 20) a = xl(oldX, -20) aPre = [2*np.exp(0.5*i) for i in xrange(-20, 21)] a.mul(aPre) b = xl(oldX, -20) bPre = [np.cos(0.1*np.pi*i) for i in xrange(-20, 21)] b.shitf(2) b.mul(bPre) c = a + b x,y = np.array([i for i in xrange(c.indexOfStart, c.indexOfEnd+1)]), np.array(c.date) plt.scatter(x, y) plt.vlines(x, [0], y) plt.hlines(0, x[0]-1, x[x.shape[0]-1]+1) plt.ylim(-20, 60) plt.xlim(-20, 20) plt.show()
def plot_lightcurve(self): """ plot the lightcurve for a given star """ mean = np.mean(self.m) std = np.std(self.m) plt.hlines(mean,min(self.t),max(self.t),linestyle='--') plt.ylim(mean+std*3,mean-std*3) plt.xlim(min(self.t),max(self.t)) plt.grid() plt.title(self.starid) plt.xlabel('days') plt.ylabel('mag') plt.scatter(self.t, self.m, edgecolor='none') #plt.show() plt.savefig('/work1/jwe/Dropbox/Documents/Talks/AIP2014a/lightcurve.pdf') plt.close()
def fwhm_whisker_plot(stampImgList=None, bkgList=None, sigma=1.1 / scale): whk, fwhm = get_fwhm_whisker_list(stampImgList, bkgList, sigma=sigma) whk = list(whk.T) fwh = list(fwhm.T) pl.figure(figsize=(7, 5)) pl.boxplot(whk) pl.hlines(0.2, 0, 3, linestyle='solid', color='g') pl.ylim(0., .4) pl.xticks(np.arange(1, 3), ['whisker_Wmoments', 'whisker_Amoments']) pl.figure(figsize=(12, 5)) pl.boxplot(fwh) pl.ylim(0.4, 1.5) pl.hlines(0.9, 0, 6, linestyle='solid', color='g') pl.xticks(np.arange(1, 6), [ 'fwhm_weighted', 'fwhm_Amoments', 'fwhm_moffat', 'fwhm_gauss', 'fwhm_sech2' ]) return '-----done !----'
def plot_samples(S, axis_list=None): pl.scatter(S[:, 0], S[:, 1], s=2, marker="o", linewidths=0, zorder=10) if axis_list is not None: colors = [(0, 0.6, 0), (0.6, 0, 0)] for color, axis in zip(colors, axis_list): axis /= axis.std() x_axis, y_axis = axis # Trick to get legend to work pl.plot(0.1 * x_axis, 0.1 * y_axis, linewidth=2, color=color) # pl.quiver(x_axis, y_axis, x_axis, y_axis, zorder=11, width=0.01, pl.quiver(0, 0, x_axis, y_axis, zorder=11, width=0.01, scale=6, color=color) pl.hlines(0, -3, 3) pl.vlines(0, -3, 3) pl.xlim(-3, 3) pl.ylim(-3, 3) pl.xlabel("x") pl.ylabel("y")
def plot_pair(self, cutoffs, target, titles=[None,None], show_loss=False): """Plots performance with raw=True and raw=False in two subplots.""" kws = {} if show_loss: pc = self.data.profit_cutoffs(target) kws.update(dict(othercutoffs=pc, otherthreshold=target)) if isinstance(titles, str): titles = [titles + ' (raw score)', titles + ' (per-group)'] pylab.clf() pylab.subplot(121) self.plot_performance(cutoffs=cutoffs, raw=True, **kws) pylab.hlines(target*100, self.data.cdfs.index.min(), self.data.cdfs.index.max(), linewidth=1, colors='k') pylab.title(titles[0], **titlekws) pylab.subplot(122) self.plot_performance(cutoffs=cutoffs, **kws) pylab.hlines(target*100, 0, 100, linewidth=1, colors='k') pylab.title(titles[1], **titlekws) pylab.tight_layout()
def plot_samples(S, axis_list=None): pl.scatter(S[:, 0], S[:, 1], s=2, marker='o', linewidths=0, zorder=10, color='steelblue', alpha=0.5) if axis_list is not None: colors = ['orange', 'red'] for color, axis in zip(colors, axis_list): axis /= axis.std() x_axis, y_axis = axis # Trick to get legend to work pl.plot(0.1 * x_axis, 0.1 * y_axis, linewidth=2, color=color) pl.quiver(0, 0, x_axis, y_axis, zorder=11, width=0.01, scale=6, color=color) pl.hlines(0, -3, 3) pl.vlines(0, -3, 3) pl.xlim(-3, 3) pl.ylim(-3, 3) pl.xlabel('x') pl.ylabel('y')
def calc_apcorr(file): ''' MEASURE APPERTURE CORRECTION GIVEN TWO MAGNITUDES''' ''' file -- daophot filename (expects only 2 circular aperture magnitude estimates in file)''' # Save a trimmed daophot catalog with columns relevant to this study (xc,yc,mag1,mag2) trimfile = file+'.trimmed' file_query = os.access(trimfile, os.R_OK) if file_query == True: os.remove(trimfile) # remove previous trimmed files iraf.txdump(file,'xcenter,ycenter,mag', 'yes', Stdout=trimfile) # Measure the aperture correction assuming a pt source xc, yc, mag1,mag2 = np.loadtxt(trimfile, unpack=True) deltamag=mag1-mag2 # Use somewhat hacky method to extract box in mag.vs.deltamag plot where we will estimate median deltamag xgd=[21.8,25.0] # fixed--works well for both filters #estimate y-range from a rough median estimate tmp_median = np.median(deltamag[(mag1 >= xgd[0])&(mag1 <= xgd[1])&(np.abs(deltamag) < 1)]) ygd=[tmp_median-0.1, tmp_median+0.1] f_deltamag=deltamag[(mag1 >= xgd[0])&(mag1 <= xgd[1])&(deltamag > ygd[0])&(deltamag <ygd[1])] # avoid saturated and faint sources ac05 = np.median(f_deltamag) # Plot the aperture correction on delta_mag vs. mag scatter diagram pylab.scatter(mag1, deltamag,s=1.0,c='r',marker='o') pylab.ylim(-0.5,1.0) pylab.xlim(19.0,29.0) pylab.xlabel('m3') pylab.ylabel('m3 - m16') pylab.axhline(0.0, c='k', ls='--', linewidth=3) pylab.axhline(ac05) pylab.vlines(xgd,ygd[0],ygd[1], colors='red',linestyles='dotted') pylab.hlines(ygd,xgd[0],xgd[1], colors='red',linestyles='dotted') pylab.annotate('ac05='+str(ac05),[19.3,ac05-0.07]) pylab.annotate('m_corr = m1 - ac05 - AC05',[19.3,-0.4]) fsplit=file.split('_') pylab.annotate(fsplit[0], [20.0,-0.2],color='r') pylab.savefig('deltamag_vs_mag_'+fsplit[0]+'.pdf') pylab.clf() return ac05
def plot(self, bgimage=None): import pylab as pl self._plot_background(bgimage) ax = pl.gca() y0, y1 = pl.ylim() # r is the width of the thick line we use to show the facade colors r = 5 patch = pl.Rectangle((self.facade_left + r, self.sky_line + r), self.width - 2 * r, self.door_line - self.sky_line - 2 * r, color=self.color, fill=False, lw=2 * r) ax.add_patch(patch) pl.text((self.facade_right + self.facade_left) / 2., (self.door_line + self.sky_line) / 2., '$\sigma^2={:0.2f}$'.format(self.uncertainty_for_windows())) patch = pl.Rectangle((self.facade_left + r, self.door_line + r), self.width - 2 * r, y0 - self.door_line - 2 * r, color=self.mezzanine_color, fill=False, lw=2 * r) ax.add_patch(patch) # Plot the left and right edges in yellow pl.vlines([self.facade_left, self.facade_right], self.sky_line, y0, colors='yellow') # Plot the door line and the roof line pl.hlines([self.door_line, self.sky_line], self.facade_left, self.facade_right, linestyles='dashed', colors='yellow') self.window_grid.plot()
def PlotTemp(md_list): """ First function to analyze the results of the activation threshold""" close(3) figure(3) xlim((-1, 62)) hlines(0, -1, 62) ylim((-0.3, 10.2)) vlines(0, -0.2, 10.2) for md in md_list: md.PlotvPar( par=1, position=md.data_other['Time'], alpha=0.9,\ color=color[md.experiment][0], linewidth=2) x, y = [], [] for d in md.d: x += [[md.data_other['Time']] * len(d.y)] y += [log10(d.y * d.mult_factors / d.Sc + 1)] plot( x, y, ' ', marker=color[md.experiment][1], markersize=4,\ color=color[md.experiment][0]) ylabel(md.unit) xlabel(r"$min$") savefig("Images/All.png")
def simulation(recipe, curvNo, noIndicators): worker = recipe.getWorker("ThicknessModeller") simulation = worker.plugCalcAbsorption.getResult() worker = recipe.getWorker("AddColumn") table = worker.plugCompute.getResult(subscriber=TextSubscriber("Add Column")) thickness = table[u"thickness"] index = curvNo2Index(table[u"pixel"], curvNo) worker = recipe.getWorker("MRA Exp") minimaPos = worker.plugMra.getResult()[r'\lambda_{min}'].inUnitsOf(simulation.dimensions[1]) maximaPos = worker.plugMra.getResult()[r'\lambda_{max}'].inUnitsOf(simulation.dimensions[1]) visualizer = ImageVisualizer(simulation, False) ordinate = simulation.dimensions[1].data if not noIndicators: pylab.hlines(thickness.data[index],ordinate.min(),ordinate.max(), label ="$%s$"%minimaPos.shortname) abscissae = simulation.dimensions[0].data pylab.vlines(minimaPos.data[:,index],abscissae.min(),abscissae.max(), label ="$%s$"%minimaPos.shortname) pylab.vlines(maximaPos.data[:,index],abscissae.min(),abscissae.max(), label ="$%s$"%maximaPos.shortname)
def plot_effmass_with_fit(cfnc, ti, tf, T, save=False, name='', title=None, yrange=[]): "Also show the mass determined from a fit." effmass = naive_effmass(cfnc) ave, sigma = effmass[0], JKsigma(effmass) fit = fit_twopoint_cfuns(cfnc, ti, tf, T) m, sigm = fit[0][1], fit[1][1] p.figure() if title is not None: p.title(title) if yrange: p.ylim(yrange) p.xlabel('$t$') p.ylabel('$|\\frac{C[t+1]}{C[t]}|$') p.errorbar(range(len(ave)), ave, sigma, fmt='ko') p.hlines([m-sigm, m+sigm], ti, tf, colors='r') #p.axhspan((m-sigm), (m+sigm), facecolor=(1.0,0.0,0.0), alpha=0.5) if save: p.savefig(name) else: p.show()
def plotHMapEffects(s,alpha=0.1,Nsamp=1000): D = s.D Htrans = s.Htrans cpairs = zip( (['r','b','k'][i%3] for i in count(0)), zip(xrange(D),[j%D for j in xrange(1,D+1)]) ) x = sampleSCrossSD(r0=1.0,r1=0.3,D=D-1,N=Nsamp) tmpx = array(x) for h,A in zip(Htrans.H,Htrans.A): f = h.f figure(figsize=(12,12)) subplot(2,2,1) for c,(i,j) in cpairs: scatter(tmpx[:,i],tmpx[:,j],alpha=alpha,c=c) subplot(2,2,2) bt = h.computebtilde(tmpx) if bt.shape[1]==1: scatter(zeros(bt.shape[0]),bt[:,0],alpha=alpha) lnes = f.getEllipse() for l in lnes: hlines(l,-1,1) subplot(2,2,3) a = applyAffine(h.ga,tmpx[:,:h.split]) if a.shape[1]>2: scatter(a[:,0],a[:,1],alpha=alpha) else: scatter(zeros_like(a[:,0]),a[:,0],alpha=alpha) else: scatter(*bt.T,alpha=alpha) plot(*f.getEllipse()) subplot(2,2,3) a = applyAffine(h.ga,tmpx[:,:h.split]) scatter(zeros(a.shape[0]),a[:,0],alpha=alpha) subplot(2,2,4) tmpx = h(tmpx) for c,(i,j) in cpairs: scatter(tmpx[:,i],tmpx[:,j],alpha=alpha,c=c) tmpx = dot(A,tmpx.T).T
def fwhm_whisker_des_plot(stampImgList=None,bkgList=None,whkSex=None,fwhmSex=None,sigma=1.1/scale,dimmfwhm=None): whk,fwhm = get_fwhm_whisker_list(stampImgList,bkgList,sigma=sigma) whk=list(whk.T) fwh=list(fwhm.T) fwh.append(fwhmSex) whk.append(whkSex) pl.figure(figsize=(15,10)) pl.subplot(2,1,1) pl.boxplot(whk) pl.hlines(0.2,0,4,linestyle='solid',color='g') pl.ylim(np.median(whk[2])-0.3,np.median(whk[2])+0.6) pl.grid() pl.xticks(np.arange(1,4),['whisker_Wmoments','whisker_Amoments','whisker_sx']) if dimmfwhm != None: pl.title('DIMM Seeing FWHM: '+str(round(dimmfwhm,3)) +'(arcsec) sqrt(DIMM fwhm^2 + 0.55^2): '+str(round(np.sqrt(dimmfwhm**2 + 0.55**2),3))) pl.subplot(2,1,2) pl.boxplot(fwh) pl.ylim(0,np.median(fwh[5])+2) pl.grid() pl.hlines(0.9,0,7,linestyle='solid',color='g') pl.xticks(np.arange(1,7),['fwhm_weighted', 'fwhm_Amoments','fwhm_moffat', 'fwhm_gauss','fwhm_sech2','fwhm_sx']) return '-----done !----'
def plot_channel(ax, c, clusters, cluster_p_values,plot_type,full=False): for i_c, (start, stop) in enumerate(clusters): if start / n_times == c: start -= c*n_times stop -= c*n_times if cluster_p_values[i_c] <= 0.05: h = ax.axvspan(times[start], times[stop-1], color='r', alpha=0.3) else: ax.axvspan(times[start], times[stop-1], color=(0.3, 0.3, 0.3), alpha=0.3) pl.axhline(y=0,linewidth=1,color="black") if plot_type == "data": hf = ax.plot(times, -1*means0[c],"r",times,-1*means1[c],"g") if not full: pl.text(-0.035,ydata_scale*.9,ydata_scale_txt) pl.legend(hf,(cond_names[0],cond_names[1]),loc="upper right") elif plot_type == "f": hf = ax.plot(times, T_obs[c], 'g') pl.vlines(x=xt,ymin=ymarks*-1,ymax=ymarks) pl.vlines(x=xt2,ymin=np.array([0]),ymax=ymarks2,linewidth=1) pl.hlines(ydata_scale,xmark*-1,xmark) pl.xlim([0,times[lent-1]]) return hf
def myPlot2(X,fun,X0,funp,D,c1,c2): p.figure(figsize=(10,6)) F=do(f,X) d=0 dr=[0] for DD in D: if DD==1: p.plot(X0[d:d+2],funp[d:d+2],c1+'o-',lw=2,) elif DD==2: yr=p.linspace(0,1,100) xr=X0[d]+(X0[d+2]-X0[d])*yr fr=funp[d]+(funp[d+1]-funp[d])*(4.*yr*(1.0-yr))+2.0*(funp[d+2]-funp[d])*yr*(yr-0.5) p.plot(X0[d],funp[d],c1+'o',lw=2,) p.plot(xr,fr,c1+'-',lw=2,) p.plot(X0[d],funp[d],c1+'o-',lw=2,) dr.append(dr[-1]+DD) d=d+DD p.hlines(0,0,1) p.vlines(X0[dr],0,funp[dr],linestyle='dotted') p.xticks(X0[dr],['$x_{%s}$'%i for i in range(len(X0[dr]))],fontsize='large') p.yticks([]) p.ylabel('$f(x)$',fontsize='large') p.axis([X0[0],X0[-1],0,F.max()+0.1])
def plotGaussianAndSignaPoints(x_range, gaussian, sigma_points, means): # Get inputs gaussian_i = gaussian[0] gaussian_t = gaussian[1] gaussian_mc = gaussian[2] gaussian_ekf = gaussian[3] sigma_points_i = sigma_points[0] sigma_points_t = sigma_points[1] mean_ekf, mean_sigma, mean_mc = means fig = pylab.figure("Gaussian and sigma points") plot = fig.gca() # get the offset to plot in reverse rev_offset = np.min(x_range) # plot the gaussians plot.plot(x_range, gaussian_i, 'b-') plot.plot(gaussian_t, x_range + rev_offset,'g-.', label='Trans. Inodore') plot.plot(gaussian_mc[0],gaussian_mc[1][:-1] + rev_offset, 'g', label='Monte Carlo') plot.plot(gaussian_ekf,x_range + rev_offset,'g.', label=u'Linéarisation') # plot the sigma points plot.plot(sigma_points_i[:,0], sigma_points_i[:,1], 'bo') plot.plot(sigma_points_t[:,1] + np.min(x_range), sigma_points_t[:,0] + rev_offset, 'go') # plot the transformation # plot.plot(x_range, x_range + rev_offset, 'k-', linewidth = 0.5) plot.plot(x_range, transform(x_range) + rev_offset, 'k--', label='Fonction de transfert') # plot the mean values max_line = 2 pylab.hlines(mean_ekf,0, max_line, colors = 'r', linestyles='dotted') pylab.hlines(mean_sigma,0, max_line, colors = 'r', linestyles='dashdot') pylab.hlines(mean_mc,0, max_line, colors = 'r', linestyles='solid') # set plot parameters pylab.xlim([np.min(x_range),np.max(x_range)]) pylab.ylim([0,8]) pylab.legend(loc = 'upper right') plot.set_aspect('equal') pylab.title(u'Différentes méthodes de propagation') pylab.grid(True, 'both', 'both') fig.show()