コード例 #1
0
ファイル: s_t_fit.py プロジェクト: QuantumDancer/FP2
def main():
    data = Z0Data.fromROOTFile('../data/daten/daten_1.root', 'h33')
    energiedatas = data.splitEnergies()
    xmin, xmax = -0.9, 0.9
    binsizes = {88.48021:80, 89.47158:80, 90.22720:80, 91.23223:50, 91.97109:25, 92.97091:59, 93.71841:80}
    integrals = []
    eds = list(energiedatas.items())  # energy datas sorted after energy
    eds.sort(key=lambda x: x[0])
    table = []
    for energie, data in eds:
        (s, ss), (t, st) = stFit(data, energie, xmin, xmax, binsizes[energie])
        # s intergral:
        Is = s * (xmax - xmin + (xmax ** 3 - xmin ** 3) / 3)
        sIs = Is * ss / s
        # t integral
        It = t * (1 / (1 - xmax) - 1 / (1 - xmin))
        sIt = It * st / t
        r = Is / (Is + It)  # s-ratio
        sr = r * sqrt((sIs / Is) ** 2 + (sIs ** 2 + sIt ** 2) / ((Is + It) ** 2))
        integrals.append((energie, Is, sIs, It, sIt, r, sr))
        table.append([energie, r, sr])
    with TxtFile('../calc/s-t-integrals.txt', 'w') as f:
        f.write2DArrayToFile(integrals, ['%.5f'] + ['%.3f'] * 6)
    with TxtFile('../src/tab_st_ratios.tex', 'w') as f:
        f.write2DArrayToLatexTable(table, [r"$\sqrt{s}$ / GeV", r"$c_{\text{st}}$", r"$s_{c_{\text{st}}}$"], 
                                   ["%.2f", "%.2f", "%.2f"], 
                                   r"Korrekturfaktoren $c_{\text{st}}$ der s-t-Kanal Trennung für verschiedene Schwerpunktsenergien.", 
                                   "tab:st:corrs")
コード例 #2
0
def evalEnergyCalibration(peaks, percents):
    maxenergy = 1.95 * 0.87 * 84
    smaxenergy = maxenergy * sqrt((0.05 / 1.95)**2 + (0.01 / 0.87)**2 +
                                  (5 / 84)**2)
    channels = list(list(zip(*peaks))[0])
    schannels = list(list(zip(*peaks))[1])
    energies = list(map(lambda x: x / 100 * maxenergy, percents))
    senergies = list(map(lambda x: x / 100 * smaxenergy, percents))
    print(energies)
    print(senergies)

    with TxtFile('../src/tab_energycalibration.tex', 'w') as f:
        f.write2DArrayToLatexTable(
            list(zip(*[percents, channels, schannels, energies, senergies])),
            ['\% energy', '$c$', '$s_c$', '$E$ / MeV', '$s_E$ / MeV'],
            ['%d', '%.3f', '%.3f', '%.1f', '%.1f'],
            "Channels of fitted peaks and their theoretical energy for the energy calibration.",
            "tab:ecal")

    data = DataErrors.fromLists(channels, energies, schannels, senergies)
    c = TCanvas('c_energycalibration', '', 1280, 720)
    g = data.makeGraph('g_energycalibration', 'channel c', 'energy E / MeV')
    g.Draw('AP')

    fit = Fitter('fit_energycalibration', 'pol1(0)')
    fit.function.SetNpx(1000)
    fit.setParam(0, 'a', 0)
    fit.setParam(1, 'b', 1 / 3)
    fit.fit(g, 0, max(channels) + 5)
    fit.saveData('../fit/energyCalibration.txt')

    l = TLegend(0.15, 0.6, 0.575, 0.85)
    l.SetTextSize(0.03)
    l.AddEntry(g, 'Peaks of flight through spectra / pedestal', 'p')
    l.AddEntry(fit.function, 'fit with E(c) = a + b * c', 'l')
    fit.addParamsToLegend(l, (('%.2f', '%.2f'), ('%.3f', '%.3f')),
                          chisquareformat='%.2f',
                          units=('MeV', 'MeV / channel'),
                          lang='en')
    l.Draw()

    c.Update()
    c.Print('../img/energyCalibration.pdf', 'pdf')

    with TxtFile('../calc/energyCalibration.txt', 'w') as f:
        f.writeline('\t', str(fit.params[0]['value']),
                    str(fit.params[0]['error']))
        f.writeline('\t', str(fit.params[1]['value']),
                    str(fit.params[1]['error']))
        f.writeline('\t', str(fit.getCovMatrixElem(0, 1)))
コード例 #3
0
def main():
    effmatrix = loadCSVToList('../calc/efficencies.txt')
    seffmatrix = loadCSVToList('../calc/efficencies_error.txt')

    t1 = time.time()

    #generate matrices
    ms = []
    for i in range(100000):
        m = generateErrorMatrix(effmatrix, seffmatrix)
        ms.append(inv(m))

    #group values
    sigmas = [[[] for i in range(4)] for j in range(4)]  # empty 4x4 matrix
    for i in range(4):
        for j in range(4):
            entries = []
            for m in ms:
                entries.append(m[i][j])
            sigmas[i][j] = std(entries, ddof=1)

    t2 = time.time()
    print('%.3f' % (t2 - t1))
    print(matrix(sigmas))

    with TxtFile('../calc/invEfficencies_error.txt', 'w') as f:
        f.write2DArrayToFile(sigmas, ['%.7f'] * 4)
コード例 #4
0
ファイル: part2.py プロジェクト: QuantumDancer/FP2
def evalIntervalConst(avgspectrum):
    def avg2vals(val1, val2):
        return avgerrors([val1[0], val2[0]], [val1[1], val2[1]])

    def sub2vals(val1, val2):
        return val1[0] - val2[0], sqrt(val1[1] ** 2 + val2[1] ** 2)
    s = avgspectrum
    sfreq85 = sub2vals(s[3], s[2])  # 85 S delta freq
    s = avgspectrum[:2] + avgspectrum[-2:]
    sfreq87 = avg2vals(sub2vals(s[2], s[0]), sub2vals(s[3], s[1]))  # 87 S delta freq
    pfreq87 = avg2vals(sub2vals(s[3], s[2]), sub2vals(s[1], s[0]))  # 87 P delta freq
    
    freqs = [sfreq85, sfreq87, pfreq87]
    Fs = [2, 1, 1]  # F of HFS
    names = [r"\rb{85}: ${}^2\text{S}_{1/2}$", r"\rb{87}: ${}^2\text{S}_{1/2}$", r"\rb{87}: ${}^2\text{P}_{1/2}$"]
    litvals = ["4.185", "14.13", "1.692"]
    As = []
    for name, litval, (freq, sfreq87), F in zip(*[names, litvals, freqs, Fs]):
        A = freq * h_eVs / (F + 1) * 1e15  # in µeV and GHz in Hz
        sA = sfreq87 * h_eVs / (F + 1) * 1e15
        As.append([name, litval, A, sA])
    with TxtFile('../src/tab_part2_A.tex', 'w') as f:
        f.write2DArrayToLatexTable(As,
                                   ["Isotop / Feinstruktur", r"$A^\text{Lit.}$ / \textmu eV",
                                    r"$A^\text{exp}$ / \textmu eV", r"$s_{A^\text{exp}}$ / \textmu eV"],
                                   ['%s', '%s', '%.2f', '%.2f'],
                                   r"Errechnete HFS-Intervallkonstanten $A$ für das ${}^2\text{S}_{1/2}$ Niveau von \rb{85} " + 
                                   r"und für das ${}^2\text{S}_{1/2}$- und ${}^2\text{P}_{1/2}$ Niveau von \rb{87}.",
                                   "tab:hfs:intervalconsts")
コード例 #5
0
ファイル: data.py プロジェクト: QuantumDancer/FP2
    def saveDataToLaTeX(self,
                        thead,
                        format,
                        caption,
                        label,
                        path,
                        mode,
                        encoding='utf-8'):
        """prints all points formatted into an latex file and saves it.

        Arguments:
        thead    -- list of descriptions for columns, is used as first row
        format   -- list of formatting rules, how to convert numbers into strings
        caption  -- caption of table in latex
        label    -- label of table in latex
        path     -- relative path to file in which the data is saved to
        mode     -- write mode (usually 'w' for overwriting or 'a' for appending)
        encoding -- file encoding (default = 'utf-8')        
        """
        i = '  '  # intendation
        with TxtFile(path, mode, encoding) as f:
            f.writeline('\\begin{table}[H]')
            f.writeline('\\caption{' + caption + '}')
            f.writeline('\\begin{center}')
            f.writeline('\\begin{tabular}{' + '|c' * len(self.points[0]) +
                        '|}')
            f.writeline(i + '\hline')
            f.writeline(i + ' & '.join(thead) + ' \\\\ \hline ')
            for point in self.points:
                f.writeline(i + ' & '.join(format) % (point[0], point[1]) +
                            ' \\\\ \hline')
            f.writeline('\\end{tabular}')
            f.writeline('\\end{center}')
            f.writeline('\\label{' + label + '}')
            f.writeline('\\end{table}')
コード例 #6
0
def evalTotalGamma(gammas):
    gammas.append(avgerrors(list(zip(*gammas))[0], list(zip(*gammas))[1]))
    with TxtFile('../calc/gamma_total.txt', 'w') as f:
        f.write2DArrayToFile(gammas, ['%f'] * 2)
    table = []
    desc = [LATEXE, LATEXM, LATEXT, LATEXQ, "gew. Mittel"]
    for i, (gamma, sgamma) in enumerate(gammas):
        table.append([desc[i], gamma, sgamma])
    with TxtFile('../src/tab_gamma_total.tex', 'w') as f:
        f.write2DArrayToLatexTable(
            table, [
                "Zerfallskanal", r"$\Gamma_\text{Z}$ / GeV",
                r"$s_{\Gamma_\text{Z}}$ / GeV"
            ], ['%s', '%.3f', '%.3f'],
            r"Durch Fits bestimmte totale Zerfallsbreite des \Z-Bosons und gewichtetes Mittel.",
            "tab:gamma:total")
コード例 #7
0
ファイル: eval_I2_absorption.py プロジェクト: Bigben37/FP1
def makeProgTables():
    name = 'prog%dnl.txt'
    for i in range(1, 3 + 1):
        prog = I2Data.fromPath('../data/' + name % i)
        x = prog.getX()
        y = prog.getY()
        prog.correctValues(False)
        yc = prog.getY()
        yce = prog.getEY()
        f = TxtFile('../src/prog%d.tex' % i, 'w')
        f.write2DArrayToLatexTable(zip(x, y, yc, yce),
                                   ['$\\nu\'$', r'$\lambda_{\text{exp}}$ / nm', r'$\lambda_{\text{cor}}$ / nm', r'$s_{\lambda_{\text{cor}}}$ / nm'],
                                   ['%0.f', '%3.2f', '%3.2f', '%.8f'],
                                   'Measured position of transmission minima in $I_2$-spectrum and corrected values of progession %d.' % i,
                                   'tab:prog%d' % i)
        f.close()
コード例 #8
0
def evalMasses(masses):
    masses.append(avgerrors(list(zip(*masses))[0], list(zip(*masses))[1]))
    with TxtFile('../calc/mass.txt', 'w') as f:
        f.write2DArrayToFile(masses, ['%f'] * 2)
    table = []
    desc = [LATEXE, LATEXM, LATEXT, LATEXQ, "gew. Mittel"]
    for i, (mass, smass) in enumerate(masses):
        table.append([desc[i], mass, smass])
    with TxtFile('../src/tab_mass.tex', 'w') as f:
        f.write2DArrayToLatexTable(
            table, [
                "Zerfallskanal", r"$M_\text{Z}$ / GeV",
                r"$s_{M_\text{Z}}$ / GeV"
            ], ['%s', '%.3f', '%.3f'],
            r"Durch Fits bestimmte Masse des \Z-Bosons und gewichtetes Mittel.",
            "tab:mass")
コード例 #9
0
def calibrateNDFilters():
    errorp = 0.01  # percentage error
    offset = 70
    data = loadCSVToList('../data/part5/04.10/filters.txt')
    ref = data[0][2] + offset
    sref = sqrt((data[0][2] * errorp)**2 + (offset * errorp)**2)
    newdata = []
    filters = dict()
    for d in data:
        int = (d[2] + offset) / ref
        if int == 1:
            sint = 0
        else:
            sint = int * sqrt((sqrt((d[2] * errorp)**2 +
                                    (offset * errorp)**2) /
                               (d[2] + offset))**2 + (sref / ref)**2)
        newdata.append(d + [int * 100, sint * 100])
        filters[d[0]] = (int, sint)

    with TxtFile('../src/tab_part5_NDFilters.tex', 'w') as f:
        f.write2DArrayToLatexTable(
            newdata, [
                "Stärke des Filters", r"$I_\text{nominell}$ / \%",
                r"$U_\text{ph}$ / mV", r"$I_\text{mess}$ / \%",
                r"$s_{I_\text{mess}}$ / \%"
            ], ['%.1f', '%.3f', '%d', '%.2f', '%.2f'],
            r'Kalibrierung der Neutraldichtefilter: Nominelle Transmission $I_{\text{nominell}}$, gemessene Spannung an der Photodiode $U_{\text{ph}}$ und daraus berechnete Transmission $I_{\text{mess}}$. ',
            'tab:deh:dnfilter')

    return filters
コード例 #10
0
ファイル: fitter.py プロジェクト: Bigben37/FP1
    def saveData(self, path, mode='w', enc='utf-8'):
        """saves fitting info (chi^2, DoF, chi^2/DoF, paramters with values and errors, covariance and correlation matrix)

        Arguments:
        path -- relative path to file
        mode -- write mode (usually 'w' for overwriting or 'a' for appending)
        enc  -- encoding (default = 'utf-8')
        """
        with TxtFile.fromRelPath(path, mode) as f:
            f.writeline('fitting info')
            f.writeline('============')
            f.writeline(TxtFile.CHISQUARE + ':\t\t' + str(self.getChisquare()))
            f.writeline('DoF:\t' + str(self.getDoF()))
            f.writeline(TxtFile.CHISQUARE + '/DoF:\t' + str(self.getChisquareOverDoF()))
            f.writeline('\t', 'p-value:', *map(str, self.getPValue()))
            f.writeline('')
            f.writeline('parameters')
            f.writeline('==========')
            for i, param in self.params.iteritems():
                f.writeline('\t', str(i), param['name'], str(param['value']), TxtFile.PM, str(param['error']))
            f.writeline('')
            f.writeline('covariance matrix')
            f.writeline('=================')
            f.writelines('\t'.join(str(j) for j in i) + '\n' for i in self._covMatrix)
            f.writeline('')
            f.writeline('correlation matrix')
            f.writeline('==================')
            f.writelines('\t'.join(str(j) for j in i) + '\n' for i in self._corrMatrix)
            f.writeline()
            f.close()
コード例 #11
0
def main():
    # load data
    data = Z0Data.fromROOTFile('../data/daten/daten_1.root', 'h33')
    energiedatas = data.splitEnergies()
    inveffmatrix, sinveffmatrix = loadInvEffMatrix()
    stRatios = loadSTRatios()
    lums = loadLums()
    corrs = loadCorrections()

    plotDataDistributions(data)
    trueVectors = dict()
    sTrueVectors = dict()
    for energie, data in energiedatas.items():
        # print("E_lep: ", energie)
        # energies = []
        #  for event in data.getEvents():
        #     energies.append(event["E_lep"])
        # print("E_lep_data: ", average(energies) * 2)

        MeasVector = makeDataCut(data)
        # print("MeasVector: ")
        # print(MeasVector)

        # print("TrueVector:")
        trueVector = list(dot(inveffmatrix, MeasVector))
        sTrueVector = [
            sqrt(
                sum((inveffmatrix[i][j] * MeasVector[j])**2 *
                    ((sinveffmatrix[i][j] / inveffmatrix[i][j])**2 +
                     (sqrt(MeasVector[j]) / MeasVector[j])**2)
                    for j in range(4))) for i in range(4)
        ]
        old = trueVector[0]
        trueVector[0] = old * stRatios[energie][0]
        sTrueVector[0] = trueVector[0] * sqrt(
            (sTrueVector[0] / old)**2 +
            (stRatios[energie][1] / stRatios[energie][0])**2)
        # print(trueVector)
        # print("")

        trueVectors[energie] = trueVector
        sTrueVectors[energie] = sTrueVector

    NDatas = [[] for i in range(4)]
    names = ['ee', 'mm', 'tt', 'qq']
    for energie in trueVectors.keys():
        for i in range(4):
            NDatas[i].append(
                (energie, trueVectors[energie][i], sTrueVectors[energie][i]))

    crosssections = dict()
    for ctype, NData in zip(*[names, NDatas]):
        sigmas = calcCrossSection(ctype, NData, lums, corrs)
        crosssections[ctype] = sigmas
        with TxtFile('../calc/crosssections_%s.txt' % ctype, 'w') as f:
            for sigma in sigmas:
                f.writeline('\t', *list(map(str, sigma)))
コード例 #12
0
ファイル: evalEnergy.py プロジェクト: QuantumDancer/FP2
def main():
    evalUnderground()
    makeEnergyPlot()
    e, se = makeFermiKuriePlot()
    E = e * 2
    sE = se * 2
    print(E, sE)
    with TxtFile('../calc/energy.txt', 'w') as f:
        f.writeline('\t', *map(lambda x: '%.2f' % x, (e, se)))
        f.writeline('\t', *map(lambda x: '%.2f' % x, (E, sE)))
コード例 #13
0
def makeTable():
    sigmas = loadCSVToList('../calc/invEfficencies_error.txt')
    thead = [r"Schnitt$\backslash$MC-Daten", LATEXE, LATEXM, LATEXT, LATEXQ]
    firstrow = [LATEXE, LATEXM, LATEXT, LATEXQ]
    with TxtFile('../src/tab_effmat_inv_err.tex', 'w') as f:
        f.write2DArrayToLatexTable(
            list(zip(*([firstrow] + list(zip(*sigmas))))), thead,
            ['%s'] + ['%.7f'] * 4,
            'Fehler der inversen Effizienzmatrix, berechnet mit einem toy-experiment.',
            'tab:inveffmat:err')
コード例 #14
0
def evalPartGamma(gammas):
    with TxtFile('../calc/gamma_part.txt', 'w') as f:
        f.write2DArrayToFile(gammas, ['%f'] * 2)
    table = []
    desc = [LATEXE, LATEXM, LATEXT, LATEXQ]
    litvals = [
        r"$83.91 \pm 0.12$", r"$83.99\pm0.18$", r"$84.04\pm0.22$",
        r"$1744.4\pm2.0$"
    ]
    for i, (gamma, sgamma) in enumerate(gammas):
        table.append([desc[i], gamma * 1e3, sgamma * 1e3, litvals[i]])
    with TxtFile('../src/tab_gamma_part.tex', 'w') as f:
        f.write2DArrayToLatexTable(
            table, [
                "Zerfallskanal $i$", r"$\Gamma_i$ / MeV",
                r"$s_{\Gamma_i}$ / MeV", r"$\Gamma_i^{\text{Lit.}}$ / MeV"
            ], ['%s', '%.1f', '%.1f', '%s'],
            r"Durch Fits bestimmte partielle Zerfallsbreiten des \Z-Bosons und Literaturwerte \cite{pdg}.",
            "tab:gamma:part")
コード例 #15
0
def main():
    E, sE = 107.7, 1.42
    t, st = 2.237, 0.052
    tToeV = 1 / hbar_eVs * 1e-6
    nt, snt = tToeV * t, tToeV * st
    A = 192 * pi**3
    G = sqrt(A / (nt * E**5)) * 1e3
    sG = 1 / 2 * sqrt(A * (E**2 * snt**2 + 25 * sE**2 * nt**2) /
                      (E**7 * nt**3)) * 1e3
    print(G, sG)
    with TxtFile('../calc/G.txt', 'w') as f:
        f.writeline('\t', '%.4e' % G, '%.2e' % sG)
コード例 #16
0
def main():
    # luminosity
    lums = loadCSVToList('../data/daten/lum.txt')
    with TxtFile('../src/tab_lums.tex', 'w') as f:
        f.write2DArrayToLatexTable(
            lums, [
                r"$\sqrt{s}$ / GeV", r"$L$ / (1/nb)",
                r"$s_L^\text{stat}$ / (1/nb)", r"$s_L^\text{sys}$ / (1/nb)",
                r"$s_L^\text{tot}$ / (1/nb)"
            ], ["%.2f"] + ["%.0f"] * 4,
            "Zeitlich integrierte Luminosität mit statistischem, systematischem und totalem "
            + "Fehler für verschiedene Schwerpunktsenergien.", "tab:lums")

    # beam correction
    corr = loadCSVToList('../data/daten/corr.txt')
    with TxtFile('../src/tab_beamcorr.tex', 'w') as f:
        f.write2DArrayToLatexTable(
            corr, [
                r"$\sqrt{s}$ / GeV", r"$c_\text{beam, \qq}$ / nb",
                r"$c_\text{beam, \leplep}$ / nb"
            ], ["%.2f", "%.1f", "%.2f"],
            r"Strahlungskorrekturen für hadronische und leptonische Zerfälle bei verschiedenen Schwerpunktsenergien.",
            "tab:beamcorrs")
コード例 #17
0
def main():
    peak100, sigma100 = evalFlythroughSpectrum('energiekalibration_100', 275,
                                               600)
    peak050, sigma050 = evalFlythroughSpectrum('energiekalibration_50', 120,
                                               400)
    peak035, sigma035 = evalFlythroughSpectrum('energiekalibration_35', 75,
                                               240)
    peak000 = evalPedestal()
    evalEnergyCalibration([peak000, peak035, peak050, peak100],
                          [0, 35, 50, 100])
    with TxtFile('../calc/ecal_sigmas.txt', 'w') as f:
        for d in [[peak035, sigma035], [peak050, sigma050],
                  [peak100, sigma100]]:
            f.writeline('\t',
                        *map(str, [item for sublist in d for item in sublist]))
コード例 #18
0
ファイル: part2.py プロジェクト: QuantumDancer/FP2
def makePeakFreqGraph(peaks, name):
    xlist = list(list(zip(*peaks))[0])
    sxlist = list(list(zip(*peaks))[1])
    ylist = list(map(lambda i: i * 9.924, range(len(peaks))))
    sylist = list(map(lambda i: i * 0.03, range(len(peaks))))

    direction = name.split('-')[0]
    tabledata = list(zip(*[list(range(1, len(xlist) + 1)), list(map(lambda x:x * 1000, xlist)), list(map(lambda x:x * 1000, sxlist)),
                           ylist, sylist]))
    with TxtFile('../src/tab_part2_etalonfreqs_%s.tex' % direction, 'w') as f:
        f.write2DArrayToLatexTable(tabledata,
                                   ["i", r"$x_i$ / ms", r"$0.2 \cdot s_i$ / ms", r"$\nu_i$ / GHz", r"$s_{\nu_i}$ / GHz"],
                                   ["%d", "%.3f", "%.3f", "%.2f", "%.2f"],
                                   "Zentren $x_i$ der gefitteten Cauchy-Funktionen mit Fehler aus den " +
                                   "Breiteparametern $s_i$ und Frequenzdifferenzen zum ersten Peak. ",
                                   "tab:etalon:calib:%s" % direction)

    etalonData = DataErrors.fromLists(xlist, ylist, sxlist, sylist)
    etalonData.multiplyX(1000)
    c = TCanvas('c_pf_' + name, '', 1280, 720)
    g = etalonData.makeGraph('g_pf_' + name, 'Zeit t / ms', 'Frequenzabstand #Delta#nu / GHz')
    g.SetMinimum(etalonData.getMinY() - 5)
    g.SetMaximum(etalonData.getMaxY() + 5)
    g.Draw('AP')

    fit = Fitter('fit_pf_' + name, 'pol1(0)')
    fit.setParam(0, 'a')
    fit.setParam(1, 'r')
    xmin, xmax = etalonData.getMinX(), etalonData.getMaxX()
    deltax = (xmax - xmin) / 10
    fit.fit(g, xmin - deltax, xmax + deltax)
    fit.saveData('../fit/part2/%s-etalon_calibration.txt' % name)

    if fit.params[1]['value'] < 0:
        l = TLegend(0.575, 0.6, 0.85, 0.85)
    else:
        l = TLegend(0.15, 0.6, 0.425, 0.85)
    l.SetTextSize(0.03)
    l.AddEntry(g, 'Etalonpeaks', 'p')
    l.AddEntry(fit.function, 'Fit mit #Delta#nu = a + r * t', 'l')
    fit.addParamsToLegend(l, [('%.1f', '%.1f'), ('%.2f', '%.2f')], chisquareformat='%.2f', units=('GHz', 'GHz/ms'))
    l.Draw()

    c.Update()
    if not DEBUG:
        c.Print('../img/part2/%s-etalon_calibration.pdf' % name, 'pdf')

    return (fit.params[1]['value'], fit.params[1]['error'])
コード例 #19
0
def evalTaus(taus, filters):
    data = DataErrors()
    table = []
    for key, (tau, stau) in taus.items():
        invtau = 1 / tau
        sinvtau = stau / (tau**2)
        int, sint = filters[key]
        data.addPoint(int, invtau, sint, sinvtau)
        table.append([int * 100, sint * 100, tau * 1000, stau * 1000])

    table.sort(key=lambda x: x[0], reverse=True)
    # make table
    with TxtFile('../src/tab_part5_taus.tex', 'w') as f:
        f.write2DArrayToLatexTable(
            table, [
                r'$I_\text{mess}$ / \%', r'$s_{I_\text{mess}}$ / \%',
                r'$\tau$ / ms', r'$s_\tau$ / ms'
            ], ['%.2f', '%.2f', '%.3f', '%.3f'],
            r'Orientierungszeiten $\tau$ des Rubidiumensembles bei verschiedenen Pumpintensitäten $I_{\text{mess}}$.',
            'tab:deh:fitres')

    # make fit
    c = TCanvas('c_taus', '', 1280, 720)
    g = data.makeGraph('g_taus', r'relative Intensitaet I_{mess}',
                       'inverse Orientierungszeit #tau^{ -1} / s^{-1}')
    g.Draw('APX')

    fit = Fitter('fit_taus', '[0]*x + 1/[1]')
    fit.setParam(0, '#alpha', 1)
    fit.setParam(1, 'T_{R}', 1)
    fit.fit(g, 0, 1.1)
    fit.saveData('../fit/part5/taufit.txt')

    l = TLegend(0.55, 0.15, 0.85, 0.5)
    l.SetTextSize(0.03)
    l.AddEntry(g, 'Inverse Orientierungszeit #tau^{ -1}', 'p')
    l.AddEntry(fit.function,
               'Fit mit #tau^{ -1} (I) = #alpha I + #frac{1}{T_{R}}', 'l')
    fit.addParamsToLegend(l, [('%.0f', '%.0f'), ('%.5f', '%.5f')],
                          chisquareformat='%.2f',
                          units=['s^{-1}', 's'])
    l.Draw()

    g.Draw('P')
    c.Print('../img/part5/taufit.pdf', 'pdf')
コード例 #20
0
ファイル: eval_hg_peaks.py プロジェクト: Bigben37/FP1
def evalHgPeaks():
    data = I2Data.fromPath('../data/02_Hg_full_ngg11.txt')
    mins = data.findExtrema(10, 425, 630, False)
    mins.filterY(1300)
    with TxtFile.fromRelPath('../calc/hg_lines.txt', 'w') as f:
        for min in mins.points:
            f.writeline(str(min[0]))

    c = TCanvas('c1', '', 1280, 720)
    c.SetLogy()
    g = data.makeGraph('g', 'wavelength #lambda / nm', 'intensity / a.u.')
    g.GetXaxis().SetRangeUser(415, 620)
    g.SetMarkerStyle(1)
    g.Draw('AP')

    m = mins.makeGraph()
    if m:
        m.SetMarkerColor(2)
        m.Draw('P')

    c.Update()
    c.Print('../img/HgPeaks.pdf', 'pdf')
コード例 #21
0
ファイル: eval_na_peak.py プロジェクト: Bigben37/FP1
def evalNaPeaks():
    data = I2Data.fromPath('../data/01_Na_ngg13.txt')
    mins = data.findExtrema(200, 508, 630, False)
    mins.filterY(40000)
    with TxtFile.fromRelPath('../calc/na_lines.txt', 'w') as f:
        for min in mins.points:
            f.writeline(str(min[0]))

    c = TCanvas('c1', '', 1280, 720)
    g = data.makeGraph('g', 'wavelength #lambda / nm', 'intensity / a.u.')
    g.GetXaxis().SetRangeUser(415, 620)
    g.GetYaxis().SetTitleOffset(1.2)
    g.SetMarkerStyle(1)
    g.Draw('AP')

    m = mins.makeGraph()
    if m:
        m.SetMarkerColor(2)
        m.Draw('P')

    c.Update()
    c.Print('../img/NaPeaks.pdf', 'pdf')
コード例 #22
0
ファイル: calcFBAsym.py プロジェクト: QuantumDancer/FP2
def main():
    datas = Z0Data.fromROOTFile('../data/daten/daten_1.root', 'h33')
    energiedatas = datas.splitEnergies()
    binsizes = {
        88.48021: 30,
        89.47158: 30,
        90.22720: 28,
        91.23223: 75,
        91.97109: 31,
        92.97091: 30,
        93.71841: 30
    }
    results = dict()
    for energy, data in energiedatas.items():
        res = makeFBAFit(energy, data, binsizes[energy])
        if res:
            results[energy] = res

    ressort = list(results.items())
    ressort.sort(key=lambda x: x[0])
    with TxtFile('../calc/FBA.txt', 'w') as f:
        for energy, res in ressort:
            f.writeline('\t', *map(lambda x: '%.5f' % x, [energy] + list(res)))
コード例 #23
0
ファイル: fitter.py プロジェクト: QuantumDancer/FP2
    def saveData(self, path, mode='w', enc='utf-8'):
        """saves fitting info (chi^2, DoF, chi^2/DoF, paramters with values and errors, covariance and correlation matrix)

        Arguments:
        path -- relative path to file
        mode -- write mode (usually 'w' for overwriting or 'a' for appending)
        enc  -- encoding (default = 'utf-8')
        """
        with TxtFile.fromRelPath(path, mode) as f:
            f.writeline('fitting info')
            f.writeline('============')
            f.writeline(TxtFile.CHISQUARE + ':\t\t' + str(self.getChisquare()))
            f.writeline('DoF:\t' + str(self.getDoF()))
            f.writeline(TxtFile.CHISQUARE + '/DoF:\t' +
                        str(self.getChisquareOverDoF()))
            #f.writeline('\t', 'p-value:', *map(str, self.getPValue()))
            f.writeline('')
            f.writeline('parameters')
            f.writeline('==========')
            for i, param in self.params.items():
                f.writeline('\t', str(i), param['name'], str(param['value']),
                            TxtFile.PM, str(param['error']))
            f.writeline('')
            f.writeline('covariance matrix')
            f.writeline('=================')
            if self._covMatrix:
                f.writelines('\t'.join(str(j) for j in i) + '\n'
                             for i in self._covMatrix)
            f.writeline('')
            f.writeline('correlation matrix')
            f.writeline('==================')
            if self._corrMatrix:
                f.writelines('\t'.join(str(j) for j in i) + '\n'
                             for i in self._corrMatrix)
            f.writeline()
            f.close()
コード例 #24
0
def makeCuts(datas):
    efficencies = []
    sefficencies = []
    purities = []
    for cutnum, cutinfo in enumerate(CUTS):
        name, cut = cutinfo
        (effs, seffs), purity = makeCut(datas, cut, cutnum, name)
        efficencies.append(effs)
        sefficencies.append(seffs)
        purities.append(purity)
    # output for further calculations
    with TxtFile('../calc/efficencies.txt', 'w') as f:
        f.write2DArrayToFile(efficencies, ['%.8f'] * 4)
    with TxtFile('../calc/efficencies_error.txt', 'w') as f:
        f.write2DArrayToFile(sefficencies, ['%.8f'] * 4)
    with TxtFile('../calc/invEfficencies.txt', 'w') as f:
        f.write2DArrayToFile(inv(efficencies), ['%.8f'] * 4)
    with TxtFile('../calc/purities.txt', 'w') as f:
        f.write2DArrayToFile(list(zip(*[purities])), ['%.6f'])
    # output for protocol
    thead = [r"Schnitt$\backslash$MC-Daten", LATEXE, LATEXM, LATEXT, LATEXQ]
    firstrow = [LATEXE, LATEXM, LATEXT, LATEXQ]
    with TxtFile('../src/tab_effmat_val.tex', 'w') as f:
        f.write2DArrayToLatexTable(
            list(zip(*([firstrow] + list(zip(*efficencies))))), thead,
            ['%s'] + ['%.6f'] * 4, 'Effizienzmatrix.', 'tab:effmat:val')
    with TxtFile('../src/tab_effmat_err.tex', 'w') as f:
        f.write2DArrayToLatexTable(
            list(zip(*([firstrow] + list(zip(*sefficencies))))), thead,
            ['%s'] + ['%.6f'] * 4, 'Fehler der Effizienzmatrix.',
            'tab:effmat:err')
    with TxtFile('../src/tab_effmat_inv_val.tex', 'w') as f:
        f.write2DArrayToLatexTable(
            list(zip(*([firstrow] + list(zip(*inv(efficencies)))))), thead,
            ['%s'] + ['%.6f'] * 4, 'Inverse Effizienzmatrix.',
            'tab:inveffmat:val')
コード例 #25
0
ファイル: eval_I2_absorption.py プロジェクト: Bigben37/FP1
def getExcitedStateOscillationConstants():

    # plot spectrum

    data = I2Data.fromPath('../data/04_I2_ngg10_10ms.txt')
    progression = dict()
    for i in range(1, 3 + 1):
        progression[i] = I2Data.fromPath('../data/prog%d.txt' % i)

    c = TCanvas('c', '', 1280, 720)
    g = data.makeGraph('spectrum', 'wavelength #lambda / nm', 'intensity / a.u.')
    g.SetMarkerStyle(1)
    g.GetXaxis().SetRangeUser(505, 620)
    g.SetMinimum(18000)
    g.SetMaximum(49000)
    myY = TGaxis()
    myY.ImportAxisAttributes(g.GetYaxis())
    myY.SetMaxDigits(3)
    g.Draw('AL')

    pg1 = progression[1].makeGraph('prog1')
    pg1.SetMarkerColor(2)
    pg1.Draw('P')
    pg2 = progression[2].makeGraph('prog2')
    pg2.SetMarkerColor(3)
    pg2.Draw('P')
    pg3 = progression[3].makeGraph('prog3')
    pg3.SetMarkerColor(4)
    pg3.Draw('P')

    l = TLegend(0.6, 0.15, 0.85, 0.4)
    l.AddEntry('spectrum', 'measurement', 'l')
    l.AddEntry('prog1', 'first progression (#nu\'\' = 1)', 'p')
    l.AddEntry('prog2', 'second progression (#nu\'\' = 2)', 'p')
    l.AddEntry('prog3', 'third progression (#nu\'\' = 3)', 'p')
    l.Draw()

    c.Update()
    c.Print('../img/I2_absorption.pdf', 'pdf')

    # calculations

    start = [18, 7, 9]
    prog1ord = {'a': [], 'ae': [], 'b': [], 'be': []}
    for i, prog in progression.iteritems():

        # Calculate vacuum wavelength and create Birge-Sponer plot

        prog.correctValues()
        c = TCanvas('c%d' % i, '', 1280, 720)
        g = makeBirgeSponer(prog, start[i - 1]).makeGraph('prog%d_bs' % i, '#nu\' + 1/2', '#Delta G (#nu\' + 1/2) / (cm^{-1})')
        g.Draw('AP')

        # fit 2nd-order

        fit2ord = Fitter('prog%d_2ord' % i, '[0]-[1]*(2*x+2)+[2]*(3*x^2+6*x+13/4)')
        fit2ord.setParam(0, 'a', 120)
        fit2ord.setParam(1, 'b', 1)
        fit2ord.setParam(2, 'c', 0)
        fit2ord.fit(g, 4, 50)
        fit2ord.saveData('../calc/prog%d_fit2ord.txt' % i, 'w')
        l2 = TLegend(0.6, 0.7, 0.95, 0.95)
        l2.AddEntry(0, 'Fit 2nd. order', '')
        l2.AddEntry(fit2ord.function, 'y = a - b*(2*x+2) + c*(3*x^2+6*x+13/4)', 'l')
        fit2ord.addParamsToLegend(l2)
        l2.SetTextSize(0.03)
        l2.Draw()

        # fit 1st-order

        fit1ord = Fitter('prog%d_1ord' % i, '[0]-[1]*(2*x+2)')
        fit1ord.setParam(0, 'a', 120)
        fit1ord.setParam(1, 'b', 1)
        fit1ord.fit(g, 4, 50, '+')
        g.GetFunction('prog%d_1ord' % i).SetLineColor(4)
        fit1ord.saveData('../calc/prog%d_fit1ord.txt' % i, 'w')
        prog1ord['a'].append(fit1ord.params[0]['value'])
        prog1ord['ae'].append(fit1ord.params[0]['error'])
        prog1ord['b'].append(fit1ord.params[1]['value'])
        prog1ord['be'].append(fit1ord.params[1]['error'])
        l1 = TLegend(0.125, 0.15, 0.5, 0.4)
        l1.AddEntry(0, 'Fit 1st. order', '')
        l1.AddEntry(g.GetFunction('prog%d_1ord' % i), 'y = a - b*(2*x+2)', 'l')
        fit1ord.addParamsToLegend(l1)
        l1.SetTextSize(0.03)
        l1.Draw()

        c.Update()
        c.Print('../img/prog%d_birgesponer.pdf' % i, 'pdf')

    # save vibrational constants to latex file
    nus = [0, 1, 2]
    f = TxtFile('../src/ExcitedStateOscillationConstants.tex', 'w')
    f.write2DArrayToLatexTable(zip(nus, prog1ord['a'], prog1ord['ae'], prog1ord['b'], prog1ord['be']), 
                               ['$\\nu\'\'$', '$\omega_e\' / \\text{cm}^{-1}$', '$s_{\omega_e\'} / \\text{cm}^{-1}$', 
                                '$\omega_e\' x_e\' / \\text{cm}^{-1}$', '$s_{\omega_e\' x_e\'} / \\text{cm}^{-1}$'], 
                               ['%0.f', '%3.1f', '%.1f', '%.3f', '%.3f'], 
                               'Oscillation constants for first order fit of Birge-Sponer plots', 'tab:prog1ord')
    f.close()


    # calculate weighted average for fit 1st- order

    with TxtFile.fromRelPath('../calc/ExcitedStateOscillationConstants.txt', 'w') as f:
        f.writeline('\t', *map(lambda x: str(x), avgerrors(prog1ord['a'], prog1ord['ae'])))
        f.writeline('\t', *map(lambda x: str(x), avgerrors(prog1ord['b'], prog1ord['be'])))
コード例 #26
0
ファイル: part3.py プロジェクト: QuantumDancer/FP2
def evalNuclearSpin():
    results = []
    data = loadCSVToList('../data/part3/part3.txt')

    tabledata = []
    for d in data[-4:]:
        tabledata.append([d[0], d[2]] + d[4:-2])

    with TxtFile('../src/tab_part3_data.tex', 'w') as f:
        f.write2DArrayToLatexTable(tabledata, [
            r"$I_\text{L}$ / mA", r"$\nu$ / kHz", "$I_1$ / mA",
            "$s_{I_1}$ / mA", "$I_1'$ / mA", "$s_{I_1'}$ / mA"
        ], ['%.1f', '%.2f', '%d', '%d', '%d', '%d'],
                                   'Messdaten des Doppelresonanzexperiments.',
                                   'tab:part3:data')

    for iL, siL, f, sf, i1, si1, i1_, si1_, i4, si4 in data:  # I-Laser, frequency, I1, I1', I4 with respective errors
        # from mA to A
        i1 *= 1e-3
        si1 *= 1e-3
        i1_ *= 1e-3
        si1_ *= 1e-3
        i4 *= 1e-3
        si4 *= 1e-3
        # from kHz to Hz
        f *= 1e3
        sf *= 1e3
        # calc B1, B1'
        B1, sB1 = inductorIToB(1, i1, si1)
        B1_, sB1_ = inductorIToB(1, i1_, si1_)
        # calc B for nuclear spin
        B, sB = (B1 + B1_) / 2, sqrt(sB1**2 + sB1_**2) / 2
        # calc horizontal B-Field
        Bhor, sBhor = abs(B1 - B1_) / 2, sqrt(sB1**2 + sB1_**2) / 2
        # calc vertical B-Field
        Bvert, sBvert = inductorIToB(4, i4, si4)
        # calc nuclear spin
        I = mub_JT * B / (h_Js * f) - 0.5
        sI = mub_JT * B / (h_Js * f) * sqrt((sB / B)**2 + (sf / f)**2)
        results.append([["I_L/mA", (iL, siL)],
                        ["f/kHz", (f * 1e-3, sf * 1e-3)],
                        ["Bhor/µT", (Bhor * 1e6, sBhor * 1e6)],
                        ["Bver/µT", (Bvert * 1e6, sBvert * 1e6)],
                        ["I\t", (I, sI)]])
    # print out results
    with TxtFile('../calc/part3.txt', 'w') as f:
        for result in results:
            for description, values in result:
                f.writeline(
                    '\t',
                    *([description] + list(map(lambda x: '%.2f' % x, values))))
            f.writeline('')

    tableresults = []
    for result in results:
        flattend = [item for sublist in result for item in sublist[1]]
        flattend.pop(7)
        flattend.pop(6)
        flattend.pop(3)
        flattend.pop(1)
        tableresults.append(flattend)

    with TxtFile('../src/tab_part3_results.tex', 'w') as f:
        f.write2DArrayToLatexTable(
            tableresults[-4:], [
                r"$I_\text{L}$ / mA", r"$\nu$ / kHz",
                r"$B_\text{hor}$ / \textmu T",
                r"$s_{B_\text{hor}}$ / \textmu T", "$I$", "$s_I$"
            ], ['%.1f', '%.2f', '%.1f', '%.1f', '%.2f', '%.2f'],
            r"Berechnete horizontale Komponenten des Erdmagnetfeldes und Kernspin von Rubidium für das "
            +
            r"Doppelresonanzexperiment bei verschiedenen Lasterströmen $I_\text{L}$ und RF-Sender-Frequenzen $\nu$.",
            "tab:part3:results")
コード例 #27
0
ファイル: convertToTxt.py プロジェクト: QuantumDancer/FP2
from z0 import Z0Data
from txtfile import TxtFile

if __name__ == '__main__':
    files = [('mc/ee', 'h3'), ('mc/mm', 'h3'), ('mc/tt', 'h3'),
             ('mc/qq', 'h3'), ('daten/daten_1', 'h33')]
    for file, treename in files:
        data = Z0Data.fromROOTFile("../data/%s.root" % file, treename)
        with TxtFile('../data/%s.txt' % file, 'w') as f:
            for event in data.getEvents():
                f.writeline(
                    '\t',
                    *list(
                        map(str, [
                            event["run"], event["event"], event["Ncharged"],
                            event["Pcharged"], event["E_ecal"],
                            event["E_hcal"], event["E_lep"], event["cos_thru"],
                            event["cos_thet"]
                        ])))
コード例 #28
0
ファイル: part2.py プロジェクト: QuantumDancer/FP2
def makeHFSGraph(name, xmin, xmax):
    ch2 = OPData.fromPath('../data/part2/04.16/%s.tab' % name, 2)
    ch2.filterX(xmin, xmax)

    deltaY = 0.05

    c = TCanvas('c-%s' % name, '', 1280, 720)
    g2 = ch2.makeGraph('g2-%s' % name, "Zeit t / s", "Spannung U_{ph} / V")
    prepareGraph(g2, 2)
    g2.GetXaxis().SetRangeUser(xmin, xmax)
    g2.SetMinimum(ch2.getMinY() - deltaY)
    g2.SetMaximum(ch2.getMaxY() + deltaY)
    g2.Draw('APX')

    fitStartParams = getHFSFitStartParams(name)
    fitres = []
    tablefitres = []
    tablepeakcount = 0
    legendInfo = []
    isUp = name[:2] == 'up'
    if fitStartParams:
        print('got start params, starting to building fit functions')
        peakNum = 0
        offset = ch2.getY()[0]  # approx offset of underground
        slope = (ch2.getY()[-1] - ch2.getY()[0]) / (xmax - xmin)  # approx slope of underground
        for peakparams, xstartend in fitStartParams:
            xstart, xend = xstartend
            peakcount = len(peakparams)
            print('peakNum: ', peakNum)
            fitfunc = 'pol1(0)+gaus(2)'
            dpc = 2  # delta param count
            for i in range(1, peakcount):
                fitfunc += '+gaus(%d)' % (i * 3 + dpc)
            fit = Fitter('fitHFS%s_%d' % (name, peakNum), fitfunc)
            fit.function.SetLineColor(getRootColor(peakNum))
            fit.setParam(0, 'a', offset)
            fit.setParamLimits(0, 0, offset * 2)
            fit.setParam(1, 'b', slope)
            if isUp:
                fit.setParamLimits(1, 0, 2 * slope)
            else:
                fit.setParamLimits(1, 2 * slope, 0)
            for i, params in enumerate(peakparams):
                fit.setParam(i * 3 + dpc, 'A%d' % i, params[0])
                fit.setParam(i * 3 + dpc + 1, 'c%d' % i, params[1])
                fit.setParam(i * 3 + dpc + 2, 's%d' % i, params[2])
                if params[0] < 0:
                    fit.setParamLimits(i * 3 + dpc, 3 * params[0], 0)
                else:
                    fit.setParamLimits(i * 3 + dpc, 0, 2 * params[0])
                fit.setParamLimits(i * 3 + dpc + 1, params[1] - 2 * params[2], params[1] + 2 * params[2])
                fit.setParamLimits(i * 3 + dpc + 2, 0, 20 * params[2])
            fit.fit(g2, xstart, xend, 'M+')
            fit.saveData('../fit/part2/%s-%d.txt' % (name, peakNum))
            legendpeaks = []
            for i in range(len(peakparams)):
                fitres.append((fit.params[i * 3 + dpc + 1]['value'], 0.2 * fit.params[i * 3 + dpc + 2]['value']))
                tablepeakcount += 1
                legendpeaks.append(tablepeakcount)
                tablefitres.append((tablepeakcount, fit.params[i * 3 + dpc + 1]['value'] * 1e3, fit.params[i * 3 + dpc + 1]['error'] * 1e3,
                                    fit.params[i * 3 + dpc + 2]['value'] * 1e6, fit.params[i * 3 + dpc + 2]['error'] * 1e6))
            legendInfo.append((fit.function, tuple(legendpeaks)))
            peakNum += 1
        tablename = 'up' if isUp else 'down'
        with TxtFile('../src/tab_part2_hfspeaks_%s.tex' % tablename, 'w') as f:
            f.write2DArrayToLatexTable(tablefitres,
                                       ['Peak $i$', r'$\mu_i$ / ms', r'$s_{\mu_i}$ / ms', r'$\sigma_i$ / \textmu s', r'$s_{\sigma_i}$ / \textmu s'],
                                       ['%d', '%.5f', '%.5f', '%.1f', '%.1f'],
                                       r"Erwartungswerte $\mu_i$ und Standardabweichungen $\sigma_i$ der gefitteten Peaks des HFS-Spektrums.",
                                       "tab:hfs:peaks:%s" % tablename)

    g2.Draw('P')

    if isUp:
        l = TLegend(0.725, 0.15, 0.99, 0.45)
    else:
        l = TLegend(0.725, 0.55, 0.99, 0.85)
    l.SetTextSize(0.03)
    l.AddEntry(g2, 'Photodiodenspannung U_{ph}', 'l')
    for fitfunc, legendpeaks in legendInfo:
        n = len(legendpeaks)
        if n == 1:
            lstring = '%d' % legendpeaks
        elif n == 2:
            lstring = '%d und %d' % legendpeaks
        elif n == 3:
            lstring = '%d, %d und %d' % legendpeaks
        l.AddEntry(fitfunc, "Fit von Peak %s" % lstring, 'l')
    l.Draw()

    c.Update()
    if not DEBUG:
        c.Print('../img/part2/%s_fit.pdf' % name, 'pdf')

    return fitres
コード例 #29
0
ファイル: part2.py プロジェクト: QuantumDancer/FP2
def main():
    print('make graphs')
    print('===========')
    makeGraphs()
    print('eval etalon data')
    print('================')
    freqCalibrations = evalEtalonData()
    print('eval hfs peak data')
    print('==================')
    hfspeaks = evalHFSPeakData()

    litvals = (-3.07, -2.25, mean([-1.48, -1.12]), mean([1.56, 1.92]), 3.76, 4.58)
    reflit = litvals[3]
    litvals = list(map(lambda x: x - reflit, litvals))
    spectra = dict()

    for key in freqCalibrations.keys():
        gps, sgps = freqCalibrations[key]
        isUp = key[:2] == "up"
        spectrum = []
        if isUp:
            refpeak, srefpeak = hfspeaks[key][2]
            m = 1
        else:
            refpeak, srefpeak = hfspeaks[key][3]
            m = -1
        for peak, speak in hfspeaks[key]:
            freq = m * (refpeak - peak) * 1000 * gps
            if not compare2Floats(refpeak, peak):
                sfreq = abs(freq) * sqrt((sgps / gps) ** 2 + (sqrt(srefpeak ** 2 + speak ** 2) / (refpeak - peak)) ** 2)
            else:
                sfreq = 1000 * gps * speak
            if compare2Floats(freq, 0):
                freq = abs(freq)
            spectrum.append((freq, sfreq))
        if isUp:
            spectrum.reverse()
        spectra['up' if isUp else 'down'] = spectrum
        compareSpectrum('up' if isUp else 'down', spectrum, litvals)

    tabledata = []
    names = [r"\rb{87}, F:2$\to$1", r"\rb{87}, F:2$\to$2", r"\rb{85}, F:3$\to$2, 3$\to$3", r"\rb{85}, F:2$\to$2, 2$\to$3", 
             r"\rb{87}, F:1$\to$1", r"\rb{87}, F:1$\to$2"]  # Übergänge
    for i, litval in enumerate(litvals):
        tabledata.append([names[i]] + [litval] + list(spectra['up'][i]) + list(spectra['down'][i]))
    with TxtFile('../src/tab_part2_spectrum.tex', 'w') as f:
        f.write2DArrayToLatexTable(tabledata,
                                   ["Übergang",
                                    r'$\Delta \nu^\text{theo}$ / GHz',
                                    r'$\Delta \nu^\text{exp}_\text{up}$ / GHz', r'$s_{\Delta \nu^\text{exp}_\text{up}}$ / GHz',
                                    r'$\Delta \nu^\text{exp}_\text{down}$ / GHz', r'$s_{\Delta \nu^\text{exp}_\text{down}}$ / GHz'],
                                   ['%s', '%.2f', '%.2f', '%.2f', '%.2f', '%.2f'],
                                   "Theoretisches und (steigende und fallende Flanke) experimentell bestimmtes Hyperfeinstrukturspektrum von Rubidium.",
                                   "tab:hfs:spectrum")

    avgdata = []
    avgspectrum = []
    for name, lit, f1, sf1, f2, sf2 in tabledata:
        f, sf = avgerrors([f1, f2], [sf1, sf2])
        avgdata.append([name, lit, f, sf])
        avgspectrum.append((f, sf))
    compareSpectrum('avg', avgspectrum, litvals)
    with TxtFile('../src/tab_part2_spectrum_avg.tex', 'w') as f:
        f.write2DArrayToLatexTable(avgdata,
                                   ["Übergang",
                                    r'$\Delta \nu^\text{theo}$ / GHz',
                                    r'$\Delta \nu^\text{exp}_\text{avg}$ / GHz', r'$s_{\Delta \nu^\text{exp}_\text{avg}}$ / GHz'],
                                   ['%s', '%.2f', '%.2f', '%.2f', ],
                                   r"Theoretisches und aus den experimentellen Daten (\autoref{tab:hfs:spectrum}) gemitteltes Hyperfeinstrukturspektrum von Rubidium.",
                                   "tab:hfs:spectrum:avg")

    evalIntervalConst(avgspectrum)
コード例 #30
0
ファイル: eval_k.py プロジェクト: Bigben37/FP1
def makeMassFit():
    # config files
    # file = [mass, path]
    files = []
    files.append([2.0123, "../data/11_K_m9_3200_t420.txt", 420])
    files.append([2.0123, "../data/11b_K_m9_3200_t420.txt", 420])
    files.append([1.9047, "../data/13_K_m8_3200_t420.txt", 420])
    files.append([1.6812, "../data/15_K_m7_3200_t420.txt", 420])
    files.append([1.4827, "../data/17_K_m6_3200_t420.txt", 420])
    files.append([1.2952, "../data/19_K_m5_3200_t480.txt", 480])
    files.append([1.0993, "../data/21_K_m4_3200_t480.txt", 480])
    files.append([0.8086, "../data/23_K_m3_3200_t540.txt", 540])
    files.append([0.6954, "../data/25_K_m2_3200_t540.txt", 540])
    files.append([0.5007, "../data/27_K_m1_3200_t660.txt", 660])
    files.append([0.3030, "../data/29_K_m0_3200_t780.txt", 780])
    u = 0.760
    tu = 50

    d = DataErrors()

    for file in files:
        n = readSingleEntryFile(file[1])
        d.addPoint(file[0], n - u, 0.001, np.sqrt(n / file[2] + u / tu))

    d.saveDataToLaTeX(['Masse $m /$g', '$s_m /$g', 'Z\"ahlrate $n / (1/\\text{s})$', '$s_n / (1/\\text{s})$'],
                      ['%.3f', '%.3f', '%.3f', '%.3f'], 
                      'Z\"ahlraten von \\kalium\,f\"ur verschiedene Massen mit Fehlern', 'tab:data:kalium', '../src/data_kalium.tex', 'w')

    c = TCanvas('c2', '', 800, 600)
    g = d.makeGraph('g', 'Masse m / g', 'Z#ddot{a}hlrate n / (1/s)')
    g.SetMaximum(6)
    g.SetMinimum(2)
    g.Draw('AP')

    fit = Fitter('f', '[0]*(1-exp(-[1]*x))')
    fit.setParam(0, 'a')
    fit.setParam(1, 'b')
    fit.fit(g, 0.1, 2.5)
    fit.saveData('../fit/kalium.txt')
    
    a = fit.params[0]['value']
    sa = fit.params[0]['error']
    b = fit.params[1]['value']
    sb = fit.params[1]['error']

    l = TLegend(0.4, 0.15, 0.85, 0.5)
    l.AddEntry('g', '{}^{40} Kalium ohne Untergrund', 'p')  # TODO with error bar? (options +'e')
    l.AddEntry(fit.function, 'Fit mit n(m)=a(1-exp(-b*m))', 'l')
    l.AddEntry(0, '#chi^{2} / DoF : %f' % fit.getChisquareOverDoF(), '')
    l.AddEntry(0, 'Paramter:', '') 
    l.AddEntry(0, 'a: %e #pm %e' % (a, sa), '')
    l.AddEntry(0, 'b: %e #pm %e' % (b, sb), '')   
    l.SetTextSize(0.03)
    l.Draw()

    NA = 6.02214129e23
    hrel = 0.000118
    mrel = 39.0983 + 35.45
    f = 1.29
    rho = fit.getCorrMatrixElem(1, 0)
    thalf = (np.log(2) * NA * hrel * f) / (1.12 * mrel * 2 * a * b) / (3600 * 24 * 365.242)
    sthalf = thalf * np.sqrt((sa / a) ** 2 + (sb / b) ** 2 + 2 * rho * (sa / a) * (sb / b))

    with TxtFile.fromRelPath('../fit/kalium.txt', 'a') as f:
        f.writeline()
        f.writeline('calculations')
        f.writeline('============')
        f.writeline('\t', 'half-life of Kalium:', '%e' % thalf, TxtFile.PM, '%e' % sthalf)

    c.Update()
    c.Print('../img/Kalium40_Massenabhaengigkeit.pdf')