Exemple #1
0
 def __init__(self, data_x, data_y, data_sig):
     """ Default Parameters """
     # important values
     self.x = data_x
     self.y = data_y
     # "p" uses Poisson Errors, A stringified float uses that value for sigma
     if data_sig == "p": self.sig = func.poisson_errors(self.y)
     elif type(data_sig) == type(""):
         self.sig = eval(data_sig) * sc.ones(len(self.x))
     else:
         self.sig = data_sig
     self.name = "fit"
     self.function = func.gaussian_function
     """ self.evaluator = R_squared """
     self.params = [1.0, 1.0, 1.0]  # starting params - to be best params
     self.step = [0.1, 0.1, 0.1]  #fitting step sizes
     self.range = [None, None,
                   None]  # (<#>, <min>, <max>, <step_size>), for surface
     self.min = [None, None, None]  # parameter min bounds
     self.max = [None, None, None]  # parameter max bounds
     self.errors = [None, None, None]  # Fit errors, to be determined
     self.RR = R_squared(self, self.params)  # best r-squared value
     # secondary values
     self.plot_type = "scatter"  #or "bar"
     self.plot_axes = ["x", "y", 0]
     self.param_names = [
         "parameter1", "parameter2", "parameter3", "parameter4"
     ]
Exemple #2
0
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()    
Exemple #3
0
 def __init__(self, data_x, data_y, data_sig):
     """ Default Parameters """
     # important values
     self.x = data_x
     self.y = data_y
     # "p" uses Poisson Errors, A stringified float uses that value for sigma
     if data_sig=="p":  self.sig = func.poisson_errors(self.y)
     elif type(data_sig)==type(""):  self.sig = eval(data_sig)*sc.ones(len(self.x))
     else:  self.sig = data_sig
     self.name = "fit"
     self.function = func.gaussian_function
     """ self.evaluator = R_squared """
     self.params = [1.0, 1.0, 1.0] # starting params - to be best params
     self.step = [0.1, 0.1, 0.1]  #fitting step sizes
     self.range = [None, None, None]  # (<#>, <min>, <max>, <step_size>), for surface
     self.min = [None, None, None]  # parameter min bounds
     self.max = [None, None, None]  # parameter max bounds
     self.errors = [None, None, None]  # Fit errors, to be determined
     self.RR = R_squared(self, self.params)  # best r-squared value
     # secondary values
     self.plot_type = "scatter"  #or "bar"
     self.plot_axes = ["x", "y", 0]
     self.param_names = ["parameter1", "parameter2", "parameter3", "parameter4"]
#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,
                                            steps,
                                            x_col,
                                            y_col,
                                            sig_col,
                                            name=identifier,
Exemple #5
0
    data_out = []
    for i in range(len(data[:,0])):
        if mask[i]==0:  data_out.append(data[i,:])
    return np.array(data_out)

for f in files:
    # load in data
    #name = f[-18:-13]  #spec_cut
    #name = f[-9:-4]  #all_data
    name = f.split("/")[-1][0:5].strip("_")
    if float(name) < 200.0:  continue
    data = clean_data(np.loadtxt(f) ) 
    if len(data)<2:  continue
    # Set up data
    x, y = data[:,0], data[:,1]
    e = func.poisson_errors(y)
    # make a line, using the average of 10 bins on each end as the anchor points
    x0, y0, x1, y1 = [], [], [], []
    i = 0
    minbin = 100.0
    while len(x0) < 5:
        if y[i] > minbin:  x0.append(x[i]);  y0.append(y[i])
        i += 1
    if eval(name) > 291:  i = -20 #-20
    elif eval(name) > 274:  i = -40
    elif eval(name) < 201:  i = -40
    else:  i = -1
    while len(x1) < 5:
        if y[i] > minbin:  x1.append(x[i]);  y1.append(y[i])
        i -= 1
    xi, yi = np.mean(x0), np.mean(y0)
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]
    print "# - Starting from:", fitter.params, fitter.RR
    print "# - With steps:", fitter.step
    # Fit
Exemple #7
0
elif suffix == '.csv':
    data = f.read_data(filename, ',')
else:
    print "WHAT?  I don't know how to read", suffix
#data = make_line_errors(10.0, 20.0, yerr=15.0)
#data = make_gauss_errors(2.0, 2.0, yerr=0.0)

#Set data
#columns in data file for respective values
x_col, y_col, sig_col = data[:,
                             1], data[:,
                                      0], data[:,
                                               1]  #sc.ones(len(data[:,0]),float) #
#y_col, edges = sc.histogram(data[:,15], bins=20, range=(-200.0, 200.0))
#x_col = (edges + 10.0)[:-1] #sc.arange( (low+(size/2.0)), 200.0, size)
sig_col = func.poisson_errors(y_col)
""" Initializations - choose correct number of parameters"""
""" 6 params """
#start_params = sc.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0])  #A function that gives a good start is nice here
#steps = sc.array([0.01,0.01,0.01,0.01,0.01,0.01])  #1/10 of expected parameter order is usually good
""" 4 params """
start_params = sc.array([4.456, 0.814, 0.226, 8.43
                         ])  #A function that gives a good start is nice here
steps = sc.array([0.001, 0.001, 0.001,
                  0.001])  #1/10 of expected parameter order is usually good
""" 3 params """
#start_params = sc.array([5.0, 5.0, 1.5])  #A function that gives a good start is nice here
#steps = sc.array([0.001,0.001,0.001])  #1/10 of expected parameter order is usually good
""" 2 params """
#start_params = sc.array([1.0, 0.001])  #A function that gives a good start is nice here
#steps = sc.array([0.01,0.0001])  #1/10 of expected parameter order is usually good
Exemple #8
0
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]
    print "# - Starting from:", fitter.params, fitter.RR
    print "# - With steps:", fitter.step
    # Fit
Exemple #9
0
def fit_hists(x_raw,
              y_raw,
              name,
              outfile=None,
              outpath="",
              fit_type='double',
              cuts=None,
              background="common",
              binsize=0.5,
              lam_offset=0.0):
    run = eval(name.split("_")[-1])
    # clean data;  don't fit bins with certain criteria
    if cuts != None:
        mask = sc.ones(len(y_raw), dtype=bool)
        for i in range(cuts.shape[0]):
            if cuts[i, 0] + lam_offset == run:  #for offset Lambda wedges
                if binsize == 0.5:
                    for j in range(cuts[i, 1], cuts[i, 2]):
                        mask[(j - 1)] = cuts[i, 3]
                if binsize == 1.0:
                    for j in range(cuts[i, 1] / 2, cuts[i, 2] / 2):
                        mask[(j - 1)] = cuts[i, 3]
    else:
        mask = sc.zeros(len(y_raw), dtype=bool)
        for i in range(len(y_raw)):
            if y_raw[i] <= 0.0: mask[i] = 1  #flag zeros
        #if y_raw[i] > 1000.0:  mask[i] = 1  #flag globular clusters
    # make new array that contains only mask==0
    x, y = [], []
    for i in range(len(y_raw)):
        if mask[i] == 0:
            x.append(x_raw[i])
            y.append(y_raw[i])
    # Set up data
    x, y = np.array(x), np.array(y)
    e = func.poisson_errors(y)
    if background == "common":
        # Make a flat background line set to most common bin height
        hline, hedges = np.histogram(y, bins=40, range=(0.0, 1000.0))
        best = 25.0 * np.argmax(hline) - 12.5
        aa, bb = 0.0, best
    elif background == "least":
        ids = np.argsort(y)[:10]
        aa, bb = 0.0, np.mean(y[ids])
    elif background == "fitline":
        # make a line, using the average of 10 bins on each end as the anchor points
        x0, y0, x1, y1 = [], [], [], []
        minbin = 1.0
        if run < 120: i = 10
        else: i = 1
        while len(x0) < 10:
            if y[i] > minbin:
                x0.append(x[i])
                y0.append(y[i])
            i += 1
        if run < 120: i = (len(y) / 2.0) - 5
        elif run > 254: i = 65
        else: i = -1
        while len(x1) < 10:
            if y[i] > minbin:
                x1.append(x[i])
                y1.append(y[i])
            i -= 1
        xi, yi = np.mean(x0), np.mean(y0)
        xf, yf = np.mean(x1), np.mean(y1)
        #xi, yi = np.mean(x[2:6]), np.mean(y[2:6])
        #xf, yf = np.mean(x[-7:-3]), np.mean(y[-7:-3])
        aa = (yf - yi) / (xf - xi)
        bb = yf - (aa * xf)
    else:
        # null line
        aa, bb = 0.0, 0.0
    #  fit it
    fitter = fit.ToFit(x, y, e)
    if fit_type == "double":
        fitter.function = func.double_gauss_line
        fitter.update_params([6.0, 0.0, 5.0, 6.0, -6.0, 5.0, aa, bb])
        fitter.step = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
        fitter.param_names = [
            "amp", "mu", "sigma", "amp", "mu", "sigma", "slope", "intercept"
        ]
    elif fit_type == "quad":
        fitter.function = func.quad_fat_gauss_line
        fitter.update_params(
            [6.0, 5.0, 1.0, 6.0, -10.0, 1.0, 5.0, 10.0, 5.0, 10.0, aa, bb])
        fitter.step = [
            1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0
        ]
        fitter.param_names = [
            "amp", "mu", "sigma", "amp", "mu", "sigma", "amp", "sigma", "amp",
            "sigma", "slope", "intercept"
        ]
    elif fit_type == "triple":
        if run < 120: tf, tm = 200.0, -50.0
        if run > 120: tf, tm = 150.0, 40.0
        fitter.function = func.triple_gauss_floor
        fitter.update_params(
            [6.0, 5.0, 1.0, 6.0, -10.0, 1.0, 2.0, tm, 40.0, tf])
        fitter.step = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 5.0, 10.0]
        fitter.param_names = [
            "amp", "mu", "sigma", "amp", "mu", "sigma", "amp", "mu", "sigma",
            "floor"
        ]
    print "\n {0}:".format(name)
    print "# - Starting from:", fitter.params, fitter.RR
    print "# - With steps:", fitter.step
    path1 = fit.gradient_descent(fitter, its=10000, line_search=0)
    path2 = fit.MCMC(fitter)
    #errors = fit.get_Hessian_errors(fitter)
    # cut from ToFit
    new_params = fitter.params
    xx = np.arange(-70.0, 40.0, 0.1)
    plt.figure(1)
    plt.bar(x_raw, y_raw, binsize, align='center', color='white', zorder=1)
    plt.bar(fitter.x,
            fitter.y,
            binsize,
            align='center',
            color='grey',
            zorder=2)
    plt.plot(xx, fitter.function(xx, new_params), 'k-')
    print new_params[:4]
    plt.plot(xx, func.gaussian_function(xx, new_params[:3]), 'k--')
    plt.plot(xx, func.gaussian_function(xx, new_params[3:6]), 'k--')
    if fit_type == "triple":
        plt.plot(
            xx,
            func.gaussian_function(
                xx, [new_params[6], new_params[7], new_params[8]]), 'k--')
        plt.plot(xx, new_params[9] * sc.ones(len(xx)), "k--")
    if fit_type == "quad":
        plt.plot(
            xx,
            func.gaussian_function(
                xx, [new_params[6], new_params[1], new_params[7]]), 'k--')
        plt.plot(
            xx,
            func.gaussian_function(
                xx, [new_params[8], new_params[4], new_params[9]]), 'k--')
    plt.xlabel("B")
    plt.ylabel("Counts")
    plt.xlim(-70.0, 40.0)
    plt.ylim(0.0, 700.0)
    #plt.text(-65.0, 1100.0, name, fontsize=8 )
    out_name = outpath + name + "_plot" + ".png"
    #plt.show()
    plt.savefig(out_name)
    plt.close('all')
    return np.insert(np.concatenate((fitter.params, fitter.error)), -1,
                     fitter.RR)
Exemple #10
0
def fit_hists(x_raw, y_raw, name, outfile=None, outpath="", fit_type='double',
        cuts=None, background="common", binsize=0.5, lam_offset=0.0):
    run = eval(name.split("_")[-1])
    # clean data;  don't fit bins with certain criteria
    if cuts != None:
        mask = sc.ones(len(y_raw), dtype=bool)
        for i in range(cuts.shape[0]):
            if cuts[i,0]+lam_offset == run:  #for offset Lambda wedges
                if binsize==0.5:
                    for j in range(cuts[i,1], cuts[i,2]):
                        mask[(j-1)] = cuts[i,3]
                if binsize==1.0:
                    for j in range(cuts[i,1]/2, cuts[i,2]/2):
                        mask[(j-1)] = cuts[i,3]
    else:
        mask = sc.zeros(len(y_raw), dtype=bool)
        for i in range(len(y_raw)):
            if y_raw[i] <= 0.0:  mask[i] = 1  #flag zeros
        #if y_raw[i] > 1000.0:  mask[i] = 1  #flag globular clusters
    # make new array that contains only mask==0
    x, y = [], []
    for i in range(len(y_raw)):
        if mask[i]==0:  x.append(x_raw[i]); y.append(y_raw[i])
    # Set up data
    x, y = np.array(x), np.array(y)
    e = func.poisson_errors(y)
    if background == "common":
        # Make a flat background line set to most common bin height
        hline, hedges = np.histogram(y, bins=40, range=(0.0, 1000.0))
        best = 25.0*np.argmax(hline) - 12.5
        aa, bb = 0.0, best
    elif background == "least":
        ids = np.argsort(y)[:10]
        aa, bb = 0.0, np.mean(y[ids])
    elif background == "fitline":
        # make a line, using the average of 10 bins on each end as the anchor points
        x0, y0, x1, y1 = [], [], [], []
        minbin = 1.0
        if run < 120:  i = 10
        else:  i = 1
        while len(x0) < 10:
            if y[i] > minbin:  x0.append(x[i]);  y0.append(y[i])
            i += 1
        if run < 120:  i = (len(y)/2.0) - 5
        elif run > 254:  i = 65
        else:  i = -1
        while len(x1) < 10:
            if y[i] > minbin:  x1.append(x[i]);  y1.append(y[i])
            i -= 1
        xi, yi = np.mean(x0), np.mean(y0)
        xf, yf = np.mean(x1), np.mean(y1)
        #xi, yi = np.mean(x[2:6]), np.mean(y[2:6])
        #xf, yf = np.mean(x[-7:-3]), np.mean(y[-7:-3])
        aa = (yf-yi)/(xf-xi)
        bb = yf - (aa*xf)
    else:
        # null line
        aa, bb = 0.0, 0.0
    #  fit it
    fitter = fit.ToFit(x,y,e)
    if fit_type == "double":
        fitter.function=func.double_gauss_line
        fitter.update_params([6.0, 0.0, 5.0, 6.0, -6.0, 5.0, aa, bb])
        fitter.step = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
        fitter.param_names = ["amp", "mu", "sigma", "amp", "mu", "sigma", "slope", "intercept"]
    elif fit_type == "quad":
        fitter.function=func.quad_fat_gauss_line
        fitter.update_params([6.0, 5.0, 1.0, 6.0, -10.0, 1.0, 5.0, 10.0, 5.0, 10.0, aa, bb])
        fitter.step = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0]
        fitter.param_names = ["amp", "mu", "sigma", "amp", "mu", "sigma", "amp","sigma", "amp","sigma","slope","intercept"]
    elif fit_type == "triple":
        if run < 120:  tf, tm = 200.0, -50.0
        if run > 120:  tf, tm = 150.0, 40.0
        fitter.function=func.triple_gauss_floor
        fitter.update_params([6.0, 5.0, 1.0, 6.0, -10.0, 1.0, 2.0, tm, 40.0, tf])
        fitter.step = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 5.0, 10.0]
        fitter.param_names = ["amp", "mu", "sigma", "amp", "mu", "sigma", "amp", "mu", "sigma", "floor"]
    print "\n {0}:".format(name)
    print "# - Starting from:", fitter.params, fitter.RR
    print "# - With steps:", fitter.step
    path1 = fit.gradient_descent(fitter, its=10000, line_search=0)
    path2 = fit.MCMC(fitter)
    #errors = fit.get_Hessian_errors(fitter)
    # cut from ToFit
    new_params=fitter.params
    xx = np.arange(-70.0, 40.0, 0.1)
    plt.figure(1)
    plt.bar(x_raw, y_raw, binsize, align='center', color='white', zorder=1)
    plt.bar(fitter.x, fitter.y, binsize, align='center', color='grey', zorder=2)
    plt.plot(xx, fitter.function(xx, new_params), 'k-')
    print new_params[:4]
    plt.plot(xx, func.gaussian_function(xx, new_params[:3]), 'k--')
    plt.plot(xx, func.gaussian_function(xx, new_params[3:6]), 'k--')
    if fit_type == "triple":
        plt.plot(xx, func.gaussian_function(xx, [new_params[6], new_params[7], new_params[8]]), 'k--')
        plt.plot(xx, new_params[9]*sc.ones(len(xx)), "k--")
    if fit_type == "quad":
        plt.plot(xx, func.gaussian_function(xx, [new_params[6], new_params[1], new_params[7]]), 'k--')
        plt.plot(xx, func.gaussian_function(xx, [new_params[8], new_params[4], new_params[9]]), 'k--')
    plt.xlabel("B")
    plt.ylabel("Counts")
    plt.xlim(-70.0, 40.0)
    plt.ylim(0.0, 700.0)
    #plt.text(-65.0, 1100.0, name, fontsize=8 )
    out_name = outpath+name+"_plot"+".png"
    #plt.show()
    plt.savefig(out_name)
    plt.close('all')
    return np.insert(np.concatenate((fitter.params, fitter.error)), -1, fitter.RR)
Exemple #11
0
turnoff = []
for i in range(len(datafile)):
    if skip[i] == 1:  continue
    data = f.read_data(datafile[i], ',')
    mu = results[i,2] + 5.*(m.log10(DISTANCE[i]*1000) - 1.)
    holder=[]
    for j in range(len(data[:,0])):
        if data[j,2] > (mu+spread):  continue
        if data[j,2] < (mu-spread):  continue
        holder.append(data[j,2]-data[j,3])
    histogram = h.make_hist(holder, 0.01)
    h.plot_histogram(histogram, 0.01, name=('hist_'+str(i)), x_label=r'$(g-r)_0$')
    #h.plot_multiple_hist(histogram[:,0], [histogram[:,1]], 0.01, name=('hist_'+str(i)), x_label=r'$(g-r)_0$')
    #x_col, y_col, sig_col = histogram[:,0], (histogram[:,1]/len(holder)), (func.poisson_errors(histogram[:,1])/len(holder) )
    x_col, y_col, sig_col = histogram[:,0], (histogram[:,1]), (func.poisson_errors(histogram[:,1]))
    #print x_col, y_col, sig_col
    start_params = sc.array([0.2, 0.1, sc.ma.max(y_col)])
    steps = sc.array([0.001, 0.001, 0.01])
    function = func.gaussian_function
    #Fit function
    MCMC_fit, errors, best_fit = mc.do_MCMC(function, start_params, steps, x_col, y_col,
                              sig_col, name=('histfit_'+str(i)), number_steps=10000, save=0)
    best_fit = gd.gradient_descent(function, best_fit, x_col, y_col, sig_col)
    errors = he.get_hessian_errors(function, best_fit, x_col, y_col, sig_col, steps)
    turnoff.append([best_fit[0], best_fit[1], errors[0], errors[1]])
#    if (pdf.plot_function(x_col, y_col, function, best_fit, save_name=('histfitplot_'+str(i)), 
#                      title=['', r'$(g-r)_0$', 'Normalized Counts'], save=1) == 1):
    plt.figure()
    plt.scatter(x_col, y_col)
    func_x = sc.arange( (sc.ma.min(x_col)*0.9), (sc.ma.max(x_col)*1.1), 0.01)
Exemple #12
0
 mu = results[i, 2] + 5. * (m.log10(DISTANCE[i] * 1000) - 1.)
 holder = []
 for j in range(len(data[:, 0])):
     if data[j, 2] > (mu + spread): continue
     if data[j, 2] < (mu - spread): continue
     holder.append(data[j, 2] - data[j, 3])
 histogram = h.make_hist(holder, 0.01)
 h.plot_histogram(histogram,
                  0.01,
                  name=('hist_' + str(i)),
                  x_label=r'$(g-r)_0$')
 #h.plot_multiple_hist(histogram[:,0], [histogram[:,1]], 0.01, name=('hist_'+str(i)), x_label=r'$(g-r)_0$')
 #x_col, y_col, sig_col = histogram[:,0], (histogram[:,1]/len(holder)), (func.poisson_errors(histogram[:,1])/len(holder) )
 x_col, y_col, sig_col = histogram[:,
                                   0], (histogram[:,
                                                  1]), (func.poisson_errors(
                                                      histogram[:, 1]))
 #print x_col, y_col, sig_col
 start_params = sc.array([0.2, 0.1, sc.ma.max(y_col)])
 steps = sc.array([0.001, 0.001, 0.01])
 function = func.gaussian_function
 #Fit function
 MCMC_fit, errors, best_fit = mc.do_MCMC(function,
                                         start_params,
                                         steps,
                                         x_col,
                                         y_col,
                                         sig_col,
                                         name=('histfit_' + str(i)),
                                         number_steps=10000,
                                         save=0)
 best_fit = gd.gradient_descent(function, best_fit, x_col, y_col, sig_col)