Ejemplo n.º 1
0
    def find_peaks():  # implement multiple runs?
        t_peak = []
        ch1_peak = []

        dt = []

        for number in t[argrelmax(yFit)]:
            tempx, tempy = selectdomain(t, ch1, [number - .007, number + .005])

            tempy = gaussian_filter(tempy, 7)

            p = [.14, .0027, tempx[argrelmax(tempy)[0]], -.05]

            # popt, pcov = curve_fit(gaussian, tempx, tempy)
            #
            # tempyFit = gaussian(tempx, *popt)
            # tempyuFit = gaussian(tempx, *p)
            #
            # plt.plot(tempx, tempy)
            # plt.plot(tempx, tempyFit, 'r')
            # plt.plot(tempx, tempyuFit, 'g')

            t_peak.append(tempx[argrelmax(tempy)[0]])
            ch1_peak.append(tempy[argrelmax(tempy)[0]])

            dt.append(p[1] / len(tempy))

        return t_peak, ch1_peak, dt
Ejemplo n.º 2
0
def FWHM_hyperfine(dataset):
    conversions = convert_time_freq()

    t, ch1, ch2 = loadtxt(dataset, unpack=True, skiprows=1, usecols=(0, 1, 3))

    k = conversions["Frequency value"] / conversions["Time value"]
    dk = np.sqrt((conversions["Time Uncertainty"] /
                  conversions["Time value"])**2 +
                 (conversions["Frequency Uncertainty"] /
                  conversions["Frequency value"])**2)
    ti, c1 = selectdomain(t, ch1, [.09, .091])

    c1_filter = gaussian_filter(c1, 5)

    x0 = ti[argrelmin(c1_filter)]

    print x0

    p = [-9e-6, 2.35e-4, x0, 1e-2, 1.18e-1]

    popt, pcov = curve_fit(lorentzian_back, ti, c1, p0=p)

    lw = 1.054e-34 / (6.626e-34 * popt[1] * k)
    dlw = np.sqrt((np.sqrt(pcov[1, 1]) / popt[1])**2 +
                  dk**2) * 1.054e-34 / (6.626e-34 * popt[1] * k)

    print "Linewidth of Hyperfine State: %.2e +- %.2e" % (lw, dlw)

    yFit = lorentzian_back(ti, *popt)
    yuFit = lorentzian_back(ti, *p)

    ch1err = est_error(ch1, 1e-3)
    c1err = est_error(c1, 1e-3)

    hyperfine_text1 = r"$f(t) = \frac{A}{\pi}\frac{\frac{1}{2}\Gamma}{(t - t_0)^2 + (\frac{1}{2}\Gamma)^2} + Bt + C$"

    hyperfine_text2 = r"$f(t) = \frac{%.2e}{\pi}\frac{\frac{1}{2}%.2e}{(t - %.2e)^2  + (\frac{1}{2}%.2e)^2} + %.2et + %.2e$" % (
        popt[0], popt[1], popt[2], popt[1], popt[3], popt[4])

    hyperfine_text3 = "Lifetime of Hyperfine State: $%.2e\,\pm\,%.2e$ s" % (
        lw, dlw)

    plt.figure(figsize=(10, 10))
    plt.errorbar(ti, c1, c1err, fmt='o')
    plt.plot(ti, yFit, 'r', lw=2, alpha=.8, label="Lorentzian Fit")
    plt.text(.0899, .06, "%s\n%s" % (hyperfine_text1, hyperfine_text3))
    plt.xlabel("Time (s)")
    plt.ylabel("Absorbtion $W/(m^2)$")
    plt.title("Determining the lifetime of a Hyperfine Feature peak")
    plt.legend()
    plt.savefig("plots/rb87_hyperfine.pdf")
    plt.show()
Ejemplo n.º 3
0
    def calibrate():
        data = np.genfromtxt("data/cross_section/na_compton.tsv", skip_header=26)
        xdata, ydata = selectdomain(data[:,0], data[:,1], [100, 2048])

        plt.figure(figsize=(10, 10))
        plt.plot(xdata, ydata)
        plt.annotate("Na-22 1275 keV Compton Edge", (500, 50), (750, 200), arrowprops = dict(width=2, headwidth=4, facecolor="red"))
        plt.xlabel("Channel")
        plt.ylabel("Counts")
        plt.title("One Point Calibration")
        plt.savefig("plots/calibration.pdf")

        return 500
Ejemplo n.º 4
0
    def sim_data(n_runs):
        countrates = []
        for i in range(0, n_runs):
            start = np.random.randn(1)*50 + 1500

            xdata, ydata = selectdomain(data[:,0], data[:,1], [start, 2048])

            with open("data/cross_section/%s" % dataset) as f:
                f.seek(300)
                try:
                    livetime = float(f.read(6))
                except Exception:
                    f.seek(404)
                    livetime = float(f.read(6))
                f.close()
            #print livetime

            countrates.append(np.trapz(ydata, xdata)/livetime)

        return countrates
Ejemplo n.º 5
0
def plot_broadened_data(
    dataset
):  #need to update this code to be frequency on x axis, also need to double-check converstion, might be off by about 3 orders of magnitude

    conversions = convert_time_freq()

    t, ch1, ch2 = loadtxt(dataset, unpack=True, skiprows=1, usecols=(0, 1, 3))

    k = conversions["Frequency Uncertainty"] / conversions["Time value"]

    ti, c1 = selectdomain(t, ch1, [.0825, .105])

    c1_filter = gaussian_filter(c1, 25)

    x0 = ti[argrelmax(c1_filter)]

    #print x0

    p = [4e-3, 1.5e-2, x0, -.07]

    popt, pcov = curve_fit(lorentzian, ti, c1, p0=p)

    yFit = lorentzian(ti, *popt)
    yuFit = lorentzian(ti, *p)

    ch1err = est_error(ch1, 1e-3)
    c1err = est_error(c1, 1e-3)

    print 2 * (popt[2] * k / 3e8) * np.sqrt(
        (2 * 1.38e-23 * 300 * np.log(2)) / 1.419e-25)

    #print "Linewidth: %.2e Hz" % (k*popt[1])
    #print k

    f2 = "87 Rb F = 2"
    f3 = "85 Rb F = 3"
    f285 = "85 Rb F = 2"
    f1 = "87 Rb F = 1"
Ejemplo n.º 6
0
def convert_time_freq():
    time, chan1 = np.genfromtxt("data/interferometer_cal.tsv",
                                unpack=True,
                                skip_header=1,
                                usecols=(0, 1))

    time = time

    t, ch1 = selectdomain(time, chan1, [.06, .16])

    ##### Fitting consine #####

    # [A, B, omega1, omega2, delta1, delta2, C]
    p = [1.8e-2, 6.68e-2, 7.264, 4.419e2, 1.773, -4.52, 0]

    popt, pcov = curve_fit(multi_cosine, t, ch1, p0=p)

    yFit = multi_cosine(t, *popt)
    yuFit = multi_cosine(t, *p)

    # plt.plot(t, ch1)
    # plt.plot(t, yFit)

    ##### Getting exact peak locations #####
    def find_peaks():  # implement multiple runs?
        t_peak = []
        ch1_peak = []

        dt = []

        for number in t[argrelmax(yFit)]:
            tempx, tempy = selectdomain(t, ch1, [number - .007, number + .005])

            tempy = gaussian_filter(tempy, 7)

            p = [.14, .0027, tempx[argrelmax(tempy)[0]], -.05]

            # popt, pcov = curve_fit(gaussian, tempx, tempy)
            #
            # tempyFit = gaussian(tempx, *popt)
            # tempyuFit = gaussian(tempx, *p)
            #
            # plt.plot(tempx, tempy)
            # plt.plot(tempx, tempyFit, 'r')
            # plt.plot(tempx, tempyuFit, 'g')

            t_peak.append(tempx[argrelmax(tempy)[0]])
            ch1_peak.append(tempy[argrelmax(tempy)[0]])

            dt.append(p[1] / len(tempy))

        return t_peak, ch1_peak, dt

    t_peak, ch1_peak, dt = find_peaks()

    t_peak = np.ravel(t_peak)

    dt = np.absolute(dt)

    ##### Now we find the conversion from time to frequency #####

    def find_conv(nruns):
        parms_A = []
        parms_B = []
        deltat = []

        for j in range(0, nruns):
            t_pk = np.random.randn(len(t_peak)) * dt + t_peak

            l = len(t_pk)

            delt = []
            for i in range(0, l - 1):
                delt.append(t_pk[i + 1] - t_pk[i])
            delt = np.ravel(delt)

            ld = len(delt)

            deltat.append(delt)

        return deltat

    delt = find_conv(5000)
    dt = np.ravel(delt)

    df = 3e8 / (2 * (29.5e-2 - 10.5e-2))

    deltf = np.sqrt((.5e-2 / 29.5e-2)**2 + (.5e-2 / 10.5e-2)**2) * df

    f = np.ones_like(dt) * df

    # plt.figure(figsize = (10, 10))
    # plt.errorbar(deltat, f, fmt='o', label = "Data")
    # plt.xlabel("Change in Time (d(s))")
    # plt.ylabel("Change in Frequency (d(Hz))")
    # plt.title("Linear Fit to Find Conversion from Time to Frequency")
    # plt.savefig("plots/linear_conversion.png")
    # plt.show()

    # print np.average(deltat), np.std(deltat), df, deltf

    # interferometer_text = "Fit Form:\n \
    #                       $A\cos(\omega_1 t + \delta_1) + B\cos(\omega_2 t + \delta_2)$"
    #
    #
    # plt.figure(figsize = (10, 10))
    # plt.plot(t, ch1, 'o', label = "Raw Data")
    # plt.plot(t_peak, ch1_peak, 'ro', ms=15, label = "Peaks")
    # plt.plot(t, yFit, 'r', label = "Fitted Curve")
    #
    # plt.text(.08, .11, interferometer_text)
    # #plt.plot(t, yuFit, 'g', label = "Guesses")
    # plt.xlabel("Time (s)")
    # plt.ylabel("Absorbtion $W/(m^2)$")
    # plt.title("Finding Conversion Factors")
    # plt.legend()
    # plt.savefig("plots/conversion.pdf")
    # plt.show()

    return {
        "Time value": np.average(dt),
        "Time Uncertainty": np.std(dt),
        "Frequency value": df,
        "Frequency Uncertainty": deltf
    }
Ejemplo n.º 7
0
def plot_hyperfine(dataset):
    conversions = convert_time_freq()

    t, ch1, ch2 = loadtxt(dataset, unpack=True, skiprows=1, usecols=(0, 1, 3))

    k = conversions["Frequency value"] / conversions["Time value"]

    dk = np.sqrt((conversions["Time Uncertainty"] /
                  conversions["Time value"])**2 +
                 (conversions["Frequency Uncertainty"] /
                  conversions["Frequency value"])**2)

    #print k, dk, conversions["Frequency value"], conversions["Frequency Uncertainty"]

    ti, c1 = selectdomain(t, ch1, [.0825, .105])

    x = [.08625, .0879, .0893, .0906, .0922, .0950]

    ts = []
    cs = []

    for i in range(0, len(x)):
        n = x[i]

        temp_ti, temp_c1 = selectdomain(ti, c1, [n - .0004, n + .0004])

        c1_filter = gaussian_filter(temp_c1, 4)

        c1_filter_minus_lin = c1_filter - (
            (c1_filter[-1] - c1_filter[0]) /
            (temp_ti[-1] - temp_ti[0]) * temp_ti)

        # plt.plot(temp_ti, c1_filter)
        # plt.plot(temp_ti[argrelmin(c1_filter_minus_lin)], temp_c1[argrelmin(c1_filter_minus_lin)], 'o')

        ts.append(temp_ti[argrelmin(c1_filter_minus_lin)])
        cs.append(temp_c1[argrelmin(c1_filter_minus_lin)])

    diff = []
    ddiff = []
    for i in range(0, len(ts) - 1):
        temp = (ts[i + 1] - ts[i]) * k * 1e-6
        diff.append(temp)
        ddiff.append((.0002 * k * 1e-6) / temp)

    dk = np.sqrt(dk**2 + np.average(ddiff)**2)

    diffs = np.array([
        "%.18e" % diff[0],
        "%.18e" % (diff[1] + diff[2]),
        "%.18e" % (diff[-1] + diff[-2])
    ])
    ddiffs = np.array([
        "%.18e" % (dk * diff[0]),
        "%.18e" % (dk * (diff[1] + diff[2])),
        "%.18e" % (dk * (diff[-1] + diff[-2]))
    ])

    #print diffs[0]
    #print diffs[1]
    #print diffs[2]

    ch1err = est_error(ch1, 1e-3)
    c1err = est_error(c1, 1e-3)

    headers = ["Differences in MHz", "Uncertainties"]

    to_file = np.transpose(np.vstack(([diffs], [ddiffs])))
    #print np.shape(to_file)

    np.savetxt("hyperfine_splitting.txt", to_file, fmt="%s\t%s")
Ejemplo n.º 8
0
def calibration(plot_cal):
    try:
        data = np.genfromtxt("data/run_3/na_22_cal_2.tsv", skip_header=26, usecols=(0,2))
    except Exception:
        data = np.genfromtxt("data/run_3/na_22_cal_2.tsv", skip_header=26)
    data_err = np.sqrt(data[:,1])

    peak_1_x, peak_1_y = selectdomain(data[:,0], data[:,1], [120, 180])

    p1 = [1e6, 50, 170, -10, 200]

    popt1, pcov1 = curve_fit(gaussian_back, peak_1_x, peak_1_y, p0 = p1)

    yFit1 = gaussian_back(peak_1_x, *popt1)
    yuFit1 = gaussian_back(peak_1_x, *p1)

    #print popt1[2]

    peak_2_x, peak_2_y = selectdomain(data[:,0], data[:,1], [330, 430])

    p2 = [1e6, 100, 350, 0]

    popt2, pcov2 = curve_fit(gaussian, peak_2_x, peak_2_y, p0 = p2)

    yFit2 = gaussian(peak_2_x, *popt2)
    yuFit2 = gaussian(peak_2_x, *p2)

    #print popt2[2]

    data_cs = np.genfromtxt("data/run_3/cs_137_cal_2.tsv", skip_header=26, usecols=(0,2))
    cs_err = np.sqrt(data_cs[:,1])

    peak_3_x, peak_3_y = selectdomain(data_cs[:,0], data_cs[:,1], [160, 230])

    p3 = [1e3, 50, 200, -10, 200]

    popt3, pcov3 = curve_fit(gaussian_back, peak_3_x, peak_3_y, p0 = p3)

    yFit3 = gaussian_back(peak_3_x, *popt3)
    yuFit3 = gaussian_back(peak_3_x, *p3)

    #print popt3[2]

    if plot_cal:
        plt.figure(figsize=(10,10))

        plt.annotate("Na-22 511 keV", (popt1[2], 1.7e4), (popt1[2]+50, 1.7e4), arrowprops = dict(width=2, headwidth=4, facecolor="red"))
        plt.annotate("Cs-137 662 keV", (popt3[2], .98e4),  (popt3[2], 1.3e4), arrowprops = dict(width=2, headwidth=4, facecolor="red"))
        plt.annotate("Na-22 1275 keV", (popt2[2], 3e3), (popt2[2], 4e3), arrowprops = dict(width=2, headwidth=4, facecolor="red"))

        plt.errorbar(data[:,0], data[:,1], data_err)
        # plt.plot(peak_1_x, yuFit1)
        plt.plot(peak_1_x, yFit1, alpha=.8, lw=3, label="Center: %.0f $\pm$ %.2f channel" % (popt1[2], np.sqrt(pcov1[2,2])))
        # plt.plot(peak_2_x, yuFit2)
        plt.plot(peak_2_x, yFit2, alpha=.8, lw=3, label="Center: %.0f $\pm$ %.2f channel" % (popt2[2], np.sqrt(pcov2[2,2])))
        #plt.figure(figsize=(10, 10))
        plt.errorbar(data_cs[:,0], data_cs[:,1], cs_err)
        # plt.plot(peak_3_x, yuFit3)
        plt.plot(peak_3_x, yFit3, alpha=.8, lw=3, label="Center: %.0f $\pm$ %.2f channel" % (popt3[2], np.sqrt(pcov3[2,2])))
        plt.xlabel("Channel")
        plt.ylabel("Counts")
        plt.title("Energy Calibration Using Known Sources")
        plt.legend()
        plt.savefig("plots/calibration_peaks.pdf")

    cal_line_x = np.array([popt1[2], popt3[2], popt2[2]])
    cal_line_y = np.array([511, 662, 1275])
    x_err = np.array([np.sqrt(pcov1[2,2]), np.sqrt(pcov3[2,2]), np.sqrt(pcov2[2,2])])

    p_lin = [2.0, 150.0]

    lin, lin_pcov = curve_fit(linear, cal_line_x, cal_line_y, p0 = p_lin)

    # print lin

    yFit = linear(cal_line_x, *lin)
    yuFit = linear(cal_line_x, *p_lin)

    if plot_cal:
        plt.figure(figsize=(10, 10))
        plt.errorbar(cal_line_x, cal_line_y, x_err, fmt='o', ms=np.average(x_err), label="Point Uncertainty: %.3f channel" % np.average(x_err))
        plt.plot(cal_line_x, yFit, alpha = .7, lw = np.sqrt(lin_pcov[0,0]), label="Slope Uncertainty: %.3f keV/channel" % np.sqrt(lin_pcov[0,0]))
        plt.xlabel("Channel")
        plt.ylabel("Energy (keV)")
        plt.text(175, 1100, "Ax + B \n %.3fx + %.3f" % (lin[0], lin[1]))
        plt.title("Calibrating Channel to Energy")
        plt.legend(loc=4)
        plt.savefig("plots/channel_energy_cal.pdf")

    return lin
Ejemplo n.º 9
0
def cross_section(dataset, plot = False):

    def calibrate():
        data = np.genfromtxt("data/cross_section/na_compton.tsv", skip_header=26)
        xdata, ydata = selectdomain(data[:,0], data[:,1], [100, 2048])

        plt.figure(figsize=(10, 10))
        plt.plot(xdata, ydata)
        plt.annotate("Na-22 1275 keV Compton Edge", (500, 50), (750, 200), arrowprops = dict(width=2, headwidth=4, facecolor="red"))
        plt.xlabel("Channel")
        plt.ylabel("Counts")
        plt.title("One Point Calibration")
        plt.savefig("plots/calibration.pdf")

        return 500

    # calibrate()
    data = np.genfromtxt("data/cross_section/%s" % dataset, skip_header=26)

    def sim_data(n_runs):
        countrates = []
        for i in range(0, n_runs):
            start = np.random.randn(1)*50 + 1500

            xdata, ydata = selectdomain(data[:,0], data[:,1], [start, 2048])

            with open("data/cross_section/%s" % dataset) as f:
                f.seek(300)
                try:
                    livetime = float(f.read(6))
                except Exception:
                    f.seek(404)
                    livetime = float(f.read(6))
                f.close()
            #print livetime

            countrates.append(np.trapz(ydata, xdata)/livetime)

        return countrates


    countrates = sim_data(1500)

    countrate = np.average(countrates)
    dc = np.std(countrates)

    with open("data/cross_section/countrates.tsv", 'a+') as f:
        f.write(str(countrate))
        f.write("\t")
        f.write(dataset)
        f.write("\t")
        f.write(str(dc))
        f.write("\n")
        f.close()

    #print np.trapz(ydata, xdata)/livetime

    if plot:
        xdata, ydata = selectdomain(data[:,0], data[:,1], [1500, 2048])

        plt.figure(figsize=(10, 10))
        plt.semilogy(data[:,0], data[:,1])
        plt.fill_between(xdata, np.min(ydata), ydata, alpha = 0.5, label="Region of Interest: \n 3 x 1275 keV Compton Edge - End = channel 1500-2048")
        plt.xlabel("Channel")
        plt.ylabel("Counts (log(counts))")
        plt.title("Showing Region of Interest - 3.75 cm Al")
        plt.legend(loc=0)
Ejemplo n.º 10
0
def spectrum(dataset, plot_full = False):
    conversion = calibration(False)

    try:
        data = np.genfromtxt(dataset, skip_header=26, usecols=(0,2))
    except ValueError:
        data = np.genfromtxt(dataset, skip_header=26, usecols=(0,1))

    data_x = linear(data[:,0], *conversion)

    domain = [2000, 2450]

    peak_x, peak_y = selectdomain(data_x, data[:,1], domain)

    back_x, back_y = selectdomain(data_x, data[:,1], [800, 3500], domain)
    back_x_full, back_y_full = selectdomain(data_x, data[:,1], [800, 3500])

    p_back = np.array([1e4, -1e-3, 6e2])

    back_popt, back_pcov = curve_fit(exponential, back_x, back_y, p0 = p_back, maxfev=int(1e4))

    back_yFit = exponential(back_x_full, *back_popt)
    back_yuFit = exponential(back_x_full, *p_back)

    to_subtract_x, to_subtract_y = selectdomain(back_x_full, back_yFit, domain)

    if plot_full:
        plt.figure(figsize=(10, 10))
        plt.errorbar(data_x, data[:,1], np.sqrt(data[:,1]), fmt='o', ms=1)
        plt.errorbar(peak_x, peak_y, np.sqrt(peak_y), fmt='o', ms=1, label = "Region of Interest")
        plt.plot(back_x_full, back_yFit, label = "Background Fit")
        plt.ylabel("Counts")
        plt.xlabel("Energy (keV)")
        plt.title("Isolating the Peak")
        plt.legend()
        plt.savefig("plots/peak_isolation_%s.pdf" % dataset.split("/")[2].split(".")[0])

    flat_peak = peak_y - to_subtract_y

    peak_p = [450, 18, 2200, 11]

    peak_popt, peak_pcov = curve_fit(gaussian, peak_x, flat_peak, p0 = peak_p)
    peak_yFit = gaussian(peak_x, *peak_popt)

    # print peak_popt

    with open(dataset) as f:
        f.seek(298)
        try:
            livetime = float(f.read(6))
        except Exception:
            f.seek(404)
            livetime = float(f.read(6))
        f.close()
    # print livetime

    plt.figure(figsize=(10, 10))
    plt.errorbar(peak_x, flat_peak, np.sqrt(flat_peak), fmt='o')
    plt.plot(peak_x, peak_yFit, label = "Gaussian Fit\nCenter: %.0f $\pm$ %.0f keV\nCountrate: %.2f $\pm$ %.2f counts/s" % (peak_popt[2], np.absolute(peak_popt[1]/np.sqrt(len(peak_x))), peak_popt[0]/livetime, np.sqrt(peak_pcov[0,0])/livetime))
    plt.ylabel("Counts (after subtracting background)")
    plt.xlabel("Energy (keV)")
    plt.title("Finding the Peak Center")
    plt.legend()
    plt.savefig("plots/peak_center_%s.pdf" % dataset.split("/")[2].split(".")[0])