def plot_masserr(self, filename): import pcolors data=eu.io.read(filename) nr200 = data.size nb = data['B'][0].size plt = FramedPlot() colors = pcolors.rainbow(nr200, 'hex') clist = [] for ri in xrange(nr200): r200 = data['r200'][ri] m200 = data['m200'][ri] p = Points(data['B'][ri], (m200-data['m200meas'][ri])/m200, type='filled circle', color=colors[ri]) crv = Curve(data['B'][ri], (m200-data['m200meas'][ri])/m200, color=colors[ri]) crv.label = 'r200: %0.2f' % r200 clist.append(crv) plt.add(p,crv) key = PlotKey(0.1,0.4,clist) plt.add(key) plt.xlabel=r'$\Omega_m \sigma_8^2 D(z)^2 b(M,z)$' plt.ylabel = r'$(M_{200}^{true}-M)/M_{200}^{true}$' epsfile = filename.replace('.rec','.eps') print 'writing eps:',epsfile plt.write_eps(eu.ostools.expand_path(epsfile))
def doplot(self): tab = Table(2, 1) tab.title = self.title xfit, yfit, gprior = self.get_prior_vals() nrand = 100000 binsize = self.binsize h = self.h h1 = self.h1 h2 = self.h2 g1rand, g2rand = gprior.sample2d(nrand) grand = gprior.sample1d(nrand) hrand = histogram(grand, binsize=binsize, min=0.0, max=1.0, more=True) h1rand = histogram(g1rand, binsize=binsize, min=-1.0, max=1.0, more=True) fbinsize = xfit[1] - xfit[0] hrand["hist"] = hrand["hist"] * float(yfit.sum()) / hrand["hist"].sum() * fbinsize / binsize h1rand["hist"] = h1rand["hist"] * float(h1["hist"].sum()) / h1rand["hist"].sum() pltboth = FramedPlot() pltboth.xlabel = r"$g$" hplt1 = Histogram(h1["hist"], x0=h1["low"][0], binsize=binsize, color="red") hplt2 = Histogram(h2["hist"], x0=h2["low"][0], binsize=binsize, color="blue") hpltrand = Histogram(hrand["hist"], x0=hrand["low"][0], binsize=binsize, color="magenta") hplt1rand = Histogram(h1rand["hist"], x0=h1rand["low"][0], binsize=binsize, color="magenta") hplt1.label = r"$g_1$" hplt2.label = r"$g_2$" hplt1rand.label = "rand" hpltrand.label = "rand" keyboth = PlotKey(0.9, 0.9, [hplt1, hplt2, hplt1rand], halign="right") pltboth.add(hplt1, hplt2, hplt1rand, keyboth) tab[0, 0] = pltboth plt = FramedPlot() plt.xlabel = r"$|g|$" hplt = Histogram(h["hist"], x0=h["low"][0], binsize=binsize) hplt.label = "|g|" line = Curve(xfit, yfit, color="blue") line.label = "model" key = PlotKey(0.9, 0.9, [hplt, line, hpltrand], halign="right") plt.add(line, hplt, hpltrand, key) tab[1, 0] = plt if self.show: tab.show() return tab
def plot_ellip_vs_input(self, show=False): ''' Plot the measured ellip as a function of the input for sigma_index=0 which is a reasonably large object ''' import biggles from biggles import PlotLabel,FramedPlot,Table,Curve,PlotKey,Points from pcolors import rainbow import pprint data = self.read() w=where1(data['sigma_index'] == 10) data = data[w] e1_input, e2_input, Tinput = util.mom2ellip(data['Irr_input'], data['Irc_input'], data['Icc_input']) e1_meas, e2_meas, Tinput = util.mom2ellip(data['Irr_meas'], data['Irc_meas'], data['Icc_meas']) einput = sqrt(e1_input**2 + e2_input**2) emeas = sqrt(e1_meas**2 + e2_meas**2) plt=FramedPlot() p = Points(einput,emeas, type='filled circle') plt.add(p) plt.xlabel=r'$\epsilon_{in}$' plt.ylabel=r'$\epsilon_{meas}$' sig=sqrt((data['Irr_meas'][0]+data['Icc_meas'][0])/2) lab1=PlotLabel(0.1,0.9,self.model, halign='left') lab2=PlotLabel(0.1,0.8,r'$\sigma: %0.2f$' % sig, halign='left') plt.add(lab1,lab2) einput.sort() c = Curve(einput, einput, color='red') c.label = r'$\epsilon_{input} = \epsilon_{meas}$' key=PlotKey(0.95,0.07,[c], halign='right') plt.add(c) plt.add(key) if show: plt.show() epsfile=self.epsfile('ellip-vs-input') print("Writing eps file:",epsfile) plt.write_eps(epsfile)
def test_xi_converge_nplk(epsfile=None): """ Test how xi converges with the number of k points per log10(k) Note we should test other convergence factors too! """ tab=Table(2,1) pltbig = FramedPlot() pltzoom = FramedPlot() pltbig.xlabel='r' pltbig.ylabel='xi(r)' pltbig.xlog=True pltbig.ylog=True pltzoom.xlabel='r' pltzoom.ylabel='xi(r)' l=Linear() r=10.0**linspace(0.0,2.3,1000) nplk_vals = [20,60,100,140,160] color_vals = ['blue','skyblue','green','orange','magenta','red'] plist=[] lw=2.4 for nplk,color in zip(nplk_vals,color_vals): print 'nplk:',nplk xi = l.xi(r, nplk=nplk) limxi = where(xi < 1.e-5, 1.e-5, xi) climxi = Curve(r,limxi,color=color,linewidth=lw) climxi.label = 'nplk: %i' % nplk pltbig.add(climxi) plist.append(climxi) w=where1(r > 50.0) cxi = Curve(r[w], xi[w], color=color, linewidth=lw) pltzoom.add(cxi) key = PlotKey(0.7,0.8, plist) pltzoom.add(key) tab[0,0] = pltbig tab[1,0] = pltzoom if epsfile is not None: tab.write_eps(epsfile) else: tab.show()
def plot_size_vs_input(self, show=False): ''' Plot recovered size vs input for ellip=0, which is ellip_index=0 ''' import biggles from biggles import PlotLabel,FramedPlot,Table,Curve,PlotKey,Points from pcolors import rainbow import pprint data = self.read() w=where1(data['ellip_index'] == 0) data = data[w] siginput = sqrt(data['Irr_input']) sigmeas = sqrt(data['Irr_meas']) pars=numpy.polyfit(siginput, sigmeas, 1) print("offset:",pars[1]) print("slope: ",pars[0]) print("IGNORING OFFSET") plt=FramedPlot() p = Points(siginput,sigmeas, type='filled circle') plt.add(p) plt.xlabel=r'$\sigma_{in}$' plt.ylabel=r'$\sigma_{meas}$' lab=PlotLabel(0.1,0.9,self.model) plt.add(lab) yfit2=pars[0]*siginput cfit2=Curve(siginput, yfit2, color='steel blue') cfit2.label = r'$%0.2f \sigma_{in}$' % pars[0] plt.add( cfit2 ) key=PlotKey(0.95,0.07,[cfit2], halign='right') plt.add(key) if show: plt.show() epsfile=self.epsfile('size-vs-input') print("Writing eps file:",epsfile) plt.write_eps(epsfile)
def _draw_background(self, context): pc = _PlotComposite() nl = self.ribs_l b = _series(-90 // 2, 90 // 2, 2 * math.pi / 180.) for l0 in _series(-nl, nl, math.pi / nl): c = Curve([l0] * len(b), b, **self.ribs_style) #c = apply( Curve, ([l0]*len(b), b), self.ribs_style ) pc.add(c) nb = self.ribs_b l = _series(-180 // 2, 180 // 2, 2 * math.pi / 180.) for b0 in _series(-nb, nb, 0.5 * math.pi / (nb + 1)): c = Curve(l, [b0] * len(l), **self.ribs_style) #c = apply( Curve, (l, [b0]*len(l)), self.ribs_style ) pc.add(c) pc.render(context)
def plot_T(self, k, T, Tc=None, Tb=None): from biggles import FramedPlot, Curve, PlotKey plt=FramedPlot() c=Curve(k, T**2) c.label = '$T^2$' plt.add(c) plist = [c] if Tc is not None: cc=Curve(k,Tc**2,color='blue') cc.label = '$Tc^2$' plt.add(cc) plist.append(cc) if Tb is not None: tmp = where(Tb < 1.e-5, 1.e-5, Tb) cb=Curve(k,tmp**2,color='red') cb.label = '$Tb^2$' plt.add(cb) plist.append(cb) plt.xlog=True plt.ylog=True plt.ylabel = '$T^2' plt.xlabel = 'k' plt.yrange = [1.e-8,1.0] plt.aspect_ratio=1 if Tc is not None or Tb is not None: key=PlotKey(0.1,0.9,plist) plt.add(key) plt.show()
def test(self, relerr=0.2,dowrite=False, epsfile=None): omega_m=0.25 z = 0.3 nfw = lensing.nfw.NFW(omega_m, z) lin = lensing.linear.Linear(omega_m=omega_m) r200=0.5 c=5.0 B=1.0 print 'generating fake data with %i%% errors' % (relerr*100,) nr = 21 logrmin=-2.0 logrmax=1.5 r = logspace(logrmin,logrmax,nr) ds = nfw.dsig(r,r200,c) + B*lin.dsig(r) dserr = ds*relerr ds += dserr*numpy.random.standard_normal(nr) if dowrite: f='~/tmp/fake-dsig.dat' print 'Writing fake data to:',f colprint(r,ds,dserr,format='%0.8f', file=f) print 'generating fine grid truth values' rtrue = logspace(logrmin,logrmax,nr*5) dstrue = nfw.dsig(rtrue,r200,c) + B*lin.dsig(rtrue) drhotrue = nfw.rho(rtrue,r200,c) + B*lin.drho(rtrue) # add linear term mnfw = nfw.m(rtrue, r200,c) mlin = lin.m(rtrue, B) mtrue = mnfw + mlin print 'Doing inversion' odict = self.invert(r,ds,dserr=dserr) tab = Table(2,2) od = lensing.plotting.plot_dsig(odict, noshow=True) # show some log-interpolated points of dsig nper = 10 for i in xrange(nr-1): amp = odict['ds_amp'][i] slope = odict['ds_slope'][i] off = odict['ds_offset'][i] x = logspace(log10(r[i]),log10(r[i+1]),nper) y = amp*x**(-slope) - off od['plt'].add(Curve(x,y,color='blue')) od['plt'].add(Curve(rtrue,dstrue,color='red')) tab[0,0] = od['plt'] # plot uncorrected with no error bar rod = lensing.plotting.plot_drho(r=odict['rdrho'], drho=odict['drho_noendc'], drhoerr=odict['drhoerr']*0, noshow=True) rod2 = lensing.plotting.add_to_log_plot(rod['plt'], odict['rdrho'], odict['drho'], odict['drhoerr'], color='blue') pnocorr = rod['p'] p = rod2['p'] pnocorr.label = 'no end correction' p.label = 'end correction' plist = [pnocorr,p] drhotrue_curve = Curve(rtrue,drhotrue,color='red') drhotrue_curve.label = 'Truth' rod['plt'].add(drhotrue_curve) plist.append(drhotrue_curve) rod['plt'].add(PlotKey(0.1,0.2,plist)) tab[0,1] = rod['plt'] # for the mass stuff # first show log-interpolated points of drho to see how # it looks rod_interp = lensing.plotting.plot_drho(odict, noshow=True) nper = 10 for i in xrange(odict['drho'].size-1): amp = odict['drho_amp'][i] slope = odict['drho_slope'][i] off = odict['drho_offset'][i] x = logspace(log10(r[i]),log10(r[i+1]),nper) y = amp*x**(-slope) - off y = where(y < 1.e-5, 1.e-5, y) rod_interp['plt'].add(Curve(x,y,color='blue')) tab[1,0] = rod_interp['plt'] mod = lensing.plotting.plot_mass(odict, noshow=True) mp = mod['p'] mp.label = 'Recovered Mass' nfw_curve = Curve(rtrue,mnfw,color='green') nfw_curve.label = 'NFW' mod['plt'].add(nfw_curve) lin_curve = Curve(rtrue,mlin,color='orange') lin_curve.label = 'linear' mod['plt'].add(lin_curve) true_curve = Curve(rtrue,mtrue,color='magenta') true_curve.label = 'True' mod['plt'].add(true_curve) #m200 = nfw.m200(r200) #m200p = Points([r200],[m200],type='cross',color='blue') #m200p.label = r'$M_{200} true' #mod['plt'].add(m200p) # now find r200 from the mass profile #mvf = MvirFinder(omega_m, z, 200) #rvir,rvir_err,mvir,mvir_err = mvf.find_mvir(odict['rmass'], # odict['mass'], # odict['masserr']) #mvp = Points([rvir],[mvir],type='filled square',color='red') #mvexp = SymErrX([rvir],[mvir],[rvir_err],color='red') #mveyp = SymErrY([rvir],[mvir],[mvir_err],color='red') #mvp.label = r'$M_{200}' #mod['plt'].add(mvp,mvexp,mveyp) #mod['plt'].add(PlotKey(0.1,0.9,[mp,true_curve,nfw_curve,lin_curve, # m200p,mvp])) mod['plt'].add(PlotKey(0.1,0.9,[mp,true_curve,nfw_curve,lin_curve])) tab[1,1] = mod['plt'] if dowrite: f='~/tmp/fake-dsig-invert.dat' print 'Writing inverted fake data to:',f colprint(odict['rdrho'], odict['drho'],odict['mass'],odict['masserr'], format='%20.8e',file=f) if epsfile is not None: print 'Writing eps file:',epsfile tab.write_eps(epsfile) else: tab.show()
def plot(self, odict, epsfile=None, show=True, overdrho=True): """ odict is the output of invert() """ tab = Table(2,2) od = lensing.plotting.plot_dsig(odict, noshow=True) # show some log-interpolated points of dsig nper = 10 r = odict['r'] for i in xrange(r.size-1): amp = odict['ds_amp'][i] slope = odict['ds_slope'][i] off = odict['ds_offset'][i] x = logspace(log10(r[i]),log10(r[i+1]),nper) y = amp*x**(-slope) - off od['plt'].add(Curve(x,y,color='blue')) tab[0,0] = od['plt'] # plot uncorrected with no error bar rod = lensing.plotting.plot_drho(r=odict['rdrho'], drho=odict['drho_noendc'], drhoerr=odict['drhoerr']*0, noshow=True) rod2 = lensing.plotting.add_to_log_plot(rod['plt'], odict['rdrho'], odict['drho'], odict['drhoerr'], color='blue') pnocorr = rod['p'] p = rod2['p'] pnocorr.label = 'no end correction' p.label = 'end correction' rod['plt'].add(PlotKey(0.1,0.2,[pnocorr,p])) tab[0,1] = rod['plt'] # for the mass stuff # first show log-interpolated points of drho to see how # it looks rod_interp = lensing.plotting.plot_drho(odict, noshow=True) nper = 10 for i in xrange(odict['drho'].size-1): amp = odict['drho_amp'][i] slope = odict['drho_slope'][i] off = odict['drho_offset'][i] x = logspace(log10(r[i]),log10(r[i+1]),nper) y = amp*x**(-slope) - off y = where(y < 1.e-5, 1.e-5, y) rod_interp['plt'].add(Curve(x,y,color='blue')) tab[1,0] = rod_interp['plt'] mod = lensing.plotting.plot_mass(odict, noshow=True) mp = mod['p'] mp.label = 'Mass Avg' odin=lensing.plotting.add_to_log_plot(mod['plt'], odict['rmass'], odict['massin'], odict['massinerr'], color='green', type='filled diamond') pin = odin['p'] pin.label = 'Mass In' mod['plt'].add(pin) odout=lensing.plotting.add_to_log_plot(mod['plt'], odict['rmass'], odict['massout'], odict['massouterr'], color='magenta', type='filled diamond') pout = odout['p'] pout.label = 'Mass Out' rhoc0 = 0.27752 mdel = (4./3.)*PI*200*rhoc0*1.e12*odict['rmass']**3 pdel = Curve(odict['rmass'],mdel,color='blue') pdel.label = r'$200 \rho_{c} V$' mod['plt'].add(pdel) mod['plt'].add(PlotKey(0.1,0.9,[mp,pin,pout,pdel])) tab[1,1] = mod['plt'] if epsfile is not None: print 'Writing to epsfile:',epsfile tab.write_eps(epsfile) if show: tab.show()
def test_fit_nfw_lin_dsig(rmin=0.01): from biggles import FramedPlot,Points,SymmetricErrorBarsY,Curve,PlotKey omega_m=0.25 z=0.25 r200 = 1.0 c = 5.0 B=10.0 rmax = 50.0 log_rmin = log10(rmin) log_rmax = log10(rmax) npts = 30 r = 10.0**linspace(log_rmin,log_rmax,npts) fitter = NFWBiasFitter(omega_m,z,r) ds = fitter.dsig(r, r200, c, B) # 10% errors dserr = 0.1*ds ds += dserr*numpy.random.standard_normal(ds.size) guess = numpy.array([r200,c,B],dtype='f8') # add 10% error to the guess guess += 0.1*guess*numpy.random.standard_normal(guess.size) res = fitter.fit(ds,dserr,guess, more=True) r200_fit=res['r200'] r200_err = res['r200_err'] c_fit=res['c'] c_err = res['c_err'] B_fit=res['B'] B_err = res['B_err'] print 'Truth:' print ' r200: %f' % r200 print ' c: %f' % c print ' B: %f' % B print 'r200_fit: %f +/- %f' % (r200_fit,r200_err) print ' c_fit: %f +/- %f' % (c_fit,c_err) print ' B_fit: %f +/- %f' % (B_fit,B_err) print 'Cov:' print res['cov'] rfine = 10.0**linspace(log_rmin,log_rmax,100) fitter2 = NFWBiasFitter(omega_m,z,rfine) yfit = fitter2.dsig(rfine, r200_fit, c_fit, B_fit) yfit_nfw = fitter2.nfw.dsig(rfine, r200_fit, c_fit) yfit_lin = fitter2.lin_dsig(rfine,B_fit) plt=FramedPlot() plt.add(Points(r,ds,type='filled circle')) plt.add(SymmetricErrorBarsY(r,ds,dserr)) cyfit = Curve(rfine,yfit,color='blue') cyfit_nfw = Curve(rfine,yfit_nfw,color='red') cyfit_lin = Curve(rfine,yfit_lin,color='orange') cyfit.label = 'Best Fit' cyfit_nfw.label = 'NFW' cyfit_lin.label = 'linear' key=PlotKey(0.1,0.3,[cyfit,cyfit_nfw,cyfit_lin]) plt.add(cyfit,cyfit_nfw,cyfit_lin,key) plt.xlabel = r'$r$ [$h^{-1}$ Mpc]' plt.ylabel = r'$\Delta\Sigma ~ [M_{sun} pc^{-2}]$' plt.xrange = [0.5*rmin, 1.5*rmax] plt.yrange = [0.5*(ds-dserr).min(), 1.5*(ds+dserr).max()] plt.xlog=True plt.ylog=True plt.show()
def test_scinv_npts(self, nplot, show=False, reload=False, type="png"): """ Test accuracy as a function of the numer of points used in the integration. """ dzl = 0.015 zlmin = 0.02 zlmax = 0.6 from biggles import Points, FramedPlot, PlotKey, Table, Histogram, Curve from time import time import lensing import pcolors if self.data is None or reload: self.load_example_data() # this is old ScinvCalculator, need to make work # with new one scalc1000 = ScinvCalculator(self.zs, dzl, zlmin, zlmax, npts=1000) nptsvals = [100, 200, 300, 400, 500, 600, 700, 800, 900] numcheck = len(nptsvals) # colors=['black','magenta','blue','green','orange','red'] colors = pcolors.rainbow(len(nptsvals), "hex") scalc = [] for npts in nptsvals: scalc.append(ScinvCalculator(self.zs, dzl, zlmin, zlmax, npts=npts)) times = numpy.zeros(numcheck, dtype="f8") time1000 = 0.0 # we'll fill this in scinv_all = numpy.zeros((numcheck, scalc1000.zlvals.size)) xlim = [0, scalc1000.zsvals.max()] for i in xrange(nplot): pz = self.data["pofz"][i] print("Doing 1000...", end="") tm0 = time() scinv1000 = scalc1000.calc_mean_scinv(pz) time1000 += time() - tm0 print("done") for j in xrange(numcheck): npts = nptsvals[j] print("%d " % npts, end="") tm0 = time() scinv_all[j, :] = scalc[j].calc_mean_scinv(pz) times[j] += time() - tm0 print("\nplotting") # plot the p(z) tab = Table(3, 1) binsize = scalc1000.zsvals[1] - scalc1000.zsvals[0] pzh = Histogram(pz, x0=scalc1000.zsvals[0], binsize=binsize) plt_pzh = FramedPlot() plt_pzh.xrange = xlim plt_pzh.xtitle = r"$z_s$" plt_pzh.ytitle = r"$P(z_s)$" plt_pzh.add(pzh) tab[0, 0] = plt_pzh # plot scinv for each npts value plt_scinv = FramedPlot() plt_scinv.xrange = xlim scinv_plots = [] for j in xrange(numcheck): npts = nptsvals[j] p = Curve(scalc[j].zlvals, scinv_all[j, :], type="solid", color=colors[j]) p.label = "npts: %d" % npts plt_scinv.add(p) scinv_plots.append(p) scinv_key = PlotKey(0.95, 0.9, scinv_plots, halign="right") plt_scinv.add(scinv_key) plt_scinv.ylabel = r"$\langle \Sigma_{crit}^{-1}(z_{lens}) \rangle$" plt_scinv.xlabel = r"$z_{lens}$" plt_scinv.yrange = [0, 2.1e-4] tab[1, 0] = plt_scinv # ratio to 1000 points plt_rat = FramedPlot() plt_rat.xrange = xlim plt_rat.yrange = [1 - 1.0e-2, 1 + 1.0e-2] rat_plots = [] for j in xrange(numcheck): npts = nptsvals[j] w = where1(scinv1000 > 0) ratio = scinv_all[j, w] / scinv1000[w] # ratio=scinv_all[j,:]/scinv1000[:] p = Curve(scalc[j].zlvals[w], ratio, type="solid", color=colors[j]) p.label = "npts: %d" % npts plt_rat.add(p) rat_plots.append(p) key = PlotKey(0.95, 0.9, rat_plots, halign="right") plt_rat.add(key) plt_rat.ylabel = r"$\langle \Sigma_{crit}^{-1} \rangle / \langle \Sigma_{crit}^{-1} \rangle_{1000}$" plt_rat.xlabel = r"$z_{lens}$" tab[2, 0] = plt_rat if show: tab.show() plotfile = self.npts_plot_file(i, type) print("writing to file:", plotfile) if type == "png": tab.write_img(1000, 1000, plotfile) else: tab.write_eps(plotfile) print("time npts=1000:", time1000) for j in xrange(numcheck): npts = nptsvals[j] print("time npts=%s: %s" % (npts, times[j]))
def test_sigmacritinv_npts(epsfile=None): """ Test accuracy of sigmacrit inv as a function of number of points """ from biggles import FramedPlot, PlotKey, PlotLabel, Curve, FramedArray, Table c1000 = Cosmo(npts=1000) c5 = Cosmo(npts=5) c4 = Cosmo(npts=4) c3 = Cosmo(npts=3) c2 = Cosmo(npts=2) tab = Table(2, 2) tab.uniform_limits = 0 tab.cellspacing = 1 p5 = FramedPlot() p5.xlabel = 'zsource' p5.ylabel = '% diff' p4 = FramedPlot() p4.xlabel = 'zsource' p4.ylabel = '% diff' p3 = FramedPlot() p3.xlabel = 'zsource' p3.ylabel = '% diff' p2 = FramedPlot() p2.xlabel = 'zsource' p2.ylabel = '% diff' l5 = PlotLabel(0.2, 0.7, 'npts = 5') p5.add(l5) l4 = PlotLabel(0.2, 0.1, 'npts = 4') p4.add(l4) l3 = PlotLabel(0.2, 0.9, 'npts = 3') p3.add(l3) l2 = PlotLabel(0.2, 0.9, 'npts = 2') p2.add(l2) colors = [ 'black', 'violet', 'blue', 'green', 'orange', 'magenta', 'firebrick', 'red' ] zlvals = numpy.arange(0.1, 0.9, 0.1) if zlvals.size != len(colors): raise ValueError("mismatch colors and zlvals") i = 0 allc5 = [] for zl in zlvals: zs = numpy.arange(zl + 0.01, 2.0, 0.01) scinv = c1000.sigmacritinv(zl, zs) scinv5 = c5.sigmacritinv(zl, zs) scinv4 = c4.sigmacritinv(zl, zs) scinv3 = c3.sigmacritinv(zl, zs) scinv2 = c2.sigmacritinv(zl, zs) curve5 = Curve(zs, 100 * (scinv - scinv5) / scinv, color=colors[i]) curve5.label = 'zlens: %0.2f' % zl allc5.append(curve5) p5.add(curve5) curve4 = Curve(zs, 100 * (scinv - scinv4) / scinv, color=colors[i]) p4.add(curve4) curve3 = Curve(zs, 100 * (scinv - scinv3) / scinv, color=colors[i]) p3.add(curve3) curve2 = Curve(zs, 100 * (scinv - scinv2) / scinv, color=colors[i]) p2.add(curve2) i += 1 key = PlotKey(0.15, 0.5, allc5) p5.add(key) tab[0, 0] = p5 tab[0, 1] = p4 tab[1, 0] = p3 tab[1, 1] = p2 tab.show() if epsfile is not None: tab.write_eps(epsfile)
def test_scinv_dz(self, beg, end, yrange=[0, 2.1e-4], show=False, reload=False, type="png"): """ Test accuracy of interpolating scinv as a function of dzl, the lens redshift spacing. """ import biggles from biggles import Points, FramedPlot, PlotKey, Table, Histogram, Curve from time import time import lensing import pcolors biggles.configure("default", "fontface", "HersheySans") biggles.configure("default", "fontsize_min", 1.3) zsmin = self.zs[0] zsmax = self.zs[-1] zlmin = 0.00 zlmax = 1.0 # dzl_vals = numpy.linspace(0.001,0.015,10) dzl_vals = numpy.linspace(0.001, 0.015, 4) nzl_vals = ((zlmax - zlmin) / dzl_vals).astype("i8") numcheck = len(dzl_vals) colors = pcolors.rainbow(numcheck, "hex") scalc = [] for nzl in nzl_vals: s = ScinvCalculator(zlmin, zlmax, nzl, zsmin, zsmax, npts=100) scalc.append(s) times = numpy.zeros(numcheck, dtype="f8") # we'll fill this in # scinv_all = numpy.zeros( (numcheck, scalc[0].zlvals.size) ) xlim = [0, zsmax] for i in xrange(beg, end): scinv_all = [] pz = self.data["pofz"][i] # print(pz) for j in xrange(numcheck): dzl = dzl_vals[j] nzl = nzl_vals[j] print(" nzl: %s dzl: %g" % (nzl, dzl)) tm0 = time() # scinv_all[j,:] = scalc[j].calc_mean_scinv(pz) sc = scalc[j].calc_mean_scinv(self.zs, pz) # sc=sc.clip(min=0.0) # print("sc",j,sc) scinv_all.append(sc) times[j] += time() - tm0 print("\nplotting") # plot the p(z) tab = Table(3, 1) binsize = self.zs[1] - self.zs[0] pzh = Histogram(pz, x0=self.zs[0], binsize=binsize) plt_pzh = FramedPlot() plt_pzh.xrange = xlim plt_pzh.xtitle = r"$z_s$" plt_pzh.ytitle = r"$P(z_s)$" plt_pzh.add(pzh) tab[0, 0] = plt_pzh # plt_pzh.show() # plot scinv for each dzl plt_scinv = FramedPlot() plt_scinv.xrange = xlim scinv_plots = [] for j in xrange(numcheck): dzl = dzl_vals[j] nzl = nzl_vals[j] p = Curve(scalc[j].zlvals, scinv_all[j], type="solid", color=colors[j]) p.label = r"$nz_{lens}: %s dz_{lens}: %0.3f$" % (nzl, dzl) plt_scinv.add(p) scinv_plots.append(p) scinv_key = PlotKey(0.95, 0.9, scinv_plots, halign="right") plt_scinv.add(scinv_key) plt_scinv.ylabel = r"$\Sigma_{crit}^{-1}(z_{lens})$" plt_scinv.xlabel = r"$z_{lens}$" plt_scinv.yrange = yrange # plt_scinv.show() tab[1, 0] = plt_scinv # %diff to best dz plt_pdiff = FramedPlot() plt_pdiff.xrange = xlim plt_pdiff.yrange = [-0.05, 0.05] pdiff_plots = [] zl_interp = numpy.linspace(zlmin, zlmax, 1000) scinv_interp_best = esutil.stat.interplin(scinv_all[0], scalc[0].zlvals, zl_interp) w = where1(scinv_interp_best > 0) for j in xrange(numcheck): dzl = dzl_vals[j] nzl = nzl_vals[j] scinv_interp = esutil.stat.interplin(scinv_all[j], scalc[j].zlvals, zl_interp) if w.size > 0: pdiff = scinv_interp[w] / scinv_interp_best[w] - 1.0 p = Curve(zl_interp[w], pdiff, type="solid", color=colors[j]) else: pdiff = numpy.ones(scinv_interp.size) p = Curve(zl_interp, pdiff, type="solid", color=colors[j]) p.label = r"$nz_{lens}: %s dz_{lens}: %0.3f$" % (nzl, dzl) plt_pdiff.add(p) pdiff_plots.append(p) key = PlotKey(0.95, 0.9, pdiff_plots, halign="right") plt_pdiff.add(key) plt_pdiff.ylabel = r"$\Sigma_{crit}^{-1} / \Sigma_{crit}^{-1}_{best} - 1$" plt_pdiff.xlabel = r"$z_{lens}$" tab[2, 0] = plt_pdiff if show: tab.show() plotfile = self.dzl_plot_file(i, type) print("writing to file:", plotfile) if type == "png": tab.write_img(1000, 1000, plotfile) else: tab.write_eps(plotfile) for j in xrange(numcheck): dzl = dzl_vals[j] print("time dzl=%s: %s" % (dzl, times[j]))
def plot_nfw_lin_fits_byrun(run, name, npts=100, prompt=False, withlin=True, ymin=0.01, ymax=2000.0): """ This should be made not specific for the m-z splits we used on the sims """ conf = lensing.files.cascade_config(run) if withlin: ex='lin' nex='lin' else: nex='' ex='' d = lensing.sample_read(type='fit',sample=run, name=name, extra=ex) omega_m = conf['cosmo_config']['omega_m'] rravel = d['r'].ravel() xrange = [0.5*rravel.min(), 1.5*rravel.max()] #for i in xrange(d.size): i=0 for dd in d: zrange = dd['z_range'] mrange = dd['m200_range'] if dd['rrange'][0] > 0: log_rmin = log10(dd['rrange'][0]) log_rmax = log10(dd['rrange'][1]) else: log_rmin = log10(dd['r'][0]) log_rmax = log10(dd['r'][-1]) rvals = 10.0**linspace(log_rmin,log_rmax,npts) plt = FramedPlot() lensing.plotting.add_to_log_plot(plt, dd['r'],dd['dsig'],dd['dsigerr']) z = dd['z_mean'] fitter = lensing.fit.NFWBiasFitter(omega_m,z,rvals,withlin=withlin) if withlin: yfit = fitter.nfw_lin_dsig(rvals, dd['r200_fit'],dd['c_fit'],dd['B_fit']) yfit_nfw = fitter.nfw.dsig(rvals,dd['r200_fit'],dd['c_fit']) yfit_lin = fitter.lin_dsig(rvals,dd['B_fit']) yfit = where(yfit < 1.e-5, 1.e-5, yfit) yfit_lin = where(yfit_lin < 1.e-5, 1.e-5, yfit_lin) cyfit = Curve(rvals,yfit,color='blue') cyfit_nfw = Curve(rvals,yfit_nfw,color='red') cyfit_lin = Curve(rvals,yfit_lin,color='orange') cyfit.label = 'Best Fit' cyfit_nfw.label = 'NFW' cyfit_lin.label = 'linear' key=PlotKey(0.1,0.3,[cyfit,cyfit_nfw,cyfit_lin]) plt.add(cyfit,cyfit_nfw,cyfit_lin,key) else: yfit_nfw = fitter.nfw.dsig(rvals,dd['r200_fit'],dd['c_fit']) cyfit_nfw = Curve(rvals,yfit_nfw,color='blue') plt.add(cyfit_nfw) zlab='%0.2f < z < %0.2f' % (zrange[0],zrange[1]) plt.add(PlotLabel(0.7,0.8,zlab)) ll = (log10(mrange[0]),log10(mrange[1])) mlab = r'$%0.2f < logM_{200} < %0.2f$' % ll plt.add(PlotLabel(0.7,0.9,mlab)) #yrange = [ymin,(dd['dsig']+dd['dsigerr']).max()*1.5] yrange = [ymin,ymax] plt.xrange = xrange plt.yrange = yrange plt.xlog=True plt.ylog=True plt.xlabel = r'$r$ [$h^{-1}$ Mpc]' plt.ylabel = r'$\Delta\Sigma ~ [M_{sun} pc^{-2}]$' plt.aspect_ratio=1 if prompt: plt.show() rinput = raw_input('hit a key: ') if rinput == 'q': return else: d = lensing.files.lensbin_plot_dir(run,name) if not os.path.exists(d): os.makedirs(d) epsfile=path_join(d,'desmocks-nfw%s-fit-%02i.eps' % (nex,i)) print 'Writing epsfile:',epsfile plt.write_eps(epsfile) i += 1
def compare_idl(ratios=False, epsfile=None): from biggles import FramedPlot,Points, Table omega_m=0.25 omega_b=0.055 sigma_8=1.0 h=1.0 ns=0.98 r=eu.recfile.Open('/home/esheldon/tmp/linear-compare/pkidl.dat', delim=' ',dtype=[('k','f8'),('pk','f8')]) pkidlst = r.read() r.close() k,pkidl = pkidlst['k'],pkidlst['pk'] r=eu.recfile.Open('/home/esheldon/tmp/linear-compare/xiidl.dat', delim=' ',dtype=[('r','f8'),('xi','f8')]) xiidlst = r.read() r.close() r,xiidl = xiidlst['r'],xiidlst['xi'] l = Linear(omega_m=omega_m,omega_b=omega_b,sigma_8=sigma_8,h=h,ns=ns) pk = l.pk(k) xi = l.xi(r, nplk=1000) #xi = l.xi(r) pkrat = pk/pkidl xirat = xi/xiidl tab=Table(2,1) symsize=1 if ratios: pkplt = FramedPlot() pkplt.xlabel='k' pkplt.xlog=True pkplt.ylabel='P(k)/P(k) dave' pkplt.add( Points(k,pkrat,type='filled circle',size=symsize) ) pkplt.add( Curve(k,pkrat,color='blue') ) tab[0,0] = pkplt if ratios: xiplt = FramedPlot() xiplt.xlabel='r' xiplt.xlog=True xiplt.ylabel='xi(r)/xi(r) dave' xiplt.add( Points(r,xirat,type='filled circle',size=symsize) ) xiplt.add( Curve(r,xirat,color='blue') ) tab[1,0] = xiplt else: # big log-log plot limxi = where(xi < 1.e-5, 1.e-5, xi) #pxi = Points(r,limxi,type='filled circle',size=symsize) cxi = Curve(r,limxi,color='blue') limxiidl = where(xiidl < 1.e-5, 1.e-5, xiidl) #pxiidl = Points(r,limxiidl,type='filled circle',size=symsize) cxiidl = Curve(r,limxiidl,color='red') xipltall = FramedPlot() xipltall.xlabel='r' xipltall.xlog=True xipltall.ylog=True xipltall.ylabel='xi(r)' #xipltall.add(pxi,cxi,pxiidl,cxiidl) xipltall.add(cxi,cxiidl) tab[0,0] = xipltall # zoomed in plot xiplt = FramedPlot() xiplt.xlabel='r' xiplt.xlog=True xiplt.ylabel='xi(r)' pxi = Points(r,xi,type='filled circle',size=symsize) cxi = Curve(r,xi,color='blue') cxi.label = 'Mine' pxiidl = Points(r,xiidl,type='filled circle',size=symsize) cxiidl = Curve(r,xiidl,color='red') cxiidl.label = 'Dave' key=PlotKey(0.8,0.9, [cxi,cxiidl]) xiplt.add(pxi,cxi,pxiidl,cxiidl) xiplt.xrange = [50.0,r.max()] xiplt.yrange=[-2.e-3,1.e-2] xiplt.add(key) tab[1,0] = xiplt if epsfile is not None: tab.write_eps(epsfile) else: tab.show()
def plot_sheardiff_bys2n(self, nperbin, nperbin_sub, show=False): import biggles from biggles import FramedPlot,PlotLabel, Curve, Points, Table, PlotKey data=self.get_sheardiff_data() epsfile=get_shear_compare_plot_url(self['serun'],self['merun']) print >>stderr,'Will write summary plot:',epsfile print >>stderr,'histogramming shear_s2n',nperbin hdict=eu.stat.histogram(data['shear_s2n'],nperbin=nperbin, rev=True,more=True) rev=hdict['rev'] cdlist=[] for i in xrange(hdict['hist'].size): if rev[i] != rev[i+1]: w=rev[ rev[i]:rev[i+1] ] label=r'$%0.3g < S/N < %0.3g$' \ % (hdict['low'][i],hdict['high'][i]) print >>stderr,label,'mean:',hdict['mean'][i],'num:',w.size cd=self.plot_sheardiff(nperbin_sub,indices=w,label=label, num=i, show=show) cdlist.append(cd) slopes1=[cd['coeff1'][0] for cd in cdlist] offsets1=[cd['coeff1'][1] for cd in cdlist] slopes2=[cd['coeff2'][0] for cd in cdlist] offsets2=[cd['coeff2'][1] for cd in cdlist] tab=Table(2,1) plt_slope=FramedPlot() cslope1 = Curve(hdict['mean'],slopes1,color='red') cslope2 = Curve(hdict['mean'],slopes2,color='blue') pslope1 = Points(hdict['mean'],slopes1,color='red', type='filled circle') pslope2 = Points(hdict['mean'],slopes2,color='blue', type='filled circle') cslope1.label = r'$\gamma_1$' cslope2.label = r'$\gamma_2$' key=PlotKey(0.1,0.2,[cslope1,cslope2],halign='left') plt_slope.add(cslope1,cslope2,pslope1,pslope2,key) plt_slope.xlabel = 'Shear S/N' plt_slope.ylabel = 'Slope' plt_slope.xlog=True plt_slope.xrange = eu.plotting.get_log_plot_range(hdict['mean']) plt_offset=FramedPlot() coffset1 = Curve(hdict['mean'],offsets1,color='red') coffset2 = Curve(hdict['mean'],offsets2,color='blue') poffset1 = Points(hdict['mean'],offsets1,color='red', type='filled circle') poffset2 = Points(hdict['mean'],offsets2,color='blue', type='filled circle') plt_offset.add(coffset1,coffset2,poffset1,poffset2) plt_offset.xlabel = 'Shear S/N' plt_offset.ylabel = 'Offset' plt_offset.xlog=True plt_offset.xrange = eu.plotting.get_log_plot_range(hdict['mean']) tab[0,0] = plt_slope tab[1,0] = plt_offset if show: tab.show() print >>stderr,'Writing summary plot:',epsfile tab.write_eps(epsfile) converter.convert(epsfile,dpi=90,verbose=True)
def plot_lens_s2n(zl, zslow, zshigh, pzs, cumulative=True): """ Calculate the cumulative expected usefulness of lenses as a function of redshift for the given source N(z). """ import biggles from biggles import FramedPlot, Curve, PlotLabel, PlotKey, Table, Histogram biggles.configure('screen','width',1140) biggles.configure('screen','height',1140) nzl=zshigh.size zlmin = 0.0 zlmax = max([zl.max(), zshigh.max()]) # first get the mean inverse critical density as a function # of lens redshift zsmid = (zshigh+zslow)/2. sc = lensing.sigmacrit.ScinvCalculator(zlmin, zlmax, nzl, zsmid[0], zsmind[-1]) mean_scinv = sc.calc_mean_scinv(pzs) # histogram the lens redshifts in a binning corresponding # to the mean_scinv hdict = eu.stat.histogram(zl, min=zlmin, max=zlmax, binsize=dz, more=True) # get distances to the bin centers cosmo=cosmology.Cosmo() Dlens = cosmo.Da(0.0, hdict['center']) # interpolate the mean_scinv onto the centers mean_scinv = eu.stat.interplin(mean_scinv, sc.zlvals, hdict['center']) # this is the S/N at a given lens redshift s2n = sqrt(hdict['hist']/Dlens**2)*mean_scinv hd = hdict['hist']/Dlens**2 hdcum = hd.cumsum() s2ncum = (mean_scinv*hd).cumsum()/sqrt(hdcum.clip(1.,hdcum.max())) s2n /= s2n.max() s2ncum /= s2ncum.max() tab = Table(2,2) tab.aspect_ratio=1 # redshift histograms tab[0,0] = FramedPlot() zl_histp = Histogram(hdict['hist']/float(hdict['hist'].sum()), x0=hdict['low'][0], binsize=dz, color='blue') zl_histp.label = 'lenses' zs_histp = Histogram(pzs/float(pzs.sum()), x0=zslow[0], binsize=dz, color='red') zs_histp.label = 'sources' hkey=PlotKey(0.9,0.9,[zl_histp,zs_histp],halign='right') tab[0,0].add(zl_histp, zs_histp, hkey) tab[0,0].xlabel = 'z' # mean inverse critical density tab[0,1] = FramedPlot() tab[0,1].xlabel = 'lens redshift' tab[0,1].ylabel = r'$\langle \Sigma_{crit}^{-1} \rangle$' mc = Curve(hdict['center'], mean_scinv) tab[0,1].add(mc) # cumulative volume tab[1,0] = FramedPlot() tab[1,0].xlabel = 'z' tab[1,0].ylabel = 'cumulative volume' v=zeros(hdict['center'].size) for i in xrange(v.size): v[i] = cosmo.V(0.0, hdict['center'][i]) v /= v.max() cv=Curve(hdict['center'], v) tab[1,0].add(cv) # S/N tab[1,1] = FramedPlot() tab[1,1].xlabel = 'lens redshift' tab[1,1].ylabel = 'S/N' cs2n = Curve(hdict['center'], s2n, color='blue') cs2ncum = Curve(hdict['center'], s2ncum, color='red') cs2n.label = 'S/N' cs2ncum.label = 'Cumulative S/N' ckey=PlotKey(0.9,0.9,[cs2n, cs2ncum],halign='right') tab[1,1].add(cs2n, cs2ncum, ckey) tab.show() return tab
def test_sigmacritinv_npts(epsfile=None): """ Test accuracy of sigmacrit inv as a function of number of points """ from biggles import FramedPlot, PlotKey, PlotLabel, Curve, FramedArray, Table c1000 = Cosmo(npts=1000) c5 = Cosmo(npts=5) c4 = Cosmo(npts=4) c3 = Cosmo(npts=3) c2 = Cosmo(npts=2) tab = Table( 2, 2 ) tab.uniform_limits = 0 tab.cellspacing = 1 p5 = FramedPlot() p5.xlabel = 'zsource' p5.ylabel = '% diff' p4 = FramedPlot() p4.xlabel = 'zsource' p4.ylabel = '% diff' p3 = FramedPlot() p3.xlabel = 'zsource' p3.ylabel = '% diff' p2 = FramedPlot() p2.xlabel = 'zsource' p2.ylabel = '% diff' l5 = PlotLabel(0.2,0.7,'npts = 5') p5.add(l5) l4 = PlotLabel(0.2,0.1,'npts = 4') p4.add(l4) l3 = PlotLabel(0.2,0.9,'npts = 3') p3.add(l3) l2 = PlotLabel(0.2,0.9,'npts = 2') p2.add(l2) colors = ['black','violet','blue','green','orange','magenta','firebrick','red'] zlvals = numpy.arange(0.1,0.9,0.1) if zlvals.size != len(colors): raise ValueError("mismatch colors and zlvals") i=0 allc5 = [] for zl in zlvals: zs = numpy.arange(zl+0.01, 2.0, 0.01) scinv = c1000.sigmacritinv(zl, zs) scinv5 = c5.sigmacritinv(zl, zs) scinv4 = c4.sigmacritinv(zl, zs) scinv3 = c3.sigmacritinv(zl, zs) scinv2 = c2.sigmacritinv(zl, zs) curve5 = Curve(zs, 100*(scinv-scinv5)/scinv, color=colors[i]) curve5.label = 'zlens: %0.2f' % zl allc5.append(curve5) p5.add(curve5) curve4 = Curve(zs, 100*(scinv-scinv4)/scinv, color=colors[i]) p4.add(curve4) curve3 = Curve(zs, 100*(scinv-scinv3)/scinv, color=colors[i]) p3.add(curve3) curve2 = Curve(zs, 100*(scinv-scinv2)/scinv, color=colors[i]) p2.add(curve2) i+=1 key = PlotKey(0.15,0.5,allc5) p5.add(key) tab[0,0] = p5 tab[0,1] = p4 tab[1,0] = p3 tab[1,1] = p2 tab.show() if epsfile is not None: tab.write_eps(epsfile)
def plot_meanshear_vs_trueshear_bys2n(self, nperbin, nperbin_sub, show=False): from biggles import FramedPlot, Curve, Points, Table, PlotKey type = "vs_shear" html_file = get_shear_compare_html_url(self["run"], self["mock_catalog"], type) print "html_file:", html_file data = self.get_data() epsfile = get_shear_compare_plot_url(self["run"], self["mock_catalog"], type) print >> stderr, "Will write summary plot:", epsfile print >> stderr, "histogramming shear_s2n", nperbin hdict = eu.stat.histogram(data["shear_s2n"], nperbin=nperbin, rev=True, more=True) rev = hdict["rev"] cdlist = [] pngfiles = [] for i in xrange(hdict["hist"].size): if rev[i] != rev[i + 1]: w = rev[rev[i] : rev[i + 1]] label = r"$%0.3g < S/N < %0.3g$" % (hdict["low"][i], hdict["high"][i]) print >> stderr, label, "mean:", hdict["mean"][i], "num:", w.size cd, png = self.plot_meanshear_vs_trueshear(nperbin_sub, indices=w, label=label, num=i, show=show) cdlist.append(cd) pngfiles.append(png) slopes1 = [cd["coeff1"][0] for cd in cdlist] offsets1 = [cd["coeff1"][1] for cd in cdlist] slopes2 = [cd["coeff2"][0] for cd in cdlist] offsets2 = [cd["coeff2"][1] for cd in cdlist] tab = Table(2, 1) plt_slope = FramedPlot() cslope1 = Curve(hdict["mean"], slopes1, color="red") cslope2 = Curve(hdict["mean"], slopes2, color="blue") pslope1 = Points(hdict["mean"], slopes1, color="red", type="filled circle") pslope2 = Points(hdict["mean"], slopes2, color="blue", type="filled circle") cslope1.label = r"$\gamma_1$" cslope2.label = r"$\gamma_2$" key = PlotKey(0.1, 0.2, [cslope1, cslope2], halign="left") plt_slope.add(cslope1, cslope2, pslope1, pslope2, key) plt_slope.xlabel = "Shear S/N" plt_slope.ylabel = "Slope" plt_slope.xlog = True plt_slope.xrange = eu.plotting.get_log_plot_range(hdict["mean"]) plt_offset = FramedPlot() coffset1 = Curve(hdict["mean"], offsets1, color="red") coffset2 = Curve(hdict["mean"], offsets2, color="blue") poffset1 = Points(hdict["mean"], offsets1, color="red", type="filled circle") poffset2 = Points(hdict["mean"], offsets2, color="blue", type="filled circle") plt_offset.add(coffset1, coffset2, poffset1, poffset2) plt_offset.xlabel = "Shear S/N" plt_offset.ylabel = "Offset" plt_offset.xlog = True plt_offset.xrange = eu.plotting.get_log_plot_range(hdict["mean"]) tab[0, 0] = plt_slope tab[1, 0] = plt_offset if show: tab.show() print >> stderr, "Writing summary plot:", epsfile tab.write_eps(epsfile) converter.convert(epsfile, dpi=90, verbose=True) png = epsfile.replace(".eps", ".png") pngfiles = [png] + pngfiles self.write_html(pngfiles, html_file)