def sgr_sim_density(stripes, params): SGA = fi.read_data("../sgrnorth_paper/stream_gen_analysis.txt", ",") low_lam, high_lam = 200.0, 314.8 # from Sgr stripes: (200.025901082, 314.707561185) size = (high_lam - low_lam) / 15.0 N_stars = [ 19386, 18734, 11096, 17044, 18736, 15409, 12519, 12248, 8853, 7328, 5479, 4450, 3486, 2425, 971, 9511, 16119, 16603 ] south = [79, 82, 86] out = [] for i in range(15): print "# - Lambda wedge {0}:".format(i) num = str(i) name = "./sim_streams/lamsim_out_" + num + ".txt" data = fi.read_data(name, echo=1) total = len(data[:, 0]) other = sc.sum(data[:, 3]) length = 7.653333333 # bin size out.append([(low_lam + (size * i) + (size * 0.5)), total - other, total, 0.0, total / length]) for i in range(15, 18): print "# - Southern wedge {0}:".format(south[i - 15]) data = fi.read_data("./sim_streams/sim_stripe_" + str(south[i - 15]) + ".txt") total = len(data[:, 0]) other = sc.sum(data[:, 3]) length = SGA[i, 3] mu, r, theta, phi, wedge = eval(params[i][4]), eval(params[i][5]), \ eval(params[i][6]), eval(params[i][7]), stripes[i] x, y, z = coor.stream2xyz(0.0, 0.0, 0.0, mu, r, theta, phi, wedge) Xs, Ys, Zs, lam, beta, r = sl.law_xyz2sgr_sun(x, y, z) out.append([lam, total - other, total, 0.0, total / length]) fi.write_data(sc.array(out), "sgrNorth_density_sim.txt", ",", " lam(mid), count, SDSS Deff, SDSS/FTO Deff, per degree")
def do_compare_wedges(file1="stars-82.txt", file2="Stripe82_coadd.csv", stripe=82, mag=0, size=1.0): """ Modify if size is not 1.0 """ one_run = fi.read_data(file1) or_l = len(one_run[:,0]) or_hist = sv.plot_wedge_density(one_run, stripe, q=0.458, r0=19.4, name="_rho1", mag=mag, plot=0, size=size) coadd = fi.read_data(file2) ca_l = len(coadd[:,0]) ca_hist = sv.plot_wedge_density(coadd, stripe, q=0.458, r0=19.4, name="_rho2", mag=mag, plot=0, size=size) # Separate into heights or_h = or_hist[:,1] ca_h = ca_hist[:,1] # Divide the first data set by the second if len(or_h) < len(ca_h): l = len(or_h) extra_h = -0.1*sc.ones((len(ca_h)-l)) else: l = len(ca_h) extra_h = 0.1*sc.ones((len(or_h)-l)) diff_h = sc.zeros(l) for i in range(l): diff_h[i] = ( or_h[i] / ca_h[i] ) out = sc.zeros((l,3)) for i in range(l): out[i,0], out[i,1] = ca_hist[i,0], diff_h[i] out[i,2] = 1.0 #ma.sqrt(or_hist[i,2]*or_hist[i,2] + ca_hist[i,2]*ca_hist[i,2]) return out
def get_errors(file1="../sgrnorth_paper/results_BG_easyread.txt", file2="../sgrnorth_paper/results_errors.txt"): """ Takes in mu,nu,r errors, and turns them into a 3D "sigma sphere" for fitting a plane - GARBAGE""" wedges = [ 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 79, 82, 86 ] data = fi.read_data(file1, ",") errors = fi.read_data(file2) circ = [] # circular errors for i in range(len(data[:, 0])): # Get x,y,z errors due to d_R x0, y0, z0 = coor.stream2xyz(0.0, 0.0, 0.0, data[i, 4], errors[i, 4], 0.0, 0.0, wedges[i]) # Get x,y,z errors due to d_mu - the difference between the original vector, and that vector shifted by d_mu x1, y1, z1 = coor.stream2xyz(0.0, 0.0, 0.0, data[i, 4], data[i, 5], 0.0, 0.0, wedges[i]) x2, y2, z2 = coor.stream2xyz(0.0, 0.0, 0.0, (data[i, 4] + errors[i, 3]), data[i, 5], 0.0, 0.0, wedges[i]) x3, y3, z3 = (x2 - x1), (y2 - y1), (z2 - z1) #print x0,y0,z0, x3,y3,z3 X = sc.sqrt(x0 * x0 + x3 + x3) Y = sc.sqrt(y0 * y0 + y3 + y3) Z = sc.sqrt(z0 * z0 + z3 + z3) print X, Y, Z circ.append(float(sc.sqrt(X * X + Y * Y + Z * Z))) for item in circ: print item return circ
def sgr_sim_density(stripes, params): SGA = fi.read_data("../sgrnorth_paper/stream_gen_analysis.txt", ",") low_lam, high_lam = 200.0, 314.8 # from Sgr stripes: (200.025901082, 314.707561185) size = (high_lam - low_lam) / 15.0 N_stars = [19386, 18734, 11096, 17044, 18736, 15409, 12519, 12248, 8853, 7328, 5479, 4450, 3486, 2425, 971, 9511, 16119, 16603] south = [79, 82, 86] out = [] for i in range(15): print "# - Lambda wedge {0}:".format(i) num = str(i) name = "./sim_streams/lamsim_out_"+num+".txt" data = fi.read_data(name, echo=1) total = len(data[:,0]) other = sc.sum(data[:,3]) length = 7.653333333 # bin size out.append([(low_lam+(size*i)+(size*0.5)), total-other, total, 0.0, total/length]) for i in range(15,18): print "# - Southern wedge {0}:".format(south[i-15]) data = fi.read_data("./sim_streams/sim_stripe_"+str(south[i-15])+".txt") total = len(data[:,0]) other = sc.sum(data[:,3]) length = SGA[i,3] mu, r, theta, phi, wedge = eval(params[i][4]), eval(params[i][5]), \ eval(params[i][6]), eval(params[i][7]), stripes[i] x,y,z = coor.stream2xyz(0.0, 0.0, 0.0, mu, r, theta, phi, wedge) Xs, Ys, Zs, lam, beta, r = sl.law_xyz2sgr_sun(x,y,z) out.append([lam, total-other, total, 0.0, total/length]) fi.write_data(sc.array(out), "sgrNorth_density_sim.txt", ",", " lam(mid), count, SDSS Deff, SDSS/FTO Deff, per degree")
def unload_hists(l_in=None, red_in=None, dered_in=None): if l_in != None: l_hist = fi.read_data(l_in, ",") else: l_hist = None if red_in != None: red_hist = fi.read_data(red_in, ",") else: red_hist = None if dered_in != None: dered_hist = fi.read_data(dered_in, ",") else: dered_hist = None return l_hist, red_hist, dered_hist
def unload_hists(l_in=None, red_in=None, dered_in=None): if l_in != None: l_hist = fi.read_data(l_in, ",") else: l_hist = None if red_in != None: red_hist = fi.read_data(red_in, ",") else: red_hist = None if dered_in != None: dered_hist = fi.read_data(dered_in, ",") else: dered_hist = None return l_hist, red_hist, dered_hist
def fit_distance(): dmod = [0.0, 5.0, 10.0, -5.0, -10.0] filename = "./Girardi_Isochrones/"+name+"_0.dat" iso_data = fi.read_data(filename) if name != 'Pal5': clus_data = fi.read_data("noU_NGC_"+name+"_cluster.csv", ",") else: clus_data = fi.read_data("noU_"+name+"_cluster.csv", ",") if dist < 10.0: high = 7.0 elif dist < 20.0: high = 6.0 else: high = 5.5 clus = format_data(clus_data, dist, cuts=(3.5, high))
def fit_distance(): dmod = [0.0, 5.0, 10.0, -5.0, -10.0] filename = "./Girardi_Isochrones/" + name + "_0.dat" iso_data = fi.read_data(filename) if name != 'Pal5': clus_data = fi.read_data("noU_NGC_" + name + "_cluster.csv", ",") else: clus_data = fi.read_data("noU_" + name + "_cluster.csv", ",") if dist < 10.0: high = 7.0 elif dist < 20.0: high = 6.0 else: high = 5.5 clus = format_data(clus_data, dist, cuts=(3.5, high))
def fit_iso(name, dist, plot=1): if name != 'Pal5': clus_data = fi.read_data("noU_NGC_"+name+"_cluster.csv", ",") else: clus_data = fi.read_data("noU_"+name+"_cluster.csv", ",") if dist < 10.0: high = 7.0 elif dist < 20.0: high = 6.0 else: high = 5.5 clus = format_data(clus_data, dist, cuts=(3.5, high)) iso_data, age = [], [] for i in range(len(mod)): try: filename = "./Giso_shifted/"+name+mod[i]+".dat" iso_data.append(fi.read_data(filename)) age.append(d_age[i]) except IOError: print "!!! File not found - {0}".format(filename) continue """ Get R-squared values for each isochrone""" iso, RR = [], [] for i in range(len(iso_data)): iso.append(format_isochrone(iso_data[i], cuts=(7.0, 3.5))) results = poly.poly_fit(0.0,iso[i][:,0],iso[i][:,1],iso[i][:,2], 6, verbose=0) RR.append(R_squared(clus, results)) points = sc.array(zip(age, RR)) max = sc.ma.max(points[:,1]) RRmod = -1.0*(points[:,1] - max) sigma = 0.1*sc.ones(len(RRmod)) c, d, start = mc.do_MCMC(func.gaussian_function, sc.array([0.1, 0.0, 0.2]), sc.array([0.001,0.001,0.001]), points[:,0], RRmod, sigma, "test", number_steps=10000, save=0) best = gd.gradient_descent(func.gaussian_function, start, points[:,0], RRmod, sigma) # One-dimensional errors if len(RR) != 5: error = np.sqrt(abs((8.0*0.2*0.2) / (2.0*(RR[-1]-RR[0])) ) ) #Uses last point, which should be the '-2' else: error = np.sqrt(abs((8.0*0.2*0.2) / (RR[2] + RR[4] - 2.0*RR[0]))) # Hesssian error for one parameter fit # Plot these bad boys if plot==1: plt.figure(1) plt.subplot(211) plt.errorbar(clus[:,0], clus[:,1], yerr=clus[:,2], fmt='o') for i in range(len(iso)): plt.plot(iso[i][:,0], (iso[i][:,1]) ) plt.subplot(212) plt.scatter(points[:,0], points[:,1]) x = sc.arange(plt.xlim()[0], plt.xlim()[1], 0.01) y = -1.0*(func.gaussian_function(x, best)) + max #func.gaussian_function(x, best) # plt.plot(x,y, 'g-') plt.savefig(name+"_isoAn2.ps", papertype='letter') plt.close('all') return (sc.array(zip(age,RR)), best, error)
def do_wedgeplots(): files = glob.glob('stripe_[7-8][0-9].txt') print files for stripe in files: wedge = stripe[7:9] data = fi.read_data(stripe) plot_stripe_mur(data, int(wedge), ("wedge_" + wedge))
def plot_stuff(args): g_avg = 4.18 filename=args[0] data = f.read_data(filename) l, w = data.shape blue_base, yellow_base, red_base = data[0,1], data[0,5], data[0,9] """ 2nd file stuff """ """file2 = args[1] data2 = f.read_data(file2) l2, w2 = data2.shape blue_base2, yellow_base2, red_base2 = data2[0,1], data2[0,5], data2[0,9]""" fig = plt.figure(1) ax1 = fig.add_subplot(111) '''Plot Blue Box''' # plt.subplot(3,1,1) # plt.plot( data[:,0], (data[:,1]/blue_base), 'b-') # plt.plot( data[:,0], (data[:,2]/blue_base), 'y-') # plt.plot( data[:,0], (data[:,3]/blue_base), 'r-') '''Plot Yellow Box''' # plt.subplot(3,1,2) # plt.plot( data[:,0], (data[:,4]/yellow_base), 'b-') # plt.plot( data[:,0], (data[:,5]/yellow_base), 'y-') # plt.plot( data[:,0], (data[:,6]/yellow_base), 'r-') '''Plot Red Box''' # plt.subplot(3,1,3) # plt.plot( data[:,0], (data[:,7]/red_base), 'b-') # plt.plot( data[:,0], (data[:,8]/red_base), 'y-') # plt.plot( data[:,0], (data[:,9]/red_base), 'r-') '''Plot Only turnoff stars''' ax1.plot( data[:,0], (data[:,5]/yellow_base), 'y-') ax1.plot( data[:,0], (data[:,2]/yellow_base), 'b-') ax1.plot( data[:,0], (data[:,8]/yellow_base), 'r-') ax1.plot( data[:,0], ((data[:,5]+data[:,2]+data[:,8])/yellow_base), 'k-') ''' Agiain! For files ''' """ax1.plot( data2[:,0], (data2[:,5]/yellow_base), 'y:') ax1.plot( data2[:,0], (data2[:,2]/yellow_base), 'b:') ax1.plot( data2[:,0], (data2[:,8]/yellow_base), 'r:') ax1.plot( data2[:,0], ((data2[:,5]+data2[:,2]+data2[:,8])/yellow_base), 'k:')""" '''Fancy double x-axis plotting stuff''' x_tick = ax1.get_xticks() ax1.set_xticks(x_tick) plt.xticks(fontsize=10) plt.yticks(fontsize=10) plt.xlabel(r'$d_{\rm eff}$, kpc', fontsize=10) plt.ylabel(r'Fraction of Initial', fontsize=10) new_ticks = [] for i in range(len(x_tick)): if x_tick[i] == 0: new_ticks.append("") #(g_avg) else: new_ticks.append(round( (5.0*m.log10(x_tick[i]/0.01) + g_avg), 1) ) x_lim = ax1.get_xlim() new_lim = (g_avg), (5.0*m.log10(x_lim[1]/0.01) + g_avg) ax2 = ax1.twiny() ax2.set_xlim(new_lim) plt.xticks(x_tick, new_ticks) plt.xticks(fontsize=10) plt.xlabel(r'$g_{0}$', fontsize=10) plt.show() return 0
def unpack_data(resfile, namestr=None): """Get data from a custom file, and unpacks the correct entries into HistFits """ names, parameters, errors = [], [], [] readfile = open(resfile,"r") count, unpack = 1, 0 for line in readfile: if line.strip() == "": continue if line[0] == "#": continue if namestr == None: unpack = 1 else: if (re.search(namestr, line) != None): unpack = 1 # unpack wanted values if (unpack == 1) and (count == 1): names.append(line.strip()) count = 2 continue if (unpack == 1) and (count == 2): parameters.append(line.strip()) count = 3 continue if (unpack == 1) and (count == 3): errors.append(line.strip()) count = 1 unpack = 0 continue # skip unwanted values if (unpack == 0) and (count == 1): count = 2 continue if (unpack == 0) and (count == 2): count = 3 continue if (unpack == 0) and (count == 3): count = 1 unpack = 0 continue readfile.close() # if no matching sets were found, exit if len(names) == 0: print "!!! No entries matching description {0} were found !!!".format(namestr) return 0 fits = [] #print names, parameters, errors for i in range(len(names)): params = (parameters[i].strip("[] ")).split() for j in range(len(params)): params[j] = eval(params[j]) errs = (errors[i].strip("[] ")).split() for j in range(len(errs)): errs[j] = eval(errs[j]) fits.append(HistFit(names[i], params, errs)) """ Now get the files loaded in """ files = glob.glob("./An_Project/*"+namestr+"*.txt") for i in range(len(fits)): lookfor = str(fits[i].dist) # The "+1" will cause it to error out if no matching file is found for j in range(len(files)+1): if re.search(lookfor, files[j]) != None: break fits[i].insert_data(fi.read_data(files[j])) return fits
def show_lambda(): data = fi.read_data("./sep_lbr/s1-79.txt") x, y, z = coor.lbr2xyz(data[:, 0], data[:, 1], data[:, 2]) Xs, Ys, Zs, lam1, beta, r = sl.law_xyz2sgr_sun(x, y, z) data = fi.read_data("./sep_lbr/s1-82.txt") x, y, z = coor.lbr2xyz(data[:, 0], data[:, 1], data[:, 2]) Xs, Ys, Zs, lam2, beta, r = sl.law_xyz2sgr_sun(x, y, z) data = fi.read_data("./sep_lbr/s1-86.txt") x, y, z = coor.lbr2xyz(data[:, 0], data[:, 1], data[:, 2]) Xs, Ys, Zs, lam3, beta, r = sl.law_xyz2sgr_sun(x, y, z) plt.figure() plt.hist(lam3, 20) plt.hist(lam2, 20) plt.hist(lam1, 20) plt.show() plt.close('all')
def make_table_werrors(stripes, params): file2 = "../sgrnorth_paper/results_errors_final.txt" errors = fi.read_data(file2) for i, stripe in enumerate(stripes): if stripe == 9 or stripe == 22 or stripe == 82: theta, phi = (ma.pi - eval(params[i][6])), ( eval(params[i][7]) + ma.pi) #not sure if needed anymore else: theta, phi = float(params[i][6]), float(params[i][7]) theta, phi = coor.angle_bounds3(theta * deg, phi * deg, phi_max=180.0) theta, phi = theta * rad, phi * rad fit = [ stripe, float(params[i][3]), float(params[i][4]), float(params[i][5]), theta, phi, float(params[i][8]) ] # put it together out = str(stripe) + " & " for j in range(2, 8): out = out + str(round(fit[j - 1], 2)) + r" \pm " + str( round(errors[i, j], 2)) + r" & " out = out + r" \\" print out, "\n" back = [ stripe, ]
def metal_con(filename, distances, real_dist, bins=35, limits=(-3.1, 0.2), avgs=1, detection=1, tag="out"): """ main bit """ if filename[-4:] == '.csv': delim = ',' else: delim = None data = shift_data(fi.read_data(filename, delim), real_dist, distances[0]) mod_actual = 5.*(ma.log10(real_dist*1000) - 1.) mod_new = 5.*(ma.log10(distances[0]*1000) - 1.) mod = mod_actual - mod_new print "Effective Magnitude Shift = {0}, average g={1}".format(mod, sc.mean(data[:,2])) new_data = cut_data(data, 4,2,3,5, deff=0, modulus=mod, full=1) FeH = get_photo_metal(new_data[:,4],new_data[:,2],new_data[:,3]) ref_hist = np.histogram(FeH, bins, limits) hist = [] #Also iterate over several runs and average for i in range(len(distances)): print "#- Convolving to distance {0} kpc".format(distances[i]) if i==0: deff=0 else: deff=detection temp_hist = [] for j in range(avgs): #holds dist constant, applies appropriate errors for new distance new_data = con.convolve(data, real_dist, distances[i]) #shift data so detection efficiency works correctly; has no noticable effect if deff=0 new_data = shift_data(new_data, distances[0], distances[i]) # apply color cuts and detection efficiency to shifted and convolved data new_data = cut_data(new_data, 4,2,3,5, deff=deff, modulus=None, full=0) print "Average g = {0}, total stars = {1}".format(sc.mean(new_data[:,2]), len(new_data[:,0])) FeH = get_photo_metal(new_data[:,4],new_data[:,2],new_data[:,3]) temp_hist.append(np.histogram(FeH, bins, limits)) new_hist = avg_hists(temp_hist) hist.append(new_hist) plot_hists(hist, ref_hist, distances, tag) return hist
def dotties(): data = fi.read_data("../sgrnorth_paper/planefit_results.txt", ",") planes = [] for i in range(6): planes.append(data[i, :]) #for plane in planes: print plane dots = sc.zeros((6, 6)) for i in range(6): for j in range(6): dots[i, j] = (sc.arccos(planes[i][0] * planes[j][0] + planes[i][1] * planes[j][1] + planes[i][2] * planes[j][2])) * deg print dots print errors = sc.zeros((6, 6)) for i in range(6): for j in range(6): dotty = planes[i][0] * planes[j][0] + planes[i][1] * planes[j][ 1] + planes[i][2] * planes[j][2] factor = -1.0 / sc.sqrt(1 - dotty * dotty) print factor errors[i, j] = factor * ( planes[j][0] * planes[i][4] + planes[i][0] * planes[j][4] + planes[j][1] * planes[i][5] + planes[i][1] * planes[j][5] + planes[j][2] * planes[i][6] + planes[i][2] * planes[j][6]) * deg #if i==3 and j==5: print dotty print errors Sgr = [14.655645800014774, 2.2704309216189817, -5.8873772610912614] print "# - dist to Sgr Core:" for plane in planes: print (Sgr[0]*plane[0] + Sgr[1]*plane[1] + Sgr[2]*plane[2] + plane[3]), \ (Sgr[0]*plane[4] + Sgr[1]*plane[5] + Sgr[2]*plane[6] + plane[7])
def show_lambda(): data = fi.read_data("./sep_lbr/s1-79.txt") x,y,z = coor.lbr2xyz(data[:,0],data[:,1],data[:,2]) Xs,Ys,Zs,lam1,beta,r = sl.law_xyz2sgr_sun(x,y,z) data = fi.read_data("./sep_lbr/s1-82.txt") x,y,z = coor.lbr2xyz(data[:,0],data[:,1],data[:,2]) Xs,Ys,Zs,lam2,beta,r = sl.law_xyz2sgr_sun(x,y,z) data = fi.read_data("./sep_lbr/s1-86.txt") x,y,z = coor.lbr2xyz(data[:,0],data[:,1],data[:,2]) Xs,Ys,Zs,lam3,beta,r = sl.law_xyz2sgr_sun(x,y,z) plt.figure() plt.hist(lam3, 20) plt.hist(lam2, 20) plt.hist(lam1, 20) plt.show() plt.close('all')
def dotties(): data = fi.read_data("../sgrnorth_paper/planefit_results.txt", ",") planes = [] for i in range(6): planes.append(data[i,:]) #for plane in planes: print plane dots = sc.zeros((6,6)) for i in range(6): for j in range(6): dots[i,j] = (sc.arccos(planes[i][0]*planes[j][0] + planes[i][1]*planes[j][1] + planes[i][2]*planes[j][2]))*deg print dots print errors = sc.zeros((6,6)) for i in range(6): for j in range(6): dotty = planes[i][0]*planes[j][0]+planes[i][1]*planes[j][1]+planes[i][2]*planes[j][2] factor = -1.0 / sc.sqrt(1 - dotty*dotty) print factor errors[i,j] = factor*(planes[j][0]*planes[i][4] + planes[i][0]*planes[j][4] + planes[j][1]*planes[i][5] + planes[i][1]*planes[j][5] + planes[j][2]*planes[i][6] + planes[i][2]*planes[j][6])*deg #if i==3 and j==5: print dotty print errors Sgr = [14.655645800014774, 2.2704309216189817, -5.8873772610912614] print "# - dist to Sgr Core:" for plane in planes: print (Sgr[0]*plane[0] + Sgr[1]*plane[1] + Sgr[2]*plane[2] + plane[3]), \ (Sgr[0]*plane[4] + Sgr[1]*plane[5] + Sgr[2]*plane[6] + plane[7])
def plane_fit_table(): """ Make latex tables from a set of plane-fits """ data = fi.read_data("../sgrnorth_paper/planefit_results.txt", ",") for i in range(len(data[:,0])): string = "" for j in range(4): string = string + " & " + str(round(data[i,j],3)) + r"$\pm$" + str(round(data[i,j+4],3)) print string
def do_testwedgeplots(): files = glob.glob('single*.txt') print files for stripe in files: wedge = stripe[7:-4] data = fi.read_data(stripe) #plot_stripe_mur(data, 82, ("wedge_"+wedge)) plot_stripe_mug(data, 82, ("wedge_g_" + wedge))
def do_compare_wedges(file1="stars-82.txt", file2="Stripe82_coadd.csv", stripe=82, mag=0, size=1.0): """ Modify if size is not 1.0 """ one_run = fi.read_data(file1) or_l = len(one_run[:, 0]) or_hist = sv.plot_wedge_density(one_run, stripe, q=0.458, r0=19.4, name="_rho1", mag=mag, plot=0, size=size) coadd = fi.read_data(file2) ca_l = len(coadd[:, 0]) ca_hist = sv.plot_wedge_density(coadd, stripe, q=0.458, r0=19.4, name="_rho2", mag=mag, plot=0, size=size) # Separate into heights or_h = or_hist[:, 1] ca_h = ca_hist[:, 1] # Divide the first data set by the second if len(or_h) < len(ca_h): l = len(or_h) extra_h = -0.1 * sc.ones((len(ca_h) - l)) else: l = len(ca_h) extra_h = 0.1 * sc.ones((len(or_h) - l)) diff_h = sc.zeros(l) for i in range(l): diff_h[i] = (or_h[i] / ca_h[i]) out = sc.zeros((l, 3)) for i in range(l): out[i, 0], out[i, 1] = ca_hist[i, 0], diff_h[i] out[i, 2] = 1.0 #ma.sqrt(or_hist[i,2]*or_hist[i,2] + ca_hist[i,2]*ca_hist[i,2]) return out
def one_wedge_plots(): for stripe in stripes: data = fi.read_data("/home/newbym2/Desktop/star_holder/stars-"+str(stripe[0])+".txt") wedge=stripe[0] mu_lim = (stripe[1], stripe[2]) outname = "wedgeplot-"+str(stripe[0]) sv.plot_stripe_mur(data=data, wedge=wedge, mu_lim=mu_lim, outname=outname, r_lim=None, mag=0, scale=1, color=1, nu_flatten=0) print "# - Stripe {0} Complete".format(stripe[0])
def do_cuts(infile, delimiter, outfile, cuts): # Get data data = fi.read_data(infile, delimiter) # cut data for i in range(len(cuts)): data = do_one_cut(data, cuts[i]) # write data fi.write_data(data, outfile, delimiter) print "# - Finished with cuts"
def do_cuts(infile, delimiter, outfile, cuts): # Get data data = fi.read_data(infile, delimiter) # cut data for i in range(len(cuts)): data = do_one_cut(data, cuts[i]) # write data fi.write_data(data, outfile, delimiter) print "# - Finished with cuts"
def plane_fit_table(): """ Make latex tables from a set of plane-fits """ data = fi.read_data("../sgrnorth_paper/planefit_results.txt", ",") for i in range(len(data[:, 0])): string = "" for j in range(4): string = string + " & " + str(round( data[i, j], 3)) + r"$\pm$" + str(round(data[i, j + 4], 3)) print string
def rejection(filename, min=None, max=None, bin=0.2, reject=2.0, thresh=1000.0): data = fi.read_data(filename, ",") if min == None: min = np.ma.min(data[:,2]) if max == None: max = np.ma.max(data[:,2]) data_out = [] steps = int((max-min)/bin)+1 for i in range(steps): # build a data set for each bin data_temp = [] min_temp, max_temp = (min + i*bin), (min + (i+1)*bin) for j in range(len(data[:,0])): if (data[j,2] >= min_temp) and (data[j,2] < max_temp): data_temp.append(data[j,:]) print "number of stars in bin {0}: {1}".format(i, len(data_temp)) if len(data_temp)==0: continue #skip empty sets # continue checking for rejections until no rejections occur kills = [1] while len(kills) > 0: kills, new_temp = [], [] # pack the g-r values into a single list g_minus_r = [] for j in range(len(data_temp)): g_minus_r.append(data_temp[j][2]-data_temp[j][3]) g_minus_r = sc.array(g_minus_r) avg = sc.mean(g_minus_r) stdev = sc.std(g_minus_r) #print avg, stdev # Find the values that lie outside 'reject' sigma for j in range(len(g_minus_r)): diff = ma.fabs( g_minus_r[j] - avg ) if diff > (reject*stdev): kills.append(data_temp[j]) elif diff > thresh: kills.append(data_temp[j]) else: new_temp.append(data_temp[j]) data_temp = new_temp data_out = data_out + data_temp print "Stars kept in bin: {0}".format(len(data_temp)) # restructure data data_out = sc.array(data_out) print " {0} stars remaining out of {1} original stars".format(len(data_out[:,0]), len(data[:,0])) g_minus_r_ori = data[:,2] - data[:,3] g_minus_r_out = data_out[:,2] - data_out[:,3] # show plot, then ask to save data set fig = plt.figure() #plt.scatter(g_minus_r_ori, data[:,2], 2, marker='o', facecolor="r", edgecolor='face') plt.scatter(g_minus_r_out, data_out[:,2], 1, 'k', 'o') plt.ylim(max, min) plt.xlim(-1.0, 2.0) plt.ylabel(r'$g_0$') plt.xlabel(r"$(g-r)_0$") plt.show() fname = raw_input("save data? [filename to save, empty to skip]") if fname != "": fi.write_data(data_out, fname, header="#") print "# --- Done"
def sgr_plot(folder="./sep_lbr"): files = glob.glob(folder + "/*.txt") plt.figure(1) for file in files: data = fi.read_data(file) Xs, Ys, Zs, lam, beta, r = coor.lb2sgr(data[:, 0], data[:, 1], data[:, 2]) plt.scatter(lam, beta, s=1, c="black") plt.show() plt.close('all')
def multi_wedge_plots(): prefix, pack = ["bg-", "s1-", "s2-", "s3-"], [] folder = "/home/newbym2/Desktop/star_holder/sep_lbr/" for stripe in stripes: wedge=stripe[0] mu_lim = (stripe[1], stripe[2]) outname = "multi-wedgeplot-"+str(stripe[0]) for tag in prefix: pack.append(fi.read_data(folder+tag+str(wedge)+".txt")) sv.plot_separation_mur(pack, wedge, outname, mag=0, scale=1, color=1, mu_lim=mu_lim, r_lim=None, nu_flatten=0) print "# - Stripe {0} Complete".format(stripe[0])
def get_errors(file1="../sgrnorth_paper/results_BG_easyread.txt", file2="../sgrnorth_paper/results_errors.txt"): """ Takes in mu,nu,r errors, and turns them into a 3D "sigma sphere" for fitting a plane - GARBAGE""" wedges = [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 79, 82, 86] data = fi.read_data(file1, ",") errors = fi.read_data(file2) circ = [] # circular errors for i in range(len(data[:,0])): # Get x,y,z errors due to d_R x0, y0, z0 = coor.stream2xyz(0.0, 0.0, 0.0, data[i,4], errors[i,4], 0.0, 0.0, wedges[i]) # Get x,y,z errors due to d_mu - the difference between the original vector, and that vector shifted by d_mu x1, y1, z1 = coor.stream2xyz(0.0, 0.0, 0.0, data[i,4], data[i,5], 0.0, 0.0, wedges[i]) x2, y2, z2 = coor.stream2xyz(0.0, 0.0, 0.0, (data[i,4]+errors[i,3]), data[i,5], 0.0, 0.0, wedges[i]) x3, y3, z3 = (x2-x1), (y2-y1), (z2-z1) #print x0,y0,z0, x3,y3,z3 X = sc.sqrt(x0*x0 + x3+x3) Y = sc.sqrt(y0*y0 + y3+y3) Z = sc.sqrt(z0*z0 + z3+z3) print X,Y,Z circ.append(float(sc.sqrt(X*X+Y*Y+Z*Z) ) ) for item in circ: print item return circ
def metal_con(filename, distances, real_dist, bins=35, limits=(-3.1, 0.2), avgs=1, detection=1, tag="out"): """ main bit """ if filename[-4:] == '.csv': delim = ',' else: delim = None data = shift_data(fi.read_data(filename, delim), real_dist, distances[0]) mod_actual = 5. * (ma.log10(real_dist * 1000) - 1.) mod_new = 5. * (ma.log10(distances[0] * 1000) - 1.) mod = mod_actual - mod_new print "Effective Magnitude Shift = {0}, average g={1}".format( mod, sc.mean(data[:, 2])) new_data = cut_data(data, 4, 2, 3, 5, deff=0, modulus=mod, full=1) FeH = get_photo_metal(new_data[:, 4], new_data[:, 2], new_data[:, 3]) ref_hist = np.histogram(FeH, bins, limits) hist = [] #Also iterate over several runs and average for i in range(len(distances)): print "#- Convolving to distance {0} kpc".format(distances[i]) if i == 0: deff = 0 else: deff = detection temp_hist = [] for j in range(avgs): #holds dist constant, applies appropriate errors for new distance new_data = con.convolve(data, real_dist, distances[i]) #shift data so detection efficiency works correctly; has no noticable effect if deff=0 new_data = shift_data(new_data, distances[0], distances[i]) # apply color cuts and detection efficiency to shifted and convolved data new_data = cut_data(new_data, 4, 2, 3, 5, deff=deff, modulus=None, full=0) print "Average g = {0}, total stars = {1}".format( sc.mean(new_data[:, 2]), len(new_data[:, 0])) FeH = get_photo_metal(new_data[:, 4], new_data[:, 2], new_data[:, 3]) temp_hist.append(np.histogram(FeH, bins, limits)) new_hist = avg_hists(temp_hist) hist.append(new_hist) plot_hists(hist, ref_hist, distances, tag) return hist
def sgr_density_south(stripes, params): out = [] for i in range(15, 18): mu, r, theta, phi, wedge = eval(params[i][4]), eval(params[i][5]), \ eval(params[i][6]), eval(params[i][7]), stripes[i] print mu, r, theta, phi x, y, z = coor.stream2xyz(0.0, 0.0, 0.0, mu, r, theta, phi, wedge) Xs, Ys, Zs, lam, beta, r = sl.law_xyz2sgr_sun(x, y, z) print lam, beta, r, stripes[i] name = "./sep_lbr/s1-" + str(stripes[i]) + ".txt" data = fi.read_data(name, echo=1) wedge_norm = coor.stripe_normal(stripes[i]) plane_norm = [ 0.03176573688051381, 0.98687684085235916, 0.15831942063343135 ] stream_norm = [ sc.cos(phi) * sc.sin(theta), sc.sin(phi) * sc.sin(theta), sc.cos(theta) ] print wedge_norm, stream_norm dotty = wedge_norm[0] * stream_norm[0] + wedge_norm[1] * stream_norm[ 1] + wedge_norm[2] * stream_norm[2] #dotty2 = plane_norm[0]*wedge_norm[0] + plane_norm[1]*stream_norm[1] + plane_norm[2]*stream_norm[2] if dotty > 1.0: print "!!! Not a valid dot-product: {0}".format(dotty) H = abs(2.5 / dotty) #H2 = 2.5 / sc.sqrt(1 - (dotty2*dotty2)) print "H = ", H, dotty, sc.arccos(dotty) * 180.0 / ma.pi #, H2 count, in_1, in_2 = 0, 0.0, 0.0 lam_low, lam_high = 360.0, 0.0 for j in range(len(data[:, 0])): l, b, r = data[j, 0], data[j, 1], data[j, 2] count = count + 1 # Correct for completeness Deff = 1.0 / SDSS_eff(r) in_1 = in_1 + Deff in_2 = in_2 + Deff + 1.0 / TO_eff(r) x, y, z = coor.lbr2xyz(l, b, r) Xs, Ys, Zs, lam2, beta2, r2 = sl.law_xyz2sgr_sun(x, y, z) if lam2 < lam_low: lam_low = lam2 if lam2 > lam_high: lam_high = lam2 out.append([lam, count, in_1, in_2, in_2 / H]) print "--- Lambda Range: {0}:{1}".format(lam_low, lam_high) print "### Number of stars in stream: {0}".format(count) print "### Corrected for SDSS Eff.: {0}".format(in_1) print "### Corrected for SDSS/FTO Eff: {0}".format(in_2) for o in out: print o return sc.array(out)
def one_wedge_plots(): for stripe in stripes: data = fi.read_data("/home/newbym2/Desktop/star_holder/stars-" + str(stripe[0]) + ".txt") wedge = stripe[0] mu_lim = (stripe[1], stripe[2]) outname = "wedgeplot-" + str(stripe[0]) sv.plot_stripe_mur(data=data, wedge=wedge, mu_lim=mu_lim, outname=outname, r_lim=None, mag=0, scale=1, color=1, nu_flatten=0) print "# - Stripe {0} Complete".format(stripe[0])
def do_densityplots(): files = glob.glob('single*[0-4]_2.txt') #files = glob.glob('stripe_[7-8][0-9].txt') print files for stripe in files: #wedge = stripe[7:9] wedge = stripe[7:12] data = fi.read_data(stripe) plot_wedge_density(data, wedge=82, q=1.0, r0=19.5, mu_min=310.0, mu_max=419.0, streams=None, perturb=None, name=("hernquist_" + wedge), mag=0) #int(wedge)
def make_table_werrors(stripes, params): file2="../sgrnorth_paper/results_errors_final.txt" errors=fi.read_data(file2) for i, stripe in enumerate(stripes): if stripe==9 or stripe==22 or stripe==82: theta, phi = (ma.pi-eval(params[i][6]) ), (eval(params[i][7]) + ma.pi) #not sure if needed anymore else: theta, phi = float(params[i][6]), float(params[i][7]) theta, phi = coor.angle_bounds3(theta*deg, phi*deg, phi_max=180.0) theta, phi = theta*rad, phi*rad fit = [stripe, float(params[i][3]), float(params[i][4]), float(params[i][5]), theta, phi, float(params[i][8]) ] # put it together out = str(stripe)+" & " for j in range(2,8): out = out + str(round(fit[j-1],2))+r" \pm "+str(round(errors[i,j],2))+r" & " out = out + r" \\" print out, "\n" back = [stripe, ]
def multi_wedge_plots(): prefix, pack = ["bg-", "s1-", "s2-", "s3-"], [] folder = "/home/newbym2/Desktop/star_holder/sep_lbr/" for stripe in stripes: wedge = stripe[0] mu_lim = (stripe[1], stripe[2]) outname = "multi-wedgeplot-" + str(stripe[0]) for tag in prefix: pack.append(fi.read_data(folder + tag + str(wedge) + ".txt")) sv.plot_separation_mur(pack, wedge, outname, mag=0, scale=1, color=1, mu_lim=mu_lim, r_lim=None, nu_flatten=0) print "# - Stripe {0} Complete".format(stripe[0])
def compare_MW(): stripes1, params1 = load_params("../sgrnorth_paper/results_BG_easyread.txt") stripes2, params2 = load_params("../sgrnorth_paper/results_MW_easyread.txt") errors=fi.read_data("../sgrnorth_paper/results_errors_final.txt") table = [] for i in range(15): if float(params2[i][0]) > float(params1[i][0]): line = "YES " else: line = "NO " table_l = str(stripes1[i])+" & " for j in range(1,9): #print params1[i][j], params2[i][j], errors[i,(j-1)] diff = abs(float(params1[i][j])-float(params2[i][j])) / errors[i,(j-1)] #diff = 100.0*abs(float(params1[i][j])-float(params2[i][j])) / float(params1[i][j]) line = line + str(round(diff,2)) + "\t" #FOR JUST Dsigmas param = float(params2[i][j]) table_l = table_l + str(round(param,2)) + "/" + str(round(diff,2)) + " & " table.append(table_l[:-2]) print stripes1[i], stripes2[i], line for item in table: print item
def sgr_density_south(stripes, params): out = [] for i in range(15, 18): mu, r, theta, phi, wedge = eval(params[i][4]), eval(params[i][5]), \ eval(params[i][6]), eval(params[i][7]), stripes[i] print mu, r, theta, phi x,y,z = coor.stream2xyz(0.0, 0.0, 0.0, mu, r, theta, phi, wedge) Xs, Ys, Zs, lam, beta, r = sl.law_xyz2sgr_sun(x,y,z) print lam, beta, r, stripes[i] name = "./sep_lbr/s1-"+str(stripes[i])+".txt" data = fi.read_data(name, echo=1) wedge_norm = coor.stripe_normal(stripes[i]) plane_norm = [0.03176573688051381, 0.98687684085235916, 0.15831942063343135] stream_norm = [sc.cos(phi)*sc.sin(theta), sc.sin(phi)*sc.sin(theta), sc.cos(theta)] print wedge_norm, stream_norm dotty = wedge_norm[0]*stream_norm[0] + wedge_norm[1]*stream_norm[1] + wedge_norm[2]*stream_norm[2] #dotty2 = plane_norm[0]*wedge_norm[0] + plane_norm[1]*stream_norm[1] + plane_norm[2]*stream_norm[2] if dotty > 1.0: print "!!! Not a valid dot-product: {0}".format(dotty) H = abs(2.5 / dotty) #H2 = 2.5 / sc.sqrt(1 - (dotty2*dotty2)) print "H = ", H, dotty, sc.arccos(dotty)*180.0/ma.pi #, H2 count, in_1, in_2 = 0, 0.0, 0.0 lam_low, lam_high = 360.0, 0.0 for j in range(len(data[:,0])): l, b, r = data[j,0], data[j,1], data[j,2] count = count + 1 # Correct for completeness Deff = 1.0/SDSS_eff(r) in_1 = in_1 + Deff in_2 = in_2 + Deff + 1.0/TO_eff(r) x,y,z = coor.lbr2xyz(l,b,r) Xs, Ys, Zs, lam2, beta2, r2 = sl.law_xyz2sgr_sun(x,y,z) if lam2 < lam_low: lam_low = lam2 if lam2 > lam_high: lam_high = lam2 out.append([lam, count, in_1, in_2, in_2/H]) print "--- Lambda Range: {0}:{1}".format(lam_low, lam_high) print "### Number of stars in stream: {0}".format(count) print "### Corrected for SDSS Eff.: {0}".format(in_1) print "### Corrected for SDSS/FTO Eff: {0}".format(in_2) for o in out: print o return sc.array(out)
def compare_MW(): stripes1, params1 = load_params( "../sgrnorth_paper/results_BG_easyread.txt") stripes2, params2 = load_params( "../sgrnorth_paper/results_MW_easyread.txt") errors = fi.read_data("../sgrnorth_paper/results_errors_final.txt") table = [] for i in range(15): if float(params2[i][0]) > float(params1[i][0]): line = "YES " else: line = "NO " table_l = str(stripes1[i]) + " & " for j in range(1, 9): #print params1[i][j], params2[i][j], errors[i,(j-1)] diff = abs(float(params1[i][j]) - float(params2[i][j])) / errors[i, (j - 1)] #diff = 100.0*abs(float(params1[i][j])-float(params2[i][j])) / float(params1[i][j]) line = line + str(round(diff, 2)) + "\t" #FOR JUST Dsigmas param = float(params2[i][j]) table_l = table_l + str(round(param, 2)) + "/" + str(round( diff, 2)) + " & " table.append(table_l[:-2]) print stripes1[i], stripes2[i], line for item in table: print item
import math as m import numpy as np import scipy as sc import files as f import matplotlib #matplotlib.use('PS') import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator, FormatStrFormatter '''python script for plotting u,g,r error fits on the same pane Matthew Newby, May 4, 2011''' #Get data data1 = f.read_data('Pal5_Uerrors_cut2.csv', ',') data2 = f.read_data('err_pal5_stars.txt') #Assign data u_data = data1[:,2] u_err = data1[:,3] g_data = data2[:,2] g_err = data2[:,4] r_data = data2[:,3] r_err = data2[:,5] #Initialize error functions """ Old Values a_u = 0.02076735 b_u = 0.81309147 c_u = -19.61533299 a_g = 0.0 b_g = 0.790391
def fit_iso(name, dist, plot=1): if name != 'Pal5': clus_data = fi.read_data("noU_NGC_" + name + "_cluster.csv", ",") else: clus_data = fi.read_data("noU_" + name + "_cluster.csv", ",") if dist < 10.0: high = 7.0 elif dist < 20.0: high = 6.0 else: high = 5.5 clus = format_data(clus_data, dist, cuts=(3.5, high)) iso_data, age = [], [] for i in range(len(mod)): try: filename = "./Giso_shifted/" + name + mod[i] + ".dat" iso_data.append(fi.read_data(filename)) age.append(d_age[i]) except IOError: print "!!! File not found - {0}".format(filename) continue """ Get R-squared values for each isochrone""" iso, RR = [], [] for i in range(len(iso_data)): iso.append(format_isochrone(iso_data[i], cuts=(7.0, 3.5))) results = poly.poly_fit(0.0, iso[i][:, 0], iso[i][:, 1], iso[i][:, 2], 6, verbose=0) RR.append(R_squared(clus, results)) points = sc.array(zip(age, RR)) max = sc.ma.max(points[:, 1]) RRmod = -1.0 * (points[:, 1] - max) sigma = 0.1 * sc.ones(len(RRmod)) c, d, start = mc.do_MCMC(func.gaussian_function, sc.array([0.1, 0.0, 0.2]), sc.array([0.001, 0.001, 0.001]), points[:, 0], RRmod, sigma, "test", number_steps=10000, save=0) best = gd.gradient_descent(func.gaussian_function, start, points[:, 0], RRmod, sigma) # One-dimensional errors if len(RR) != 5: error = np.sqrt(abs( (8.0 * 0.2 * 0.2) / (2.0 * (RR[-1] - RR[0])))) #Uses last point, which should be the '-2' else: error = np.sqrt(abs( (8.0 * 0.2 * 0.2) / (RR[2] + RR[4] - 2.0 * RR[0]))) # Hesssian error for one parameter fit # Plot these bad boys if plot == 1: plt.figure(1) plt.subplot(211) plt.errorbar(clus[:, 0], clus[:, 1], yerr=clus[:, 2], fmt='o') for i in range(len(iso)): plt.plot(iso[i][:, 0], (iso[i][:, 1])) plt.subplot(212) plt.scatter(points[:, 0], points[:, 1]) x = sc.arange(plt.xlim()[0], plt.xlim()[1], 0.01) y = -1.0 * (func.gaussian_function( x, best)) + max #func.gaussian_function(x, best) # plt.plot(x, y, 'g-') plt.savefig(name + "_isoAn2.ps", papertype='letter') plt.close('all') return (sc.array(zip(age, RR)), best, error)
plt.xlabel(r'Sun-centered r (kpc)') plt.ylabel(r'density') plt.show() """ # Plotting Code fig = plt.figure() ax = Axes3D(fig) #ax.plot([-5.0,5.0],[0.0, 0.0],[0.0, 0.0], c='yellow') #data_b = fi.read_data("Backgen82.txt") #xb, yb, zb = co.lbr2xyz(data_b[:,0], data_b[:,1], data_b[:,2]) #ax.scatter(xb,yb,zb, facecolor='k', edgecolor='k') data_p = fi.read_data("full_test_82.txt") xp, yp, zp = co.lbr2xyz(data_p[:,0], data_p[:,1], data_p[:,2]) ax.scatter(xp,yp,zp, c='r') #data_s = fi.read_data("stream_test.txt") #xs, ys, zs = co.lbr2xyz(data_s[:,0], data_s[:,1], data_s[:,2]) #u,v,w = twg.generate_stream(1000, -2.2, 1.9, 2.0) #xs,ys,zs = [],[],[] #for i in range(len(u)): # x_h,y_h,z_h = co.stream2xyz(u[i],v[i],w[i],360.0, 21.0, 0.0, 0.0, 82) # xs.append(x_h), ys.append(y_h), zs.append(z_h) #ax.scatter(xs,ys,zs, facecolor='b', edgecolor='b') #mu, nu, r1 = sc.array([360.0, 360.0]),sc.array([-1.25, -1.25]),sc.array([10.0, 30.0]) #x,y,z = co.GC2xyz(mu, nu, r1, 82) #ax.plot(x,y,z, c='r') #mu2, nu2, r2 = sc.array([360.0, 360.0]),sc.array([1.25, 1.25]),sc.array([10.0, 30.0])
pos_y = 1 subs = [] """Plot Initializations""" fig = plt.figure() plt.subplots_adjust(hspace=0.001, wspace=0.001) #plt.title(save_name) #plt.xlabel('g-r') #plt.ylabel('Mg') for i in range(len(gc_names)): name = gc_names[i] distance = gc_distances[i] #metal = gc_metals[i] HB_limit = cutoff[i] """Get Data""" if (i == 10): data_iso = f.read_data(('Iso_new_Pal5.dat')) data_clus = f.read_csv('noU_Pal5_cluster.csv') #'HR_Pal_5_cluster.csv' data_fid = f.read_data(('Pal5_2_fiducial_out.txt')) else: data_iso = f.read_data(('Iso_new_' + name + '.dat')) #data_iso = f.read_data( ('Iso_series_'+name+'_A.dat') ) data_clus = f.read_csv('noU_NGC_' + name + '_cluster.csv') #'HR_NGC_'+name+'_cluster.csv' data_fid = f.read_data( ('NGC_' + name + '_' + str(fid_res[i]) + '_fiducial_out.txt')) """Setup Data for Plotting""" mm = -0.01463023 bb = 0.08928602 iso_x_list, iso_y_list = [], [] for j in range(len(data_iso[:, 8])): if (data_iso[j, 8] > HB_limit):
def plot_stuff(args): g_avg = 4.18 filename = args[0] data = f.read_data(filename) l, w = data.shape blue_base, yellow_base, red_base = data[0, 1], data[0, 5], data[0, 9] """ 2nd file stuff """ """file2 = args[1] data2 = f.read_data(file2) l2, w2 = data2.shape blue_base2, yellow_base2, red_base2 = data2[0,1], data2[0,5], data2[0,9]""" fig = plt.figure(1) ax1 = fig.add_subplot(111) '''Plot Blue Box''' # plt.subplot(3,1,1) # plt.plot( data[:,0], (data[:,1]/blue_base), 'b-') # plt.plot( data[:,0], (data[:,2]/blue_base), 'y-') # plt.plot( data[:,0], (data[:,3]/blue_base), 'r-') '''Plot Yellow Box''' # plt.subplot(3,1,2) # plt.plot( data[:,0], (data[:,4]/yellow_base), 'b-') # plt.plot( data[:,0], (data[:,5]/yellow_base), 'y-') # plt.plot( data[:,0], (data[:,6]/yellow_base), 'r-') '''Plot Red Box''' # plt.subplot(3,1,3) # plt.plot( data[:,0], (data[:,7]/red_base), 'b-') # plt.plot( data[:,0], (data[:,8]/red_base), 'y-') # plt.plot( data[:,0], (data[:,9]/red_base), 'r-') '''Plot Only turnoff stars''' ax1.plot(data[:, 0], (data[:, 5] / yellow_base), 'y-') ax1.plot(data[:, 0], (data[:, 2] / yellow_base), 'b-') ax1.plot(data[:, 0], (data[:, 8] / yellow_base), 'r-') ax1.plot(data[:, 0], ((data[:, 5] + data[:, 2] + data[:, 8]) / yellow_base), 'k-') ''' Agiain! For files ''' """ax1.plot( data2[:,0], (data2[:,5]/yellow_base), 'y:') ax1.plot( data2[:,0], (data2[:,2]/yellow_base), 'b:') ax1.plot( data2[:,0], (data2[:,8]/yellow_base), 'r:') ax1.plot( data2[:,0], ((data2[:,5]+data2[:,2]+data2[:,8])/yellow_base), 'k:')""" '''Fancy double x-axis plotting stuff''' x_tick = ax1.get_xticks() ax1.set_xticks(x_tick) plt.xticks(fontsize=10) plt.yticks(fontsize=10) plt.xlabel(r'$d_{\rm eff}$, kpc', fontsize=10) plt.ylabel(r'Fraction of Initial', fontsize=10) new_ticks = [] for i in range(len(x_tick)): if x_tick[i] == 0: new_ticks.append("") #(g_avg) else: new_ticks.append( round((5.0 * m.log10(x_tick[i] / 0.01) + g_avg), 1)) x_lim = ax1.get_xlim() new_lim = (g_avg), (5.0 * m.log10(x_lim[1] / 0.01) + g_avg) ax2 = ax1.twiny() ax2.set_xlim(new_lim) plt.xticks(x_tick, new_ticks) plt.xticks(fontsize=10) plt.xlabel(r'$g_{0}$', fontsize=10) plt.show() return 0
""" @author: Yulu Su """ #https://towardsdatascience.com/how-to-forecast-sales-with-python-using-sarima-model-ba600992fa7d import warnings import itertools import numpy as np import matplotlib.pyplot as plt warnings.filterwarnings("ignore") import pandas as pd import statsmodels.api as sm import files data = files.read_data(r'LeanHogsFutures.xlsx') data = pd.DataFrame(data['Close'].dropna()) #[data.index > dt.datetime(2010, 1, 1)].dropna()) data = data.resample('M').mean() # resample daily data to monthly data data = data['1992':'2004'] data.to_csv(r'LeanHogsFu.csv') lh = np.log(data / data.shift(1)).dropna()*100 # d 1 lh.to_csv(r'leanhogsfudif.csv') lh.plot(figsize=(19, 4)) plt.show() #test stationarity from statsmodels.tsa.stattools import adfuller #Perform Dickey-Fuller test: print('Results of Dickey-Fuller Test:') dftest = adfuller(pd.Series(lh['Close']), autolag='AIC') dfoutput = pd.Series(dftest[0:4], index=['Test Statistic','p-value','#Lags Used','Number of Observations Used'])
for i in range(len(data[:,0])): if low_cut != None: if data[i,col] < low_cut: continue if high_cut != None: if data[i,col] > high_cut: continue holder.append(data[i,:]) return sc.array(holder) """ Main Cutting Function """ def cut_data(data, *args): new_data = [] if len(args) == 0: print "!!! NO ARGUMENTS DEFINING CUT !!!\n" usage() sys.exit(2) for arg in args: if new_data == []: new_data = cut_once(data, arg) else: new_data = cut_once(new_data, arg) return new_data if __name__ == "__main__": import files as fi file_in = "noU_NGC_5466_background.csv" data = fi.read_data(file_in, ",") data_out = cut_data(data, (2, 20.0, 21.0), (3, None, 20.0)) fi.write_data(data_out, (file_in[:-4]+"_cut.txt")) #print data_out #print "length of data:", len(data[:,0]), "; length of cut data:", len(data_out[:,0])
line_y = function(line_x, params) #print line_x, '\n', line_y plt.figure(1) plt.errorbar(data_x, data_y, yerr=y_err, xerr=x_err, ecolor='b', fmt=None) plt.scatter(data_x, data_y, s=1, marker='o', c='black') plt.plot((line_x), (line_y), c='g') #plt.title(title[0]) plt.xlabel(title[1], fontsize=10) plt.ylabel(title[2], fontsize=10) if save == 1: save_file = save_name + '_pltfunc.ps' plt.savefig(save_file, papertype='letter') print '#---function and fit plot saved as', save_file else: plt.show() plt.close('all') print '#---Done with function and data plot' return 1 if __name__ == "__main__": import functions as func import files as f data = f.read_data('test_data_out.txt') parameters = [5.0, 0.0, 2.0] plot_function(data[:, 0], data[:, 1], func.Nth_order_polynomial, parameters, y_err=data[:, 2], save=0)
import glob '''python script for running gc scripts Matthew Newby, Sept 6, 2010''' '''Add Limits to parameters and data! ''' #MAIN #Setup variables filename = glob.glob("./An_Project/*real_noG1_20.0*.txt") print filename function = func.double_gaussian for i in range(len(filename)): #Load data uid = "fit_" + filename[i][-13:-4] identifier = [uid, 'A', 'B', 'C', 'D', 'F', 'G', 'H'] data = f.read_data(filename[i]) #Set data #columns in data file for respective values x_col, y_col, sig_col = (data[:, 1] + 0.05), data[:, 0], func.poisson_errors(data[:, 0]) """ Initializations - choose correct number of parameters""" """ 6 params """ start_params = sc.array( [5.0, -1.0, 1.0, 2.5, 1.0, 0.5]) #A function that gives a good start is nice here steps = sc.array([0.1, 0.01, 0.01, 0.1, 0.01, 0.01]) #1/10 of expected parameter order is usually good """ fit data """ MCMC_fit, errors, best_fit = mc.do_MCMC(function, start_params,
import math as m import numpy as np import scipy as sc import files as f import matplotlib as mpl import matplotlib import matplotlib.pyplot as plt '''python script for SEGUE plate plotting Matthew Newby, July 22, 2010''' file1 = "SEGUE_plates.dat" #file2 = "SEGUE_test.dat" data1 = f.read_data(file1) #data2 = f.read_data(file2) l1, w1 = data1.shape #l2, w2 = data2.shape() in_disk = 0 plt.figure() for i in range (l1): if (abs(data1[i,5]) <= 20.0): plt.scatter(data1[i,4], data1[i,5], c='blue', marker='o') print str(data1[i,0]), "is in the disk, b =", data1[i,5] in_disk = in_disk + 1 else: plt.scatter(data1[i,4], data1[i,5], c='red', marker='x') if (data1[i,2] < -1000.0): faint_id = "---" else: faint_id = str(data1[i,2]) plate_id = str(data1[i,0]) + "/" + faint_id plt.text(data1[i,4], data1[i,5], (plate_id), fontsize=8)
import math as ma import numpy as np import scipy as sc import files as fi import matplotlib #matplotlib.use('PS') import matplotlib.pyplot as plt import functions as func import astro_coordinates as coor '''python script for quickly analyzing data. Matthew Newby, November 15,2010''' data = fi.read_data("Grillmair_2011_isochrone.dat") data2 = fi.read_data("isochrone_8gyr_n1p0.dat") data3 = fi.read_data("isochrone_7gyr_n0p8.dat") data4 = fi.read_data("isochrone_6gyr_n0p8.dat") g = coor.getg(9.7, data[:, 8]) g_minus_r = data[:, 8] - data[:, 9] g_minus_i = data[:, 8] - data[:, 10] g2 = coor.getg(9.7, data2[:, 8]) #+0.43 g3 = coor.getg(9.7, data3[:, 8]) #+0.63 g4 = coor.getg(9.7, data4[:, 8]) #+0.63 s1 = 0.41 s2 = 0.61 s3 = 0.52 M1 = 15.0 #coor.getM(15.0, 9.7) M2 = 19.5 #coor.getM(19.5, 9.7)
import math as m import numpy as np import scipy as sc import files as f import matplotlib #matplotlib.use('PS') import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator, FormatStrFormatter '''python script for plotting u,g,r error fits on the same pane Matthew Newby, May 4, 2011''' #Get data data1 = f.read_data('Pal5_Uerrors_cut2.csv', ',') data2 = f.read_data('err_pal5_stars.txt') #Assign data u_data = data1[:, 2] u_err = data1[:, 3] g_data = data2[:, 2] g_err = data2[:, 4] r_data = data2[:, 3] r_err = data2[:, 5] #Initialize error functions """ Old Values a_u = 0.02076735 b_u = 0.81309147 c_u = -19.61533299 a_g = 0.0 b_g = 0.790391 c_g = -19.8928
import functions as func import math as ma import numpy as np import scipy as sc import fit as fit import matplotlib import matplotlib.pyplot as plt run = range(1,6) start_params = [3.0, 17.0, 0.75, 5.0] bins=20 #run=[1] #debug for i in run: print "# --- Fitting region {0}".format(i) data = fi.read_data("/home/newbym2/Dropbox/Research/Cetus_Polar/bhb_dmod"+str(i)+".txt", skip=1) print "# --- l-coordinate mean, std: {0}, {1}".format(np.mean(data[:,0]), np.std(data[:,0]) ) b_hist, b_edges = np.histogram(data[:,1], bins, range=[80.0, 180.0]) b_err = func.poisson_errors(b_hist) b_wid = (np.ma.max(data[:,1]) - np.ma.min(data[:,1]) ) / bins d_hist, d_edges = np.histogram(data[:,2], bins, range=[16.0, 19.0]) d_err = func.poisson_errors(d_hist) d_wid = (np.ma.max(data[:,2]) - np.ma.min(data[:,2]) ) / bins # Initialize fitter = fit.ToFit(d_edges[:-1]+(d_wid/2.0), d_hist , d_err) fitter.function=func.gauss_plus_floor fitter.update_params(start_params) fitter.step = [0.01, 0.01, 0.01, 0.01] fitter.param_names = ["amp", "mu", "sigma", "floor"] fitter.min = [None, None, 0.0, None] fitter.max = [None, None, None, None]
plt.close('all') return 1 if __name__ == '__main__': print '#- number of arguments:', (len(sys.argv)-1) # Read arguments filename = sys.argv[1] column = int(sys.argv[2]) size = float(sys.argv[3]) if len(sys.argv) > 4: spread = [float(sys.argv[4]), float(sys.argv[5])] else: spread = [] if len(sys.argv) > 6: name = sys.argv[6] else: name = 'quick' # Load Data suffix = filename[-4:] if suffix == '.txt': data = f.read_data(filename) elif suffix == '.csv': data = f.read_csv(filename) # Run scripts to_bin = data[:,column] reg_hist = make_hist(to_bin, size, spread) plot_histogram(reg_hist, size, name=(name+'_normal') ) f.write_data(reg_hist, fileout=(name+'_normal.txt'), header='# Centers, Counts') cum_hist = cumulative_hist(to_bin, size, spread) plot_histogram(cum_hist, size, name=(name+'_cumulative') ) f.write_data(cum_hist, fileout=(name+'_cumulative.txt'), header='# Centers, Counts') print '#done with quick histograms'
""" # reference #https://www.statsmodels.org/dev/vector_ar.html #https://towardsdatascience.com/vector-autoregressions-vector-error-correction-multivariate-model-a69daf6ab618 #https://towardsdatascience.com/prediction-task-with-multivariate-timeseries-and-var-model-47003f629f9 import numpy as np import pandas as pd import statsmodels.api as sm from statsmodels.tsa.api import VAR import datetime as dt import matplotlib.pyplot as plt import files #read CME lean hogs futures' data from excel lh = files.read_data(r'LeanHogsFutures.xlsx') #read CME corn futures' data from excel cn = files.read_data(r'CornFutures.xlsx') #read CME live cattle futures' data from excel lc = files.read_data(r'LivecCattleFutures.xlsx') data = pd.DataFrame({'LeanHogs': lh['Close']}) data = data.join(pd.DataFrame({'Corn': cn['Close']})) data = data.join(pd.DataFrame({'Livecattle': lc['Close']})) data = data.resample('M').mean() # resample daily data to monthly data data = np.log(data / data.shift(1)).dropna() # d 1 data = 100 * data['1992':'2004'] #forward fill the NA data = data.fillna(method='ffill')
holder.append(sort.data2[i,:]) fi.write_data(sc.array(holder), files[2]) s3 = len(holder) print "# - {0} matched stars, {1} unmatched in file 1, {2} unmatched in file 2".format(s1,s2,s3) def create_indices(sorted_data, sub_list, c=0): """ Creates a set of indices for the sorted_data, at intervals of sub_list c is the column from which to index """ index = [] for i in range(len(sorted_data[:,c])): if (i % sub_list) == 0: index.append((sorted_data[i,c], i)) return index if __name__ == "__main__": d1 = fi.read_data("stars-10-OLD.txt") d2 = fi.read_data("stars-10-NEW.txt") sort = Compare(d1, d2, c1=0, c2=0, sub=100) match_stars(sort, 5.0*arcsec) separate_stars(sort, ["matched-10-2.txt", "unmatched-10-old-2.txt", "unmatched-10-new-2.txt"]) print "# --- Done" """ def get_index(min, max, data): base = sc.arange(min, (max+1), 1.0) # "+1" prevents index overflow during matching index, k = [], 0 for i in range(len(data[:,0])): if k == (len(base)-1): break if data[i,0] > base[k]: index.append(i)
def sgr_density(stripes, params): # get lambda for stripes holder = [] for i in range(len(stripes)): mu, r, theta, phi, wedge = eval(params[i][4]), eval(params[i][5]), \ eval(params[i][6]), eval(params[i][7]), stripes[i] x,y,z = coor.stream2xyz(0.0, 0.0, 0.0, mu, r, theta, phi, wedge) Xs, Ys, Zs, lam, beta, r = sl.law_xyz2sgr_sun(x,y,z) #if lam > 180.0: lam = lam - 360.0 #lam = -lam print lam, beta, r, stripes[i] holder.append([lam, beta, r]) Xs, Ys, Zs, lam, beta, r = sl.law_xyz2sgr_sun(14.655646, 2.270431, -5.887377) print lam, beta, r # Get distances as a function of Lamda, using straight pipes to connect points. LAB = [] # lambda, A, B such that: R = A(lam) + B; C,D st beta = C(lam) + D for i in range(15-1): # all but end A = (holder[i+1][2]-holder[i][2])/(holder[i+1][0]-holder[i][0]) # R2-R1/L2-L1 B = holder[i][2] - A*holder[i][0] # R1 - A*L1 C = (holder[i+1][1]-holder[i][1])/(holder[i+1][0]-holder[i][0]) # B2-B1/L2-L1 D = holder[i][1] - C*holder[i][0] # B1 - A*L1 LAB.append([holder[i+1][0], A, B, C, D]) # get lambda range for northern Sgr 15 N stripes, 0-14 -> 9-23 low_lam, high_lam = 200.0, 314.8 # from Sgr stripes: (200.025901082, 314.707561185) size = (high_lam - low_lam) / 15.0 print "# - LAMBDA BIN SIZE: {0}".format(size) out = [] for i in range(15): killed = 0 print "# - Lambda wedge {0}:".format(i) num = str(i) name = "./Lambda_outs/lamsim_out_"+num+".txt" data = fi.read_data(name, echo=1) count, in_1, in_2, in_0 = 0, 0.0, 0.0, 0.0 sigma = params[i][8] for j in range(len(data[:,0])): lam, beta, r = data[j,0], data[j,1], data[j,2] count = count + 1 index = 0 while data[j,0] > LAB[index][0]: index = index + 1 if (index == len(LAB)-1): break # correct for missing far edge by counting all near edge and doubling A, B = LAB[index][1], LAB[index][2] if r > (A*lam + B)/sc.cos(beta): killed=killed+1; continue #D = (0.295*lam - 42.601)/sc.cos(beta) #if r > D: killed=killed+1; continue # correct for missing side edge by counting inner and doubling #C, D = LAB[index][3], LAB[index][4] #if beta > (C*lam + D): continue # Correct for completeness Deff = 1.0/SDSS_eff(r) in_0 = in_0 + 1.0 in_1 = in_1 + Deff in_2 = in_2 + Deff/TO_eff(r) out.append([(low_lam+(size*i)+(size*0.5)), count, in_1, in_2, in_2/size]) print "### Number of stars in stream: {0}".format(count) print "### KILLED: {0}".format(killed) print "### Remaining Stars: {0}".format(in_0*1.0) print "### Corrected for SDSS Eff.: {0}".format(in_1*2.0) print "### Corrected for SDSS/FTO Eff: {0}".format(in_2*2.0) #print out return sc.array(out)
import scipy as sc import math as m import numpy as np import matplotlib #matplotlib.use('PS') import matplotlib.pyplot as plt """This program plots GC fit results as a ganged plot Matthew Newby (RPI), Dec 11, 2010 """ save = 1 save_name = 'GC_results_combined_metal.ps' data = f.read_data('results_new_corrected_singles.txt') names = ['NGC 4147', 'NGC 5024', 'NGC 5053', 'NGC 5272', 'NGC 5466', 'NGC 5904', 'NGC 6205', 'NGC 7078', 'NGC 7089', 'Pal 5'] #'NGC 6341', x_column = 13 #13=CG97 metallicity, 11=fit age, 0 = distance # !!! Order for Offsets: sig_r, sig_l, mu, turnoff """ Metallicity Offsets """ x_offset = [ [0.01, 0.01, 0.01, 0.01], [0.01, 0.01, 0.01, 0.01], [0.01, 0.01, 0.01, 0.01], [-0.11, -0.1, -0.1, -0.1], [-0.1, 0.01, 0.01, -0.1], [0.01, 0.01, 0.01, 0.01], [-0.02, -0.1, 0.01, 0.01], [0.01, 0.01, 0.01, 0.01], [0.01, 0.01, 0.01, 0.01], [0.01, 0.01, 0.01, 0.01] ]
import csv import scipy as sc import math as m import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import files as f """This program plots data from the gc project Matthew Newby (RPI), Jan 28, 2010 """ #Data data = f.read_data('best_results_firstpoint.txt') names = ['NGC 4147', 'NGC 5024', 'NGC 5053', 'NGC 5272', 'NGC 5466', 'NGC 5904', 'NGC 6205', 'NGC 7078', 'NGC 7089', 'Pal 5'] #'NGC 6341', columns = ['Distance(kpc)', 'Fwhm', '$\mu$ (magnitudes)', '$\sigma_l$', '$\sigma_r$', 'Amplitude (counts)', '$\mu$ error', '$\sigma_l$ error', '$\sigma_r$ error', 'Amplitude error', 'Average Age(Gyr)', 'Fit Age(Gyr)', '<[Fe/H]> (Harris)', '<[Fe/H]> (CG97 Scale)', 'Harris Distance(kpc)'] #x values i = 13 #y values j = 3 #y_error values e = j + 4 plt.figure(1)
cluster_name = 'NGC_6205_CG97_clean2' distance = 7.7 #starting distance save_data = 0 #saves isocrone files as output if set to 1 #initializations #plot_title = cluster_name + ', isocrone(blue) and fiducial fit(green)' file_str = 'HRISO_compare_' + cluster_name #plot file string #load in and prepare SDSS data gc_data = f.read_csv(data_file) gc_l, gc_w = gc_data.shape gc_array = sc.zeros((gc_l, 2), float) gc_array[:, 0] = gc_data[:, 2] - 5. * (m.log10(distance * 1000) - 1.0) #'g' values gc_array[:, 1] = (gc_data[:, 2] - gc_data[:, 3]) #'g-r' values #load in and prepare isocrone data iso_data = f.read_data(iso_file) #<--might fail due to leading whitespace? iso_l, iso_w = iso_data.shape iso_in = sc.zeros((iso_l, 2), float) iso_in[:, 0] = iso_data[:, 8] #'Mg' values iso_in[:, 1] = (iso_data[:, 8] - iso_data[:, 9]) #'g-r' values #Chop up isocrone so that the bounds are equal gminusr = 0.6 for i in range(1, iso_l): if ((iso_in[i, 1] < gminusr) and (iso_in[(i - 1), 1] > gminusr)): high_g = i if ((iso_in[i, 1] > gminusr) and (iso_in[(i - 1), 1] < gminusr)): low_g = i break iso_array = iso_in[high_g:low_g, :] iso_l, iso_w = iso_array.shape #break up data CMD into strips in Mg
def width_plot(stripes, params): data = fi.read_data("../sgrnorth_paper/sgrNorth_density_sim.txt", ",") #Ben = fi.read_data("../sgrnorth_paper/bensgr_lam_bins.dat") #Law = fi.read_data("../sgrnorth_paper/lawsgr_lam_bins.dat") Law = fi.read_data("../sgrnorth_paper/lawsgrTRX_lam_binsC.dat") sph = fi.read_data("../sgrnorth_paper/lawsgrSPH_lam_binsC.dat") obl = fi.read_data("../sgrnorth_paper/lawsgrOBL_lam_binsC.dat") pro = fi.read_data("../sgrnorth_paper/lawsgrPRO_lam_binsC.dat") LM10 = fi.read_data("../sgrnorth_paper/lawsgrTRX_widthsC.dat") #2 wp = fi.read_data("../sgrnorth_paper/lawsgrPRO_widthsC.dat") ws = fi.read_data("../sgrnorth_paper/lawsgrSPH_widthsC.dat") wo = fi.read_data("../sgrnorth_paper/lawsgrOBL_widthsC.dat") errors = sc.array([0.775105, 0.47734, 0.836774, 1.882841, 0.932078, 1.531246, 1.653404, 0.593513, 0.853309, 0.469178, 3.053077, 0.314356, 0.388961, 1.21, 2.330186, 0.142532, 0.989839, 0.541965]) sigma, slam = [], [] for i in range(len(stripes)): mu, r, theta, phi, wedge = eval(params[i][4]), eval(params[i][5]), \ eval(params[i][6]), eval(params[i][7]), stripes[i] #print mu, r, theta, phi x,y,z = coor.stream2xyz(0.0, 0.0, 0.0, mu, r, theta, phi, wedge) Xs, Ys, Zs, lam, beta, r = sl.law_xyz2sgr_sun(x,y,z) slam.append(lam) for param in params: sigma.append(2.35482*eval(param[8])) fig = plt.figure(1) plt.subplots_adjust(hspace=0.001, wspace=0.001) # density along stream plot sp1 = plt.subplot(211) color = ['w', 'w', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'w', 'w', 'w', 'k', 'k', 'k'] #plt.scatter(data[:,0], data[:,4]*1.0, facecolor=color, marker="s", # label="Expected Counts") plt.scatter(data[:,0], data[:,4], facecolor=color, marker="^", label="__nolabel__") plt.scatter(data[:,0], data[:,1]*(data[:,4]/data[:,2]), facecolor=color, marker="o", label="__nolabel__") #plt.errorbar([315.0, 315.0, 315.0, 312.0, 312.0, 312.0], [1000, 2000, 3000, 1000, 2000, 3000], # yerr=[39.2, 51.5, 80.0, 33.2, 43.6, 53.8], fmt="o", markersize=1, # mfc="red", ecolor="red", label="Typical Errors") #71.8 #plt.plot(Ben[:,0], Ben[:,1]*0.2, "k--") #0.1 a, b = 21, 23 plt.plot(obl[:a,0], obl[:a,1]*7.0, "r:", label="Oblate") plt.plot(obl[b:,0], obl[b:,1]*7.0, "r:", label=None) plt.plot(sph[:a,0], sph[:a,1]*7.0, "k-.", label="Spherical", linewidth=1.5) plt.plot(sph[b:,0], sph[b:,1]*7.0, "k-.", label=None, linewidth=1.5) plt.plot(pro[:a,0], pro[:a,1]*7.0, "b--", label="Prolate") plt.plot(pro[b:,0], pro[b:,1]*7.0, "b--", label=None) plt.plot(Law[:a,0], Law[:a,1]*6.0, "k-", label="L&M10 Nbody") # 1.5 plt.plot(Law[b:,0], Law[b:,1]*6.0, "k-", label=None) # 1.5 #sp1.annotate('Triaxial', xy=(178, 3200), xytext=(210, 3650), fontsize=8, # arrowprops=dict(facecolor='black', shrink=0.05, width=0.5, headwidth=3) ) #sp1.annotate('Prolate', xy=(192, 3000), xytext=(215, 3350), fontsize=8, # arrowprops=dict(facecolor='black', shrink=0.05, width=0.5, headwidth=3) ) #sp1.annotate('Spherical', xy=(199, 2750), xytext=(220, 3050), fontsize=8, # arrowprops=dict(facecolor='black', shrink=0.05, width=0.5, headwidth=3) ) #sp1.annotate('Oblate', xy=(205, 2500), xytext=(225, 2800), fontsize=8, # arrowprops=dict(facecolor='black', shrink=0.05, width=0.5, headwidth=3) ) #plt.scatter(Ben[:,0], Ben[:,1]*0.5, facecolor="blue", marker="x") #plt.scatter(Law[:,0], Law[:,1], facecolor="red", marker="+") spoof1 = plt.scatter(180.0, -10.0, facecolor='k', marker="^", label="Expected Counts") #spoof spoof2 = plt.scatter(180.0, -10.0, facecolor='k', marker="o", label="Raw Counts") #spoof plt.setp(sp1.get_xticklabels(), visible=False) plt.ylim(0.0, 6000.0) plt.ylabel("Stars per degree", fontsize=12) # legend leg1 = sp1.legend(loc='upper center', numpoints=2) for t in leg1.get_texts(): t.set_fontsize(10) # ---------------- FWHM v lambda plot -------------------- sp2 = plt.subplot(212, sharex=sp1) g_mean = np.sqrt(LM10[:,3]*LM10[:,4]) #geometric mean plt.errorbar(slam, sigma, yerr=2.35482*errors, fmt="d", mfc="black", ecolor="black", label="MLE Fits") #plt.scatter(slam, sigma, facecolor="black", marker="o", label=None) plt.plot(LM10[:21,0], 2.35482*g_mean[:21], "k-", label=None) plt.plot(LM10[21:,0], 2.35482*g_mean[21:], "k-", label=None) # NEW STUFF aa, bb = 21, 21 plt.plot(wp[:aa,0], 2.35482*np.sqrt(wp[:aa,3]*wp[:aa,4]), "b--", label=None) plt.plot(wp[bb:,0], 2.35482*np.sqrt(wp[bb:,3]*wp[bb:,4]), "b--", label=None) plt.plot(ws[:aa,0], 2.35482*np.sqrt(ws[:aa,3]*ws[:aa,4]), "k-.", label=None) plt.plot(ws[bb:,0], 2.35482*np.sqrt(ws[bb:,3]*ws[bb:,4]), "k-.", label=None) plt.plot(wo[:aa,0], 2.35482*np.sqrt(wo[:aa,3]*wo[:aa,4]), "r:", label=None) plt.plot(wo[bb+3:,0], 2.35482*np.sqrt(wo[bb+3:,3]*wo[bb+3:,4]), "r:", label=None) #plt.scatter(LM10[:,0], 2.35482*g_mean, facecolor='black', marker='+', label="L&M10 Nbody") # legend leg2 = sp2.legend(loc='lower right', numpoints=1) for t in leg2.get_texts(): t.set_fontsize(8) plt.xlabel(r"$\Lambda_{\odot}$") plt.ylabel(r"FWHM (kpc)") plt.ylim(0.0, 20.0) plt.xlim(320.0, 70.0) # 70, 320 #plt.xticks(sc.arange(80.0, 320.0, 20.0)) plt.show()