def update_refs(self): # Easy external references for parameters self.back_weight = self.background[0] self.q = self.background[2] self.r0 = self.background[3] self.num_streams=len(self.streams) if self.num_streams > 0: self.stream_weight = [self.streams[0][0]] self.mu = [self.streams[0][1]] self.R = [self.streams[0][2]] self.theta = [self.streams[0][3]] # IN DEGREES!!!! self.phi = [self.streams[0][4]] # IN DEGREES!!!! self.sigma = [self.streams[0][5]] if len(self.streams) > 1: for i in range(1,len(self.streams)): self.stream_weight.append(self.streams[i][0]) self.mu.append(self.streams[i][1]) self.R.append(self.streams[i][2]) self.theta.append(self.streams[i][3]) self.phi.append(self.streams[i][4]) self.sigma.append(self.streams[i][5]) self.mu_lim = self.stripe[0] self.nu_lim = self.stripe[1] # Damn r in param files is actually g, will convert here to make referencing easy: self.r_lim = (co.getr(self.stripe[2][0]), co.getr(self.stripe[2][1]), self.stripe[2][2])
def update_refs(self): # Easy external references for parameters self.back_weight = self.background[0] self.q = self.background[2] self.r0 = self.background[3] self.num_streams = len(self.streams) if self.num_streams > 0: self.stream_weight = [self.streams[0][0]] self.mu = [self.streams[0][1]] self.R = [self.streams[0][2]] self.theta = [self.streams[0][3]] # IN DEGREES!!!! self.phi = [self.streams[0][4]] # IN DEGREES!!!! self.sigma = [self.streams[0][5]] if len(self.streams) > 1: for i in range(1, len(self.streams)): self.stream_weight.append(self.streams[i][0]) self.mu.append(self.streams[i][1]) self.R.append(self.streams[i][2]) self.theta.append(self.streams[i][3]) self.phi.append(self.streams[i][4]) self.sigma.append(self.streams[i][5]) self.mu_lim = self.stripe[0] self.nu_lim = self.stripe[1] # Damn r in param files is actually g, will convert here to make referencing easy: self.r_lim = (co.getr(self.stripe[2][0]), co.getr(self.stripe[2][1]), self.stripe[2][2])
def Hernquist_bin(gmin=16.0, gmax=22.5, lammin=0.0, lammax=2.5, betamin=0.0, betamax=0.5, rsteps=100, beta_steps=2, lamsteps=1, absmag=4.2, rho0=10.0, r0=9.0, q=0.52): """ gets the total number of stars in one square of the sky in Sgr Lambda, Beta coords """ lam0 = (lammax - lammin) * 0.5 + lammin lambin = (lammax - lammin) / lamsteps rmin, rmax = ac.getr(gmin, M=absmag), ac.getr(gmax, M=absmag) rbin = (rmax - rmin) / rsteps rcenters = sc.arange(rmin, rmax, rbin) + (rbin * 0.5) betabin = (betamax - betamin) / beta_steps betacenters = sc.arange(betamin, betamax, betabin) + (betabin * 0.5) Nstars = 0.0 #lamsteps not implemented for r in rcenters: new = 0.0 for b in betacenters: new = new + sc.cos(b) xgal, ygal, zgal = sgr.law_sgr2xyz_sun(lam0, b, r) #note default dSun=8.0 kpc zgal = zgal / q rgal = np.sqrt(xgal * xgal + ygal * ygal + zgal * zgal) new = new * rgal / ((rgal + r0)**3) Nstars = Nstars + new return Nstars * rho0 * lambin * betabin * rbin
def tomography(): cutstep = 0.5 gcuts = np.arange(16.0, 24.0, cutstep) for i in range(len(gcuts)): rmin, rmax = ac.getr(gcuts[i]), ac.getr(gcuts[i]+cutstep) outname = "SDSSN_gslice_{0:.1f}_{1:.1f}.png".format(rmin, rmax) make_total_plot(RGB=0, rcut=(rmin, rmax), outfile=outname ) print "DONE"
def sigmoid_error(x, modfit, modulus=None): """Application of detection efficiency""" s = [0.9402, 1.6171, 23.5877] if modulus != None: s[2] = s[2] - modulus detection_efficiency = s[0] / (np.exp(s[1] * (x - s[2])) + 1.) return detection_efficiency * modfit_error(co.getr(x), modfit)
def sgr_rv_cut(): data = np.loadtxt("/home/newbym2/Dropbox/Research/sgrLetter/sgr_spec_all.csv", delimiter=",") #dered_g,dered_r,l,b,ELODIERVFINAL,ELODIERVFINALERR,plate,p_ra,p_dec g0, r0 = data[:,0], data[:,1] l, b = data[:,2], data[:,3] rv, rv_err = data[:,4], data[:,5] plates = data[:,6] p_ra, p_dec = data[:,7], data[:,8] d = ac.getr(g0) # Transform to vgsr from Yanny+ 2009 vgsr = ac.rv_to_vgsr(rv,l,b) X,Y,Z, lsgr, bsgr, r_sgr = ac.lb2sgr(l, b, d) mean, stdev, nsig = -118.233333, 30.222222, 2.0 keep = [] for i in range(len(data[:,0])): if abs(bsgr[i]) < 10.0: if g0[i] < 20.0: continue if g0[i] > 23.0: continue if vgsr[i] < (mean - stdev*nsig): continue if vgsr[i] > (mean + stdev*nsig): continue keep.append([(g0[i]-r0[i]), g0[i]], p_ra[i], p_dec[i]) keep = np.array(keep) plt.figure() plt.scatter(keep[:,0], keep[:,1], s=1) lims = plt.ylim() plt.ylim(lims[1], lims[0]) plt.ylabel(r"$g_0$") plt.xlabel(r"$(g-r)_0$") plt.show() plt.close()
def sigmoid_error(x, modfit, modulus=None): """Application of detection efficiency""" s = [0.9402, 1.6171, 23.5877] if modulus != None: s[2] = s[2] - modulus detection_efficiency = s[0] / (np.exp(s[1]*(x - s[2])) + 1.) return detection_efficiency * modfit_error(co.getr(x), modfit)
def count_stars_in_rcut(): rmin, rmax = ac.getr(16.0), ac.getr(23.5) print rmin, rmax path="/home/newbym2/Desktop/starfiles" files = glob.glob(path+"/stars*") total = 0 for f in files: wedge = int(f.split("-")[1].split(".")[0]) count = 0 data = np.loadtxt(f, skiprows=1) for i in range(len(data[:,0])): if data[i,2] < rmin: continue if data[i,2] > rmax: continue if ac.SDSS_primary(data[i,0],data[i,1],wedge,fmt="lb",low=9,high=27)==0: continue count = count + 1 total = total + 1 print count, len(data[:,2]), np.ma.min(data[:,2]), np.ma.max(data[:,2]) print "Final Count:", total
def star_convolution(r, modfit, mu=4.2, sigma=0.6): """ Convolve Stars based on turnoff distribution Using Rejection Sampling""" m_g = co.getg(r) if not modfit: return co.getr(np.random.normal(m_g, 0.6)); found = 0; sigma_l = .36 sigma_r = ((0.52 / (1.0 + sc.exp(12.0 - r))) + 0.76) sigma = .36 while not found: guess = np.random.uniform(- (.6 * 3.0), .6 * 3.0); if guess < 0.0: sigma = sigma_l else: sigma = sigma_r probability = sc.exp(-(guess * guess) / (2.0 * sigma * sigma) ) / (.5 * (sigma_r + sigma_l) * SQ2PI) if (np.random.uniform() < (probability)): found = 1 return co.getr(m_g + guess)
def plot_stripe_3D(data): l, b, r = data[:, 0], data[:, 1], coor.getr(data[:, 2]) x, y, z = coor.lbr2xyz(l, b, r) fig = plt.figure() ax = Axes3D(fig) ax.scatter([-8.5], [0.0], [0.0], c='red') ax.scatter(x, y, z, c='yellow') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') plt.show()
def star_convolution(r, modfit, mu=4.2, sigma=0.6): """ Convolve Stars based on turnoff distribution Using Rejection Sampling""" m_g = co.getg(r) if not modfit: return co.getr(np.random.normal(m_g, 0.6)) found = 0 sigma_l = .36 sigma_r = ((0.52 / (1.0 + sc.exp(12.0 - r))) + 0.76) sigma = .36 while not found: guess = np.random.uniform(-(.6 * 3.0), .6 * 3.0) if guess < 0.0: sigma = sigma_l else: sigma = sigma_r probability = sc.exp( -(guess * guess) / (2.0 * sigma * sigma)) / (.5 * (sigma_r + sigma_l) * SQ2PI) if (np.random.uniform() < (probability)): found = 1 return co.getr(m_g + guess)
def crotus_cut(path="/home/newbym2/Desktop/starfiles", cdata=None): if cdata == None: files = glob.glob(path+"/stars*") data=[] r_cut_low, r_cut_high = ac.getr(16.0), ac.getr(23.5) #30.0, 45.0 pb = pr.Progressbar(steps=len(files), prefix="Loading Stars:", suffix=None, symbol="#", active="=", brackets="[]", percent=True, size=40) for f in files: wedge = int(f.split("-")[1].split(".")[0]) sdata = np.loadtxt(f, skiprows=1) for i in range(sdata.shape[0]): if (sdata[i,2] < r_cut_low) or (sdata[i,2] > r_cut_high): continue if ac.SDSS_primary(sdata[i,0],sdata[i,1],wedge,fmt="lb",low=9,high=27)==0: continue lam, bet = (ac.lb2sgr(sdata[i,0], sdata[i,1], 10.0))[3:5] if (lam <230.0) or (lam > 255.0): continue data.append([sdata[i,0], sdata[i,1], sdata[i,2], lam, bet]) pb.updatebar(float(files.index(f)+1)/float(len(files)) ) pb.endbar() data = np.array(data) np.savetxt("crotus_data.txt", data, fmt='%.6f') else: data = [] rdata = np.loadtxt(cdata) rlim0 = 28.5 #ac.getr(22.5) rlim1 = 45.0 for i in range(rdata.shape[0]): if rdata[i,2] < rlim0: continue if rdata[i,2] > rlim1: continue data.append(rdata[i,:]) data = np.array(data) #Now do analysis sky = pp.HistMaker(data[:,3], data[:,4], xsize=0.25, ysize=0.25, xarea=(230.0, 255.0), yarea=(-10.0, 15.0)) sky.varea = (0.0, 60.0) sky.cmap="color" #sky.scale = 'sqrt' sky.yflip = 1 pp.PlotHist(sky, "crotus_cut.png") #sky.savehist("streamgen_bifExtra.csv") print "### - Done"
def Hernquist_bin(gmin=16.0, gmax=22.5, lammin=0.0, lammax=2.5, betamin=0.0, betamax=0.5, rsteps=100, beta_steps=2, lamsteps=1, absmag=4.2, rho0=10.0, r0=9.0, q=0.52 ): """ gets the total number of stars in one square of the sky in Sgr Lambda, Beta coords """ lam0 = (lammax-lammin)*0.5 + lammin lambin = (lammax-lammin)/lamsteps rmin, rmax = ac.getr(gmin, M=absmag), ac.getr(gmax, M=absmag) rbin = (rmax - rmin)/rsteps rcenters = sc.arange(rmin, rmax, rbin) + (rbin*0.5) betabin = (betamax-betamin)/beta_steps betacenters = sc.arange(betamin, betamax, betabin) + (betabin*0.5) Nstars = 0.0 #lamsteps not implemented for r in rcenters: new = 0.0 for b in betacenters: new = new + sc.cos(b) xgal, ygal, zgal = sgr.law_sgr2xyz_sun(lam0, b, r) #note default dSun=8.0 kpc zgal = zgal / q rgal = np.sqrt(xgal*xgal + ygal*ygal + zgal*zgal) new = new*rgal / ((rgal + r0)**3) Nstars = Nstars + new return Nstars*rho0*lambin*betabin*rbin
def sgr_rv_skyplot(): data = np.loadtxt("/home/newbym2/Dropbox/Research/sgrLetter/sgr_spec_all.csv", delimiter=",") #dered_g,dered_r,l,b,ELODIERVFINAL,ELODIERVFINALERR,plate,p_ra,p_dec g0, r0 = data[:,0], data[:,1] l, b = data[:,2], data[:,3] rv, rv_err = data[:,4], data[:,5] plates = data[:,6] p_ra, p_dec = data[:,7], data[:,8] d = ac.getr(g0) # Transform to vgsr from Yanny+ 2009 vgsr = ac.rv_to_vgsr(rv,l,b) X,Y,Z, lsgr, bsgr, r_sgr = ac.lb2sgr(l, b, d) pl,pb = ac.EqTolb(p_ra, p_dec) pd = 20.0*sc.ones(len(pl)) pX,pY,pZ, plsgr, pbsgr, pr_sgr = ac.lb2sgr(pl, pb, pd) mean, stdev, nsig = -118.233333, 30.222222, 1.0 #plates = plate_center_utils() locs = [] for i in range(len(data[:,0])): if g0[i] < 20.0: continue if g0[i] > 23.0: continue #if lsgr[i] > 230.0: continue locs.append([lsgr[i], bsgr[i], vgsr[i], plsgr[i], pbsgr[i] ]) locs = np.array(locs) sgr = [] for i in range(len(locs[:,0])): if locs[i,2] < (mean - stdev*nsig): continue if locs[i,2] > (mean + stdev*nsig): continue sgr.append([locs[i,0], locs[i,1]]) sgr = np.array(sgr) plt.figure() plt.scatter(locs[:,0], locs[:,1], c="k", s=1) plt.scatter(sgr[:,0], sgr[:,1], c='r', s=10) plt.scatter(locs[:,3], locs[:,4], c='b', s=10) plt.plot([190.0, 250.0, 250.0, 190.0],[10.0, 10.0, -10.0, -10.0], "b-") plt.plot([190.0, 320.0], [0.0, 0.0], "b--") plt.text(195.0, 33.0, "$\mu=$-118.2, $\sigma=$30.2\n{0} stars in {1}$\sigma$".format(len(sgr), nsig), fontsize=16) plt.xlim(190.0, 320.0) #plt.ylim(-75.0, 40.0) plt.ylim(40.0, -75.0) plt.xlabel(r"$\Lambda$", fontsize=16) plt.ylabel(r"$B$", fontsize=16) plt.show() """ hist, edges = np.histogram(sgr[:,1], bins=23, range=(-75.0, 40.0)) plt.bar(edges[:-1], hist, width=5.0, color="grey") plt.xlabel("B", fontsize=16) plt.text(-50.0, 25.0, "Stars within "+str(nsig)+r"$\sigma$ of mean $v_{\rm gsr}$; $\Lambda<230$", fontsize=12) plt.show()""" plt.close()
def convert(filename, RaDec=0): readfile = open(filename, "r") holder, MW = [], [] for line in readfile: if line[0] == "#": continue if line.strip() == "": continue holder = line.split(",") for i in range(len(holder)): holder[i] = eval(holder[i]) if RaDec==1: l,b = coor.EqTolb(holder[0], holder[1]) holder[0], holder[1] = round(l,6) , round(b,6) r = coor.getr(holder[2], 4.2) holder[2] = round(r, 6) MW.append(holder[:3]) readfile.close() nstars = len(MW) out = sc.array(MW) fi.write_data(out, filename[:-4]+"_new.txt", " ", str(nstars))
def sgr_rv_fits(): data = np.loadtxt("/home/newbym2/Dropbox/Research/sgrLetter/sgr_spec.csv", delimiter=",") #dered_g,dered_r,l,b,ELODIERVFINAL,ELODIERVFINALERR g0, r0 = data[:,0], data[:,1] l, b = data[:,2], data[:,3] rv, rv_err = data[:,4], data[:,5] d = ac.getr(g0) # Transform to vgsr from Yanny+ 2009 vgsr = ac.rv_to_vgsr(rv,l,b) X,Y,Z, lsgr, bsgr, r_sgr = ac.lb2sgr(l, b, d) for w in [0.5, 1.0, 2.5, 5.0, 7.5, 10.0, 15.0, 20.0, 25.0, 30.0, 50.0]: keep = [] for i in range(len(data[:,0])): if abs(bsgr[i]) < w: if g0[i] < 20.0: continue if g0[i] > 23.0: continue keep.append(vgsr[i]) hist, edges = np.histogram(np.array(keep), bins=60, range=(-300.0, 300.0)) y, x = hist, edges[:-1] e = func.poisson_errors(y) fitter = fit.ToFit(x,y,e) fitter.function=func.double_gaussian_one_fixed fitter.update_params([3.0, -120.0, 30.0, 2.0, 0.0, 120.0]) fitter.step = [1.0, 10.0, 1.0, 1.0, 0.0, 0.0] fitter.param_names = ["amp", "mu", "sigma", "amp", "mu", "sigma"] path1 = fit.gradient_descent(fitter, its=10000, line_search=0) path2 = fit.MCMC(fitter) new_params=fitter.params xx = sc.arange(-300.0, 300.0, 1.0) yy = func.double_gaussian_one_fixed(xx, new_params) y1 = func.gaussian_function(xx, new_params[:3]) y2 = func.gaussian_function(xx, new_params[3:]) fig = plt.figure() plt.bar(edges[:-1], hist, width=10.0, color="white") plt.plot(xx,yy, "k-") plt.plot(xx,y1, "k--") plt.plot(xx,y2, "k--") plt.title("cut width = "+str(w)) plt.xlabel(r"$v_{\rm gsr}$", fontsize=16) plt.ylabel(r"Counts") #plt.ylim(0.0, 60.0) #plt.show() plt.savefig("/home/newbym2/Dropbox/Research/sgrLetter/sgr_spec/r_cut_relative"+str(w)+".png") plt.close()
def convert(filename, RaDec=0): readfile = open(filename, "r") holder, MW = [], [] for line in readfile: if line[0] == "#": continue if line.strip() == "": continue holder = line.split(",") for i in range(len(holder)): holder[i] = eval(holder[i]) if RaDec == 1: l, b = coor.EqTolb(holder[0], holder[1]) holder[0], holder[1] = round(l, 6), round(b, 6) r = coor.getr(holder[2], 4.2) holder[2] = round(r, 6) MW.append(holder[:3]) readfile.close() nstars = len(MW) out = sc.array(MW) fi.write_data(out, filename[:-4] + "_new.txt", " ", str(nstars))
def split_by_plate(): # dered_g,dered_r,l,b,ELODIERVFINAL,ELODIERVFINALERR,plate,p_ra,p_dec data = np.loadtxt("/home/newbym2/Dropbox/Research/sgrLetter/sgr_spec_all.csv", delimiter=",") mean, stdev, nsig = -118.233333, 30.222222, 1.0 plates, pos = [], [] for i in range(len(data[:,0])): if plates.count(data[i,6]) > 0: continue plates.append(data[i,6]) pos.append([data[i,7], data[i,8]]) out = [] for i, plate in enumerate(plates): # get stars for plate stars = [] for j in range(len(data[:,0])): if data[j,6] == plate: stars.append(data[j,:]) if stars == []: continue # apply cuts keep = [] for star in stars: if star[0] < 20.0: continue if star[0] > 20.5: continue #using stricter cut X,Y,Z, lsgr, bsgr, r_sgr = ac.lb2sgr(star[2], star[3], ac.getr(star[0])) if lsgr < 190.0: continue if lsgr > 250.0: continue if abs(bsgr) > 10.0: continue vgsr = ac.rv_to_vgsr(star[4],star[2],star[3]) keep.append([lsgr, bsgr, vgsr]) if keep == []: continue # vgsr selection yes, no = 0, 0 for k in keep: if k[2] < (mean - stdev*nsig): no += 1; continue if k[2] > (mean + stdev*nsig): no += 1; continue yes += 1 print "Plate {0}: In {1} of Sgr versus out: {2}, {3}".format( plate, nsig, yes, no) # compile plate info positions out.append([plate, pos[i][0], pos[i][1], yes, no]) savename = "/home/newbym2/Dropbox/Research/sgrLetter/plate_stars.csv" np.savetxt(savename, sc.array(out), delimiter=",")
# 7.57640162772, 7.67810980299, 11.5363484879, 25.6937588232, 8.75918164562, # 37.6255221984, 54.5484852169, 13.1237001504, 12.2803690866, 11.9300143607, # 12.2150368604, 13.3084651939, 14.9866923184, 15.7846605126, 27.9365850481, # 11.2583497941, 10.1111224829, 9.12819009006 to_x = sc.zeros((len(data[:,0]), 3) ) # RAISE THIS TO 4? WHEN ERRORS ARE USED for i in range(len(data[:,0])): u, v, w, mu, r, theta, phi, sigma = 0.0, 0.0, 0.0, data[i,4], data[i,5], \ data[i,6], data[i,7], data[i,8] to_x[i,0], to_x[i,1], to_x[i,2] = co.stream2xyz(u, v, w, mu, r, theta, phi, wedges[i]) #to_x[i,3] = errors[i] """ to_x = sc.zeros((len(data[:,0]), 3) ) for i in range(len(data[:,0])): x,y,z = co.lbr2xyz(data[i,0], data[i,1], co.getr(data[i,2], 0.6)) #<--- 0.6 for Koposov 'i's to_x[i,0], to_x[i,1], to_x[i,2] = x,y,z print to_x params = pf.plane_OLS(to_x[:,0], to_x[:,1], to_x[:,2]) print "#- Distance array:", pf.plane_dist(to_x[:,0], to_x[:,1], to_x[:,2], params) fitter.x = to_x fitter.y = sc.zeros(len(data[:,0]) ) fitter.function=func.plane_fit #func.R_squared_plane fitter.update_params([3.0*ma.pi/2.0, ma.pi/2.0, 1.0]) #(params) fitter.range = [(0, 0.0, 2.0*ma.pi, ma.pi/10.0), (1, 0.0, ma.pi, ma.pi/20.0), (2, -20.0, 20.0, 1.0)] print fitter.params, fitter.RR
import math as ma import numpy as np import scipy as sc import astro_coordinates as coor import sgr_law as sl '''python script for figuring out what l,b values were used to get a Sgr Lambda, Beta Matthew Newby, July 16, 2012''' pres = 0.001 #search precision center_l, center_b, r = 180.0, 0.0, coor.getr(20.75) #search start lam_out = [75.0, 85.0, 95.0, 105.0, 115.0] #beta_out = [9.5, 10.3, 10.3, 10.7, 11.8] # Secondary Peak beta_out = [-1.3, -2.5, -1.3, -0.9, -1.4] # Primary Peak l_steps = sc.arange(-180.0, 190.0, 20.0) # -100 to 100, increments of 20 b_steps = sc.arange(-90.0, 91.0, 10.0) # -20 to -20, increments of 4 steps = len(l_steps) def dist(l,b,lam, beta): x,y,z = coor.lbr2xyz(l,b,r) x0,y0,z0,lam0,beta0,r0 = sl.law_xyz2sgr_sun(x,y,z) one = (lam0 - lam)*(lam0 - lam) two = (beta0 - beta)*(beta0 - beta) return sc.sqrt(one + two) verbose = 0
def plot_profiles(path="/home/newbym2/Desktop/starfiles", savewedge=False, suffix=""): files = glob.glob(path+"/stars*") print files suffix = "_rcut_IV" data=[] r_cut_low, r_cut_high = 40.0, ac.getr(22.5) #ac.getr(16.0), ac.getr(22.5) #20.0 OR 30.0, 45.0 pb = pr.Progressbar(steps=len(files), prefix="Loading Stars:", suffix=None, symbol="#", active="=", brackets="[]", percent=True, size=40) for f in files: wedge = int(f.split("-")[1].split(".")[0]) count=0 stripedata = open(f, "r") for line in stripedata: count = count + 1 if count==1: continue if line.strip()=="": continue temp = line.split() for i in range(len(temp)): temp[i] = float(temp[i]) if (temp[2] < r_cut_low) or (temp[2] > r_cut_high): continue if ac.SDSS_primary(temp[0],temp[1],wedge,fmt="lb",low=9,high=27)==0: continue data.append(temp) stripedata.close() pb.updatebar(float(files.index(f)+1)/float(len(files)) ) datar = np.array(data) data = np.zeros(datar.shape, float) count, nStars, pb2 = 0, float(len(data[:,0])), pr.Progressbar(steps=100, prefix="Changing Coordinates:", suffix=None, symbol="#", active="=", brackets="[]", percent=True, size=40) for i in range(len(data[:,0])): count = count + 1 #data[i,0], data[i,1] = ac.lb2GC(data[i,0], data[i,1], 15) #data[i,0], data[i,1] = ac.lbToEq(data[i,0], data[i,1]) data[i,0], data[i,1] = (ac.lb2sgr(datar[i,0], datar[i,1], 30.0))[3:5] data[i,2] = ac.getg(datar[i,2], 4.2) if count % 100 == 0: pb2.updatebar(float(count)/nStars) pb2.endbar() # loop over Lambda slices and plot Beta histograms pb3 = pr.Progressbar(steps=len(files), prefix="Making Slices:", suffix=None, symbol="#", active="=", brackets="[]", percent=True, size=40) Ls = (200.0, 300.0, 2.5) Lsteps = int((Ls[1]-Ls[0])/Ls[2]) for i in range(Lsteps): Lname = str(Ls[0]+(Ls[2]*i) )[:6]+suffix new = [] for j in range(len(data[:,0])): if data[j,0] < Ls[0]+(Ls[2]*i): continue if data[j,0] > Ls[0]+(Ls[2]*(i+1)): continue if savewedge: new.append([datar[j,0], datar[j,1], data[j,2]]) continue new.append(data[j,1]) new = np.array(new) if savewedge: np.savetxt("stars-lambda-"+("00"+str(i))[-2:]+".txt", new, fmt='%.6f') else: Lhist, Ledges = np.histogram(new, 140, (-30.0, 40.0)) #output to file outstuff = sc.array(zip(Ledges+0.25, Lhist)) np.savetxt(Lname+".out", outstuff) #plot plt.figure(1) plt.bar(Ledges[:-1], Lhist, 0.5) plt.title(Lname) plt.xlabel("B") plt.savefig(Lname+".png") plt.close('all') pb3.updatebar(float(i)/float(Lsteps)) print "Ended Successfully"
#plot wedge outline; positions of fits will be points, with size <-> sigma; # r0 can be dotted band on wedge? # show dot product for theta, phi? # pi chart for epsilons? # q? # plot area will be a rectangle, everything will be rotated to 0-180 degrees deg = 180.0 / ma.pi rad = ma.pi / 180.0 mu_min, mu_max, mu_step = 310.0, 419.0, 10 nu_min, nu_max, nu_step = -1.25, 1.25, 0.01 g_min, g_max, g_step = 16.0, 22.5, 0.1 r_min, r_max, r_step = coor.getr(g_min), coor.getr(g_max), 1.0 # params: (0) q, (1) r0, (2) eps1, (3) mu1, (4) r1, (5) theta1, (6) phi1, (7) sigma1, (8+) etc2 base_params = [ 0.455, 19.5, -2.0, 360.0, 21.0, 0.0, 0.0, 1.0, -20.0, 0.0, 0.0, 0.0, 0.0, 0.1 ] """ set 1 fits = [ [0.475327420183122, 15.713584742146832, -1.9775646182435411, 0.03651142048400802, 20.911171039807066, 0.0, 6.283185307179586, 1.0, -20.0, 75.99999999853678, 45.7, 6.283185307179586, 2.235076930198925, 1.0], [0.4893922624025933, 17.704928980687075, -2.0404335113612424, 0.04556372224625185, 21.09655088818001, 0.0, 0.0023900782833266108, 1.0, -19.9999244362222, 76.0, 36.81282179243893, 5.850074298007271, 0.2920932656983071, 19.99621820184909], [0.5365879809070045, 8.835827427800472,
def single_stripe_mur(data, wedge, mag=0, scale=0, color=1, position=111, mu_lim=None, r_lim=None, vm=None, nu_flatten=0, bar=1, ring=1, raw_coords=0): """ change 'scale' to a string tag: None, sqrt, flatten, log? """ #l, b = data[:,0], data[:,1] x_size, y_size = 0.5, 0.5 if mag == 1: r = coor.getr(data[:, 2]) else: r = data[:, 2] print len(r) if r_lim == None: r_lim = (np.ma.min(r), np.ma.max(r)) if raw_coords == 0: ra, dec = coor.lbToEq(data[:, 0], data[:, 1]) mu, nu = coor.EqToGC(ra, dec, wedge) else: mu, nu = data[:, 0], data[:, 1] if mu_lim == None: mu_lim = [np.ma.min(mu), np.ma.max(mu)] #Checks if limits straddle mu=0.0 if (mu_lim[0] < 1.0) and (mu_lim[1] > 359.0): mu_lim[0], mu_lim[1] = 0.0, 360.0 for i in mu: if (i > 180.0) and (i < mu_lim[1]): mu_lim[1] = i if (i < 180.0) and (i > mu_lim[0]): mu_lim[0] = i mu_lim[0] = mu_lim[0] - 360.0 x, y = r * sc.cos(mu * rad), r * sc.sin(mu * rad) x_bins = int((np.ma.max(x) - np.ma.min(x)) / x_size) + 1 y_bins = int((np.ma.max(y) - np.ma.min(y)) / y_size) + 1 H, x, y = np.histogram2d( y, x, [y_bins, x_bins]) #, range=[[-155.0, 110.0],[-190.0, 0.0]]) extent = [np.ma.min(y), np.ma.max(y), np.ma.max(x), np.ma.min(x)] if nu_flatten == 1: print "!!! DOUBLE-CHECK NU FLATTENING! {0}".format(H.shape) for i in range(H.shape[0]): for j in range(H.shape[1]): dist = ma.sqrt(((i - (H.shape[0] / 2.0)) * y_size)**2 + (j * x_size)**2) H[i, j] = H[i, j] / (dist * 2.5) H = sc.sqrt(H) #sc.log10(H) vm = 1.5 elif scale == 1: H = sc.sqrt(H) if vm == None: vm = 16.0 else: if vm == None: vm = 300.0 """ Begin Figure """ #fig = plt.figure(frameon=False) sp = plt.subplot(position) if color == 1: cmap = spectral_wb else: cmap = 'gist_yarg' plt.imshow(H, extent=extent, interpolation='nearest', vmin=0.0, vmax=vm, cmap=cmap) if bar == 1: bar = plt.colorbar(orientation='vertical') if scale == 1: bar_ticks = sc.arange(0.0, vm + 1.0, 2.0) bar_labels = [] for i in range(len(bar_ticks)): bar_labels.append(str(int(bar_ticks[i]**2))) bar.set_ticks(bar_ticks) bar.set_ticklabels(bar_labels, update_ticks=True) """ Draw axes - mu """ mu_axis = gen_mu_axis(mu_lim, r_lim[1], ring) plt.plot(mu_axis[0], mu_axis[1], 'k-') # Draws main axis for i in range(len(mu_axis[2])): x0 = [ 1.0 * r_lim[1] * sc.cos(mu_axis[2][i] * rad), 1.1 * r_lim[1] * sc.cos(mu_axis[2][i] * rad) ] y0 = [ 1.0 * r_lim[1] * sc.sin(mu_axis[2][i] * rad), 1.1 * r_lim[1] * sc.sin(mu_axis[2][i] * rad) ] plt.plot(x0, y0, 'k-') # Draws mu ticks if mu_axis[3][i] <= 180.0: rot = -90.0 + mu_axis[3][i] else: rot = -360.0 + mu_axis[3][i] - 90.0 if wedge < 40: offset = 1.12 #This accounts for different whitespace on each side of 180 else: offset = 1.14 x00, y00 = offset * r_lim[1] * sc.cos( mu_axis[2][i] * rad), offset * r_lim[1] * sc.sin( mu_axis[2][i] * rad) #Format tick labels - this part adds whitespace to center labels on ticks pre, mulbl = "$", str(mu_axis[3][i]) if len(mulbl) < 3: for k in range(3 - len(mulbl)): pre = " " + pre if i == (len(mu_axis[2])) - 1: plt.text(x00, y00, "$\mu=" + str(mu_axis[3][i]) + "^{\circ}$", rotation=rot, fontsize=12, horizontalalignment='center') #float(mu_axis[3][i]) ) else: plt.text(x00, y00, pre + str(mu_axis[3][i]) + "^{\circ}$", rotation=rot, fontsize=12, horizontalalignment='center') #float(mu_axis[3][i]) ) """ Draw axes - r """ r_axis = gen_r_axis(mu_lim, r_lim) plt.plot(r_axis[0], r_axis[1], 'k-') mu1 = sc.arange(mu_lim[0] - 6.0, mu_lim[1] + 7.0, 1.0) for tick in r_axis[2]: x1, y1 = tick * sc.cos(mu1 * rad), tick * sc.sin(mu1 * rad) if mu1[-1] < 90.0 or mu1[-1] > 360.0: x2, y2 = tick * sc.cos((mu1[-1]) * rad), tick * sc.sin( (mu1[-1]) * rad) hl = 'right' else: x2, y2 = tick * sc.cos((mu1[1]) * rad), tick * sc.sin( (mu1[1]) * rad) hl = 'left' plt.plot(x1[:7], y1[:7], "k-") plt.plot(x1[-7:], y1[-7:], "k-") if tick == r_axis[2][-1]: plt.text(x2, y2, "$r=" + str(int(tick)) + "$", rotation=0.0, fontsize=12, horizontalalignment=hl, verticalalignment='bottom') else: plt.text(x2, y2, "$" + str(int(tick)) + "$", rotation=0.0, fontsize=12, horizontalalignment=hl, verticalalignment='bottom') # Draw axes - g (TO BE DONE) """ Clean up output """ y_lim = plt.ylim() plt.ylim(y_lim[1], y_lim[0]) plt.setp(sp.get_xticklabels(), visible=False) plt.setp(sp.get_yticklabels(), visible=False) plt.setp(sp.get_xticklines(), visible=False) plt.setp(sp.get_yticklines(), visible=False) #ax = fig.add_axes([0, 0, 1, 1]) #These two lines supress the axes... supposedly #ax.axis('off') return sp
def plot_wedge_density(data, wedge=82, q=0.458, r0=19.5, mu_min=310.0, mu_max=419.0, streams=None, perturb=None, name="out", mag=0, plot=1, size=1.0): """Plots the average density of a wedge versus radius stream coords. should be a list of streams, with each sub-list being a standard 6-parameter set of stream parameters; perturb is weight of perturbation, if any; mag is whether data is in g magnitudes or not. CURRENTLY ONLY WORKS (WELL) FOR STRIPE 82!!!""" #Get Average Density with r x, y, z = coor.lbr2xyz(data[:, 0], data[:, 1], data[:, 2]) if mag == 1: r = coor.getr(data[:, 2]) else: r = data[:, 2] max, min = np.ma.max(r), np.ma.min(r) bins = int((max - min + 1.0) / size) rho_raw = sc.zeros(bins, int) for i in range(len(r)): index = int((r[i] - min) / size) rho_raw[index] = rho_raw[index] + 1 # get volume at each distance #mu_min, mu_max = 310.0, 419.0 #Defined in def inputs nu_min, nu_max = (-1.25 * ma.pi / 180.0), (1.25 * ma.pi / 180.0) mu_bit = mu_max - mu_min nu_bit = sc.sin(nu_max) - sc.sin(nu_min) V = sc.zeros(bins, float) for i in range(bins): r_bit = (min + (i + 1) * size)**3 - (min + i * size)**3 V[i] = r_bit * (1. / 3.) * mu_bit * nu_bit # make the histogram of rho(r) rho_hist = sc.zeros((bins, 3), float) for i in range(bins): rho_hist[i, 0] = min + (i * size) rho_hist[i, 1] = rho_raw[i] / V[i] rho_hist[i, 2] = (ma.sqrt(rho_raw[i] + 1.0) + 1.0) / V[i] """Plot Herquist, stream, perturbation functions over histogram""" #get gal-centered herquist distribution for r points in wedge mu_avg = ((mu_max - mu_min) / 2.0) + mu_min nu_avg = 0.0 sol_r = sc.arange(min, max, size) x, y, z = coor.GC2xyz(mu_avg, nu_avg, sol_r, wedge) Hern_rho = twg.hernquist_profile(x, y, z, q, r0) H_scale = sc.sum(rho_hist[:, 1]) / sc.sum( Hern_rho) #multiply a factor of 2 to account for different # of bins for i in range(len(Hern_rho)): Hern_rho[i] = Hern_rho[i] * H_scale # DO STREAM!!! ################ #get gal-centered perturbation distribution for r points in wedge if perturb != None: perturb_rho = twg.perturb_density(x, y, z, (0.0, 0.79, -19.9)) p_scale = 1.0 for i in range(len(perturb_rho)): perturb_rho[i] = perturb_rho[i] * p_scale #Plot it all if plot == 1: fig = plt.figure() plt.bar(rho_hist[:, 0], (rho_hist[:, 1] / Hern_rho) - 1.0, size) #plt.plot(sol_r, Hern_rho, c='r') if perturb != None: plt.plot(sol_r, perturb_rho, c='r') plt.xlabel(r'Sun-centered $r$ (kpc)') plt.ylabel(r'$\rho$ (stars/kpc)') #plt.savefig((name+".ps"), papertype='letter') plt.show() plt.close('all') return rho_hist
#plot wedge outline; positions of fits will be points, with size <-> sigma; # r0 can be dotted band on wedge? # show dot product for theta, phi? # pi chart for epsilons? # q? # plot area will be a rectangle, everything will be rotated to 0-180 degrees deg = 180.0 / ma.pi rad = ma.pi / 180.0 mu_min, mu_max, mu_step = 310.0, 419.0, 10 nu_min, nu_max, nu_step = -1.25, 1.25, 0.01 g_min, g_max, g_step = 16.0, 22.5, 0.1 r_min, r_max, r_step = coor.getr(g_min), coor.getr(g_max), 1.0 # params: (0) q, (1) r0, (2) eps1, (3) mu1, (4) r1, (5) theta1, (6) phi1, (7) sigma1, (8+) etc2 base_params = [0.455, 19.5, -2.0, 360.0, 21.0, 0.0, 0.0, 1.0, -20.0, 0.0, 0.0, 0.0, 0.0, 0.1] """ set 1 fits = [ [0.475327420183122, 15.713584742146832, -1.9775646182435411, 0.03651142048400802, 20.911171039807066, 0.0, 6.283185307179586, 1.0, -20.0, 75.99999999853678, 45.7, 6.283185307179586, 2.235076930198925, 1.0], [0.4893922624025933, 17.704928980687075, -2.0404335113612424, 0.04556372224625185, 21.09655088818001, 0.0, 0.0023900782833266108, 1.0, -19.9999244362222, 76.0, 36.81282179243893, 5.850074298007271, 0.2920932656983071, 19.99621820184909], [0.5365879809070045, 8.835827427800472, -1.2866515732682133, 22.0282867183652, 20.26159364245282, 1.9361892304689605, 5.156542533627633, 1.0000110295383529, -8.599516830387287, 1.8479918605604446, 3.1926322241404312, 1.3072306295288028, 6.158867283053862, 17.870352496110993],
import math as ma import numpy as np import scipy as sc import astro_coordinates as coor import sgr_law as sl '''python script for figuring out what l,b values were used to get a Sgr Lambda, Beta Matthew Newby, July 16, 2012''' pres = 0.001 #search precision center_l, center_b, r = 180.0, 0.0, coor.getr(20.75) #search start lam_out = [75.0, 85.0, 95.0, 105.0, 115.0] #beta_out = [9.5, 10.3, 10.3, 10.7, 11.8] # Secondary Peak beta_out = [-1.3, -2.5, -1.3, -0.9, -1.4] # Primary Peak l_steps = sc.arange(-180.0, 190.0, 20.0) # -100 to 100, increments of 20 b_steps = sc.arange(-90.0, 91.0, 10.0) # -20 to -20, increments of 4 steps = len(l_steps) def dist(l, b, lam, beta): x, y, z = coor.lbr2xyz(l, b, r) x0, y0, z0, lam0, beta0, r0 = sl.law_xyz2sgr_sun(x, y, z) one = (lam0 - lam) * (lam0 - lam) two = (beta0 - beta) * (beta0 - beta) return sc.sqrt(one + two) verbose = 0