Exemplo n.º 1
0
def fitTransmissionSignal(name):
    data = OPData.fromPath(DIR + name + '.tab', 2)
    c = TCanvas('c', '', 1280, 720)
    g = data.makeGraph('g_%s' % name, 'Zeit t / s', 'Spannung der Photodiode U_{ph} / V')
    prepareGraph(g, 2)
    g.GetXaxis().SetRangeUser(0.004, 0.019)
    g.Draw('APX')

    xmin, xmax = 0.0054, 0.015

    fit = Fitter('fit_%s' % name[-2:], '[0] - [1] * exp(-x/[2])')
    fit.setParam(0, 'a', 0.01)
    fit.setParam(1, 'b', 100)
    fit.setParam(2, '#tau', 0.001)
    fit.fit(g, xmin, xmax, 'M')
    fit.saveData('../fit/part5/%s.txt' % name)

    g.Draw('P')

    l = TLegend(0.35, 0.2, 0.65, 0.525)
    l.SetTextSize(0.03)
    l.AddEntry(g, 'Spannung der Photodiode', 'p')
    l.AddEntry(fit.function, 'Fit mit U_{ph}(t) = a - b e^{-t/#tau}', 'l')
    fit.addParamsToLegend(l, [('%.6f', '%.6f'), ('%.2f', '%.2f'), ('%.6f', '%.6f')], chisquareformat='%.2f', units=['V', 'V', 's'])
    l.Draw()

    c.Update()
    c.Print('../img/part5/%s.pdf' % name.replace('.', '-'), 'pdf')

    return fit.params[2]['value'], fit.params[2]['error']
Exemplo n.º 2
0
def energyGauge():
    dataList = readFileToList('../calc/hg_lines.txt')
    elemNames = ['Hg'] * len(dataList)
    dataList += readFileToList('../calc/na_lines.txt')
    elemNames += ['Na'] * (len(dataList) - len(elemNames))
    litVals = readFileToList('../data/hg_litvals.txt')
    litVals += readFileToList('../data/na_litvals.txt')

    data = DataErrors()
    for val, litval in zip(dataList, litVals):
        data.addPoint(val, litval, I2Data.ERRORBIN, 0)
        
    c = TCanvas('c', '', 1280, 720)
    g = data.makeGraph('g', 'measured wavelength #lambda_{exp} / nm', 'literature value #lambda_{lit} / nm')
    g.Draw('AP')
    
    fit = Fitter('f', '[0]+[1]*x')
    fit.setParam(0, 'a', 0)
    fit.setParam(1, 'b', 1)
    fit.fit(g, 420, 600)
    fit.saveData('../calc/fit_energy_gauge.txt', 'w')
    
    l = TLegend(0.15, 0.6, 0.5, 0.85)
    l.AddEntry(fit.function, 'y = a + b*x', 'l')
    fit.addParamsToLegend(l)
    l.SetTextSize(0.03)
    l.Draw()
    
    c.Update()
    c.Print('../img/energy_gauge.pdf', 'pdf')
Exemplo n.º 3
0
def makeSigmaFit(darkTimes, sigmas):
    dt, sdt = list(zip(*darkTimes))
    s, ss = list(zip(*sigmas))
    data = DataErrors.fromLists(dt, s, sdt, ss)

    c = TCanvas('c_sigma', '', 1280, 720)
    g = data.makeGraph('g_sigma', 'Dunkelzeit t_{D} / ms', 'Verschmierung #sigma / #mus')
    g.Draw('APX')

    fit = Fitter('fit_sigma', 'pol1(0)')
    fit.setParam(0, 'a', 0)
    fit.setParam(1, 'b', 1)
    fit.fit(g, 0, 25)
    fit.saveData('../fit/sigma.txt')

    l = TLegend(0.6, 0.15, 0.85, 0.5)
    l.SetTextSize(0.03)
    l.AddEntry(g, 'Verschmierung #sigma', 'p')
    l.AddEntry(None, 'der Fermi-Verteilung', '')
    l.AddEntry(fit.function, 'Fit mit #sigma(t_{D}) = a + b t_{D}', 'l')
    fit.addParamsToLegend(l, (('%.2f', '%.2f'), ('%.2f', '%.2f')), chisquareformat='%.2f', units=['#mus', '10^{-3}'])
    l.Draw()

    g.Draw('P')
    c.Print('../img/part6/sigmaFit.pdf', 'pdf')
Exemplo n.º 4
0
def main():
    z, sz = 840, 40
    d = [210, 106, 75]
    sd = [10, 4, 4]
    calc = list(map(lambda x: -20 * log10(x / z), d))
    scalc = list(
        map(lambda x: 20 * sqrt((x[1] / x[0])**2 + (sz / z)**2) / log(10),
            zip(*[d, sd])))

    data = DataErrors.fromLists(calc, [12, 18, 21], scalc, [0] * 3)
    c = TCanvas('c', '', 1280, 720)
    g = data.makeGraph('g', 'measured attenuation m / dB',
                       'nominal value n / dB')
    g.Draw('AP')

    fit = Fitter('fit', 'pol1(0)')
    fit.setParam(0, 'a', 0)
    fit.setParam(1, 'b', 1)
    fit.fit(g, 11, 22)
    fit.saveData('../fit/attenuator.txt')

    l = TLegend(0.15, 0.6, 0.5, 0.85)
    l.SetTextSize(0.03)
    l.AddEntry(g, 'measured att. vs. nominal value', 'p')
    l.AddEntry(fit.function, 'fit with n = a + b m', 'l')
    fit.addParamsToLegend(l, (('%.2f', '%.2f'), ('%.2f', '%.2f')),
                          chisquareformat='%.4f',
                          units=['dB', ''],
                          lang='en')
    l.Draw()

    c.Update()
    c.Print('../img/attenuator.pdf', 'pdf')
Exemplo n.º 5
0
def fitLambda():
    data = Data()
    data.addPoint(500, 1.000279)
    data.addPoint(540, 1.000278)
    data.addPoint(600, 1.000277)
    data.addPoint(682, 1.000276)

    c = TCanvas('c1', '', 1280, 720)
    g = data.makeGraph('g', 'wavelength #lambda / nm', 'refraction index n')
    g.GetYaxis().SetLabelSize(0.03)
    g.GetYaxis().SetTitleOffset(1.39)
    g.Draw('AP')

    fit = Fitter('f', '[0]+[1]*x')
    fit.setParam(0, 'a', 2)
    fit.setParam(1, 'b', -1)
    fit.fit(g, 450, 700)
    fit.saveData('../calc/fit_lambda.txt', 'w')

    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.6, 0.87, 0.87)
    l.AddEntry('g', 'refraction index n as a function of wavelength #lambda', 'p')
    l.AddEntry(fit.function, 'fit with n(#lambda)= a+b*#lambda', 'l')
    fit.addParamsToLegend(l)
    l.SetTextSize(0.03)
    l.Draw()

    c.Update()
    c.Print('../img/fit_lambda.pdf', 'pdf')
Exemplo n.º 6
0
def makeBFit(darkTimes, Bs):
    dt, sdt = list(zip(*darkTimes))
    b, sb = list(zip(*Bs))
    data = DataErrors.fromLists(dt, b, sdt, sb)

    c = TCanvas('c_B', '', 1280, 720)
    g = data.makeGraph('g_B', 'Dunkelzeit t_{D} / ms', 'Fitparameter B / V')
    g.Draw('APX')

    fit = Fitter('fit_B', '[0] + [1] * (1 - exp(-x/[2]))')
    fit.function.SetNpx(1000)
    fit.setParam(0, 'a', 0.1)
    fit.setParam(1, 'b', 0.1)
    fit.setParam(2, 'T_{R_{F}}', 6)
    fit.fit(g, 0, 25)
    fit.saveData('../fit/B.txt')

    l = TLegend(0.55, 0.15, 0.85, 0.6)
    l.SetTextSize(0.03)
    l.AddEntry(g, 'Fitparameter B', 'p')
    l.AddEntry(fit.function, 'Fit mit B(t_{D}) = a + b (1 - e^{-x/T_{R_{F}}})', 'l')
    fit.addParamsToLegend(l, (('%.3f', '%.3f'), ('%.3f', '%.3f'), ('%.1f', '%.1f')), chisquareformat='%.2f', units=['V', 'V', 'ms'])
    l.Draw()

    g.Draw('P')
    c.Print('../img/part6/BFit.pdf', 'pdf')
Exemplo n.º 7
0
def main():
    z, sz = 840, 40
    d = [210, 106, 75]
    sd = [10, 4, 4]
    calc = list(map(lambda x:-20 * log10(x/z), d))
    scalc = list(map(lambda x:20 * sqrt((x[1]/x[0]) ** 2 + (sz/z)**2) / log(10), zip(*[d, sd])))
    
    data = DataErrors.fromLists(calc, [12, 18, 21], scalc, [0]*3)
    c = TCanvas('c', '', 1280, 720)
    g = data.makeGraph('g', 'measured attenuation m / dB', 'nominal value n / dB')
    g.Draw('AP')
    
    fit = Fitter('fit', 'pol1(0)')
    fit.setParam(0, 'a', 0)
    fit.setParam(1, 'b', 1)
    fit.fit(g, 11, 22)
    fit.saveData('../fit/attenuator.txt')
    
    l = TLegend(0.15, 0.6, 0.5, 0.85)
    l.SetTextSize(0.03)
    l.AddEntry(g, 'measured att. vs. nominal value', 'p')
    l.AddEntry(fit.function, 'fit with n = a + b m', 'l')
    fit.addParamsToLegend(l, (('%.2f', '%.2f'), ('%.2f', '%.2f')), chisquareformat='%.4f', units=['dB', ''], lang='en')
    l.Draw()
    
    c.Update()
    c.Print('../img/attenuator.pdf', 'pdf')
Exemplo n.º 8
0
def main():
    x, y, sy = zip(*loadCSVToList('../calc/part3/Co-Si_mergedbins.txt'))
    data = DataErrors.fromLists(x, y, [0]*len(x), sy)
    c = TCanvas('c', '', 1280, 720)
    g = data.makeGraph('g', 'Kanal k', 'Counts N')
    g.SetMarkerStyle(8)
    g.SetMarkerSize(0.5)
    g.SetLineColor(15)
    g.SetLineWidth(0)
    g.Draw('AP')
    
    fit = Fitter('f', '1/(sqrt(2*pi*[2]^2))*gaus(0)')
    fit.setParam(0, 'A', 50)
    fit.setParam(1, 'x_{c}', 690)
    fit.setParam(2, 's', 20)
    fit.fit(g, 672, 712)
    fit.saveData('../calc/part3/fit_Co-Si_01_mergedbins.txt', 'w')
    with TxtFile('../calc/part3/fit_Co-Si_01_mergedbins_raw.txt', 'w') as f:
        for key, param in fit.params.iteritems():
            f.writeline('\t', *map(str, [param['value'], param['error']]))
    
    l = TLegend(0.7, 0.5, 0.95, 0.85)
    l.SetTextSize(0.0225)
    l.AddEntry(g, 'Gemittelte Messwerte', 'p')
    l.AddEntry(fit.function, 'Fit mit', 'l')
    l.AddEntry(0, 'N(k) = #frac{A}{#sqrt{2#pi*#sigma^{2}}} exp(- #frac{1}{2} (#frac{x-x_{c}}{#sigma})^{2})', '')
    l.AddEntry(0, '', '')
    fit.addParamsToLegend(l, chisquareformat='%.2f')
    l.Draw()
    
    c.Update()
    c.Print('../img/part3/Co-Si_01_mergedbins.pdf', 'pdf')
Exemplo n.º 9
0
def evalPedestal():
    name = 'pedestal'
    data = MyonData.fromPath('../data/%s.TKA' % name)
    data.convertToCountrate()
    c = TCanvas('c_ped', '', 1280, 720)
    g = data.makeGraph('g_ped', 'channel c', 'countrate n / (1/s)')
    g.SetLineColor(1)
    g.SetLineWidth(1)
    g.GetXaxis().SetRangeUser(0, 20)
    g.Draw('APX')
    
    fit = Fitter('fit_%s' % name, 'gaus(0)')
    fit.setParam(0, 'A', 30)
    fit.setParam(1, 'x', 6)
    fit.setParam(2, '#sigma', 3)
    fit.setParamLimits(2, 0, 100)
    fit.fit(g, 3.5, 10.5)
    fit.saveData('../fit/%s.txt' % name)
    
    l = TLegend(0.55, 0.6, 0.85, 0.85)
    l.SetTextSize(0.03)
    l.AddEntry(g, 'pedestal', 'p')
    l.AddEntry(fit.function, 'fit with n(c) = A gaus(c; x, #sigma)', 'l')
    fit.addParamsToLegend(l, (('%.2f', '%.2f'), ('%.3f', '%.3f'), ('%.3f', '%.3f')), chisquareformat='%.2f', units=('1/s', '', ''), lang='en')
    l.Draw()

    g.Draw('P')
    c.Update()
    c.Print('../img/%s.pdf' % name, 'pdf')
    
    return (fit.params[1]['value'], fit.params[1]['error'])
Exemplo n.º 10
0
def fitX0(period):
    # get data and make graph
    data = X0Data.fromPath('../data/T_%dms.txt' % period)
    c = TCanvas('c_%d' % period, '', 1280, 720)
    g = data.makeGraph('g_%d' % period, 'Differenzenfrequenz #Delta#nu / kHz', 'Auftreffpunkt x_{0}\' / mm')
    g.Draw('AP')

    # axis cross
    vline = TLine(0, 33, 0, 60)
    vline.Draw()

    # fit
    fit = Fitter('fit_%d' % period, 'pol1(0)')
    fit.setParam(0, 'x_{m}', 47)
    fit.setParam(1, 'm')
    fit.fit(g, min(data.getX()) - 3, max(data.getX()) + 3)
    fit.saveData('../calc/fit_T_%dms.txt' % period, 'w')

    # legend
    l = TLegend(0.15, 0.65, 0.425, 0.85)
    l.SetTextSize(0.03)
    l.AddEntry(g, 'Messreihe bei T = %d ms' % period, 'p')
    l.AddEntry(fit.function, 'Fit mit x_{0}\'(#Delta#nu) = x_{m} + m * #Delta#nu', 'l')
    fit.addParamsToLegend(l, [('%.3f', '%.3f'), ('%.4f', '%.4f')], chisquareformat='%.2f')
    l.Draw()

    # print
    c.Update()
    c.Print('../img/fit_T_%dms.pdf' % period, 'pdf')

    return [(fit.params[0]['value'], fit.params[0]['error']), (fit.params[1]['value'], fit.params[1]['error'])]
Exemplo n.º 11
0
def compareSpectrum(prefix, spectrum, litvals):
    xlist = list(zip(*spectrum))[0]
    sxlist = list(zip(*spectrum))[1]

    compData = DataErrors.fromLists(xlist, litvals, sxlist, [0] * len(litvals))

    c = TCanvas('c_%s_compspectrum' % prefix, '', 1280, 720)
    g = compData.makeGraph('g_%s_compspectrum' % prefix,
                           'experimentell bestimmte HFS-Aufspaltung #Delta#nu^{exp}_{%s} / GHz' % prefix,
                           'theoretische HFS-Aufspaltung #Delta#nu^{theo} / GHz')
    g.Draw('AP')

    fit = Fitter('fit_%s_compspectum' % prefix, 'pol1(0)')
    fit.setParam(0, 'a_{%s}' % prefix, 0)
    fit.setParam(1, 'b_{%s}' % prefix, 1)
    fit.fit(g, compData.getMinX() - 0.5, compData.getMaxX() + 0.5)

    if prefix == "up":
        l = TLegend(0.15, 0.6, 0.45, 0.85)
    else:
        l = TLegend(0.15, 0.6, 0.5, 0.85)
    l.SetTextSize(0.03)
    l.AddEntry(g, 'Spektrum', 'p')
    l.AddEntry(fit.function, 'Fit mit #Delta#nu^{theo} = a_{%s} + b_{%s} #Delta#nu^{exp}_{%s}' % (prefix, prefix, prefix), 'l')
    fit.addParamsToLegend(l, [('%.2f', '%.2f'), ('%.3f', '%.3f')], chisquareformat='%.2f', units=['GHz', ''])
    l.Draw()

    c.Update()
    if not DEBUG:
        c.Print('../img/part2/%s-spectrum.pdf' % prefix, 'pdf')
Exemplo n.º 12
0
def fitT(x0):
    # get data and make graph
    data = TData.fromPath('../data/x0_%dmm.txt' % x0)
    c = TCanvas('c_%d' % x0, '', 1280, 720)
    g = data.makeGraph('g_%d' % x0, 'Kreisfrequenz #omega / (rad/ms)', 'Differenzenfrequenz #Delta#nu / kHz')
    g.Draw('AP')

    # fit
    fit = Fitter('fit_%d' % x0, 'pol1(0)')
    fit.setParam(0, 'a')
    fit.setParam(1, 'b')
    fit.fit(g, min(data.getX()) - 3, max(data.getX()) + 3)
    fit.saveData('../calc/fit_x0_%dmm.txt' % x0, 'w')

    # legend
    l = TLegend(0.15, 0.625, 0.425, 0.85)
    l.SetTextSize(0.03)
    l.AddEntry(g, 'Messreihe bei x_{0}\' = %d mm' % x0, 'p')
    l.AddEntry(fit.function, 'Fit mit #Delta#nu (#omega) = a + b*#omega', 'l')
    fit.addParamsToLegend(l, [('%.1f', '%.1f'), ('%.0f', '%.0f')], chisquareformat='%.2f')
    l.Draw()

    # print
    c.Update()
    c.Print('../img/fit_x0_%dmm.pdf' % x0, 'pdf')

    return [(fit.params[0]['value'], fit.params[0]['error']), (fit.params[1]['value'], fit.params[1]['error'])]
Exemplo n.º 13
0
def evalPedestal():
    name = 'pedestal'
    data = MyonData.fromPath('../data/%s.TKA' % name)
    data.convertToCountrate()
    c = TCanvas('c_ped', '', 1280, 720)
    g = data.makeGraph('g_ped', 'channel c', 'countrate n / (1/s)')
    g.SetLineColor(1)
    g.SetLineWidth(1)
    g.GetXaxis().SetRangeUser(0, 20)
    g.Draw('APX')

    fit = Fitter('fit_%s' % name, 'gaus(0)')
    fit.setParam(0, 'A', 30)
    fit.setParam(1, 'x', 6)
    fit.setParam(2, '#sigma', 3)
    fit.setParamLimits(2, 0, 100)
    fit.fit(g, 3.5, 10.5)
    fit.saveData('../fit/%s.txt' % name)

    l = TLegend(0.55, 0.6, 0.85, 0.85)
    l.SetTextSize(0.03)
    l.AddEntry(g, 'pedestal', 'p')
    l.AddEntry(fit.function, 'fit with n(c) = A gaus(c; x, #sigma)', 'l')
    fit.addParamsToLegend(l, (('%.2f', '%.2f'), ('%.3f', '%.3f'),
                              ('%.3f', '%.3f')),
                          chisquareformat='%.2f',
                          units=('1/s', '', ''),
                          lang='en')
    l.Draw()

    g.Draw('P')
    c.Update()
    c.Print('../img/%s.pdf' % name, 'pdf')

    return (fit.params[1]['value'], fit.params[1]['error'])
Exemplo n.º 14
0
def fitTransmissionSignal(name):
    data = OPData.fromPath(DIR + name + '.tab', 2)
    c = TCanvas('c', '', 1280, 720)
    g = data.makeGraph('g_%s' % name, 'Zeit t / s',
                       'Spannung der Photodiode U_{ph} / V')
    prepareGraph(g, 2)
    g.GetXaxis().SetRangeUser(0.004, 0.019)
    g.Draw('APX')

    xmin, xmax = 0.0054, 0.015

    fit = Fitter('fit_%s' % name[-2:], '[0] - [1] * exp(-x/[2])')
    fit.setParam(0, 'a', 0.01)
    fit.setParam(1, 'b', 100)
    fit.setParam(2, '#tau', 0.001)
    fit.fit(g, xmin, xmax, 'M')
    fit.saveData('../fit/part5/%s.txt' % name)

    g.Draw('P')

    l = TLegend(0.35, 0.2, 0.65, 0.525)
    l.SetTextSize(0.03)
    l.AddEntry(g, 'Spannung der Photodiode', 'p')
    l.AddEntry(fit.function, 'Fit mit U_{ph}(t) = a - b e^{-t/#tau}', 'l')
    fit.addParamsToLegend(l, [('%.6f', '%.6f'), ('%.2f', '%.2f'),
                              ('%.6f', '%.6f')],
                          chisquareformat='%.2f',
                          units=['V', 'V', 's'])
    l.Draw()

    c.Update()
    c.Print('../img/part5/%s.pdf' % name.replace('.', '-'), 'pdf')

    return fit.params[2]['value'], fit.params[2]['error']
Exemplo n.º 15
0
def fitA(amps, times):
    listx, listsx = zip(*times)
    listy, listsy = zip(*amps)
    slaser_rel = 0.05
    listsy = list(listsy)
    for i, y in enumerate(listy):
        listsy[i] = y * np.sqrt(listsy[i] ** 2 + slaser_rel ** 2)
    data = DataErrors.fromLists(listx, listy, listsx, listsy)

    c = TCanvas('cA', '', 1280, 720)
    g = data.makeGraph('A', 'Zeit t / s', 'Amplitude A / V')
    g.GetYaxis().SetTitleOffset(1.2)
    g.Draw('AP')

    fit = Fitter('A', '[0]*exp(-(x)/[1])+[2]')
    fit.function.SetNpx(1000)
    fit.setParam(0, 'C', 5e-8)
    fit.setParam(1, '#tau_{n}', 45e-6)
    fit.setParam(2, 'a', 0)
    fit.fit(g, 7.5e-6, 18e-6)
    fit.saveData('../calc/part2/volt_fit_A.txt')

    l = TLegend(0.625, 0.625, 0.85, 0.85)
    l.SetTextSize(0.03)
    l.AddEntry('A', 'Messung', 'p')
    l.AddEntry(fit.function, 'Fit mit A(t) = C*e^{- #frac{t}{#tau_{n}}} + a', 'l')
    fit.addParamsToLegend(l, [('%.2e', '%.1e'), ('%.2e', '%.1e'), ('%.2e', '%.1e')], chisquareformat='%.2f')
    l.Draw()

    if PRINTGRAPHS or True:
        c.Update()
        c.Print('../img/part2/volt_fitA.pdf', 'pdf')
        c.SetLogy()
        c.Update()
        c.Print('../img/part2/volt_fitA_log.pdf', 'pdf')
Exemplo n.º 16
0
def fitSigma(sigs, times):
    listx, listsx = zip(*times)
    listy, listsy = zip(*sigs)
    listy = map(abs, listy)   # fits can yield negative sigma, because it only occurse to
    data = DataErrors.fromLists(listx, listy, listsx, listsy)

    c = TCanvas('cSigma', '', 1280, 720)
    g = data.makeGraph('Sigma', 'Zeit t / s', 'Standardabweichung #sigma / cm')
    g.Draw('AP')

    fit = Fitter('fitS', 'sqrt(2*[0]*(x + [1]))')
    fit.setParam(0, 'D_{n}', 100)
    fit.setParam(1, 't_{0}', 0)
    fit.fit(g, 1e-6, 21e-6)
    fit.saveData('../calc/part2/dist_fit_sigma.txt')

    l = TLegend(0.15, 0.625, 0.45, 0.85)
    l.SetTextSize(0.03)
    l.AddEntry('Sigma', 'Messung', 'p')
    l.AddEntry(fit.function, 'Fit mit #sigma(t) = #sqrt{2*D_{n}*(t + t_{0})}', 'l')
    fit.addParamsToLegend(l, [('%.1f', '%.1f'), ('%.2e', '%.2e')], chisquareformat='%.2f')
    l.Draw()

    if PRINTGRAPHS or True:
        c.Update()
        c.Print('../img/part2/dist_fitSigma.pdf', 'pdf')
Exemplo n.º 17
0
def fitSpectrum(detector, element, params, logy=True):
    data = P3SemiCon.fromPath('../data/part3/%s-%s.mca' % (element, detector))
    printTotalSpectrum(data, element, detector, logy)

    fitresults = []
    for i, peak in enumerate(params):
        c = TCanvas('cpeakl_%s-%s_%d' % (element, detector, i), '', 1280, 720)
        g = data.makeGraph('g%s-%s_%d' % (element, detector, i), 'Kanal k', 'Counts N')
        prepareGraph(g)
        g.GetXaxis().SetRangeUser(peak[2][0], peak[2][1])
        g.SetMinimum(peak[3][0])
        g.SetMaximum(peak[3][1])
        g.Draw('AP')

        fit = None
        paramnames = []
        if len(peak[0]) == 5:
            fit = Fitter('fit%d' % i, 'pol1(0) + 1/(sqrt(2*pi*[4]^2))*gaus(2)')
            paramnames = ['a', 'b', 'A', 'k_{c}', 's']
        elif len(peak[0]) == 4:
            fit = Fitter('fit%d' % i, '[0] + 1/(sqrt(2*pi*[3]^2))*gaus(1)')
            paramnames = ['a', 'A', 'k_{c}', 's']
        elif len(peak[0]) == 3:
            fit = Fitter('fit%d' % i, '1/(sqrt(2*pi*[2]^2))*gaus(0)')
            paramnames = ['A', 'k_{c}', 's']

        l = None
        if len(peak[0]) > 0:
            for j, param in enumerate(peak[0]):
                fit.setParam(j, paramnames[j], param)
            fit.fit(g, *peak[1])

            fitname = ''
            if len(peak[0]) == 5:
                fitname = 'N(k) = a + b*k + #frac{A}{#sqrt{2#pi*#sigma^{2}}} exp(- #frac{1}{2} (#frac{k-k_{c}}{#sigma})^{2})'
            elif len(peak[0]) == 4:
                fitname = 'N(k) = a + #frac{A}{#sqrt{2#pi*#sigma^{2}}} exp(- #frac{1}{2} (#frac{k-k_{c}}{#sigma})^{2})'
            elif len(peak[0]) == 3:
                fitname = 'N(k) = #frac{A}{#sqrt{2#pi*#sigma^{2}}} exp(- #frac{1}{2} (#frac{k-k_{c}}{#sigma})^{2})'
            fit.saveData('../calc/part3/fit_%s-%s_%02d.txt' % (element, detector, i), 'w')
            results = []
            for j, param in fit.params.iteritems():
                results.append((param['value'], param['error']))
            fitresults.append(results)

            # legend
            l = TLegend(0.675, 0.5, 0.995, 0.85)
            l.SetTextSize(0.025)
            l.AddEntry(g, 'Messwerte', 'p')
            l.AddEntry(fit.function, 'Fit mit', 'l')
            l.AddEntry(0, fitname, '')
            l.AddEntry(0, '', '')
            fit.addParamsToLegend(l, chisquareformat='%.2f')
            l.Draw()

        c.Update()
        if PRINTGRAPHS:
            c.Print('../img/part3/%s-%s_%02d.pdf' % (element, detector, i), 'pdf')
    return fitresults
Exemplo n.º 18
0
def makeCSGraphUnderground(ctype, startGammaEE=None):
    data = loadCrossSection(ctype)
    c = TCanvas('c_%s' % ctype, '', 1280, 720)
    g = data.makeGraph('g_%s' % ctype, '#sqrt{s} / GeV', '#sigma / nb')
    g.Draw('AP')

    if not startGammaEE:
        fit = Fitter(
            'fit_%s' % ctype,
            '[0] + [1] * x + 12*pi / [2]^2 * x^2 * [3]^2 / ((x^2-[2]^2)^2 + x^4 * [4]^2 / [2]^2) * 0.3894e6'
        )
        fitfuncstring = "a + b#sqrt{s} + #frac{12#pi}{M_{Z}^{2}} #frac{s #Gamma_{%s}^{2}}{(s-M_{Z}^{2})^{2} + s^{2} #Gamma_{Z}^{2} / M_{Z}^{2}}" % ctype[
            0]
    else:
        fit = Fitter(
            'fit_%s' % ctype,
            '[0] + [1] * x + 12*pi / [2]^2 * x^2 * [3] * [5] / ((x^2-[2]^2)^2 + x^4 * [4]^2 / [2]^2) * 0.3894e6'
        )
        fitfuncstring = "a + b#sqrt{s} + #frac{12#pi}{M_{Z}^{2}} #frac{s #Gamma_{e} #Gamma_{%s}}{(s-M_{Z}^{2})^{2} + s^{2} #Gamma_{Z}^{2} / M_{Z}^{2}}" % ctype[
            0]
    fit.setParam(0, 'a', 0)
    fit.setParam(1, 'b', 0)
    fit.setParam(2, 'M_{Z}', 91.2)
    fit.setParam(4, '#Gamma_{Z}', 2.5)
    if not startGammaEE:
        fit.setParam(3, '#Gamma_{%s}' % ctype[0], 0.08)
    else:
        fit.setParam(3, '#Gamma_{e}', startGammaEE, True)
        fit.setParam(5, '#Gamma_{%s}' % ctype[0], 2)
    fit.fit(g, 88, 94)
    fit.saveData('../fit/crosssections_%s.txt' % ctype)

    l = TLegend(0.625, 0.575, 0.98, 0.98)
    l.SetTextSize(0.03)
    l.AddEntry(g, "%s Wirkungsquerschnitte" % ctype, 'p')
    l.AddEntry(fit.function, "Fit mit #sigma(s) = ", 'l')
    l.AddEntry(None, "", '')
    l.AddEntry(None, fitfuncstring, '')
    l.AddEntry(None, "", '')
    if not startGammaEE:
        fit.addParamsToLegend(
            l, [('%.3f', '%.3f'), ('%.3f', '%.3f'), ('%.3f', '%.3f'),
                ('%.3f', '%.3f'), ('%.3f', '%.3f')],
            chisquareformat='%f',
            units=['nb', 'nb/GeV', 'GeV / c^{2}', 'GeV', 'GeV'])
    else:
        fit.addParamsToLegend(
            l, [('%.3f', '%.3f'), ('%.3f', '%.3f'), ('%.3f', '%.3f'), '%.4f',
                ('%.3f', '%.3f'), ('%.3f', '%.3f')],
            chisquareformat='%f',
            units=['nb', 'nb/GeV', 'GeV/c^{2}', 'GeV', 'GeV', 'GeV'])
    l.Draw()

    c.Update()
    c.Print('../img/crosssections_%s.pdf' % ctype, 'pdf')

    return fit.params[3]['value']
Exemplo n.º 19
0
Arquivo: eval.py Projeto: Bigben37/FP1
def main():
    snu = ERRORS["nu"]  # TODO get error
    sB = ERRORS["B"]
    sgyrorel = 0
    files = ["H", "Glycol", "Teflon"]
    for file in files:
        datalist = loadCSVToList("../data/03-%s.txt" % file)
        if len(datalist) == 1:
            B, nu = datalist[0]
            gyro, sgyro = calcGyro(nu, snu, B, sB)
            if not sgyrorel == 0:
                sgyro = gyro * sgyrorel
            with TxtFile("../calc/%s.txt" % file, "w") as f:
                f.writeline("\t", "gyro", *map(str, (gyro, sgyro)))
                f.writeline("\t", "mu", *map(str, calcMu(gyro, sgyro)))
                f.writeline("\t", "gI", *map(str, calcNucGFactor(gyro, sgyro)))
        else:
            x, y = zip(*datalist)
            sx = [0] * len(x)
            sy = [snu] * len(y)
            data = DataErrors.fromLists(x, y, sx, sy)
            data.setXErrorAbs(sB)
            c = TCanvas("c%s" % file, "", 1280, 720)
            g = data.makeGraph("g%s" % file, "Magnetfeld B / mT", "Resonanzfrequenz #nu / MHz")
            g.Draw("AP")

            fit = Fitter("fit%s" % file, "[0]*x")
            fit.setParam(0, "m", 0.002)
            fit.fit(g, datalist[0][0] * 0.95, datalist[-1][0] * 1.05)
            fit.saveData("../calc/fit-%s.txt" % file, "w")

            l = TLegend(0.15, 0.60, 0.475, 0.85)
            l.SetTextSize(0.03)
            l.AddEntry(g, "Messdaten", "p")
            l.AddEntry(fit.function, "Fit mit #nu(B) = m*B", "l")
            l.AddEntry(0, "", "")
            fit.addParamsToLegend(
                l,
                [("%.5f", "%.5f"), ("%.2f", "%.2f")],
                chisquareformat="%.2f",
                advancedchi=True,
                units=["MHz / mT", "MHz"],
            )
            l.Draw()

            gyro = 2 * np.pi * fit.params[0]["value"] * 1e9  # in Hz / T
            sgyro = 2 * np.pi * fit.params[0]["error"] * 1e9  # in Hz / T
            sgyrorel = sgyro / gyro
            with TxtFile("../calc/%s.txt" % file, "w") as f:
                f.writeline("\t", "gyro", *map(str, (gyro, sgyro)))
                f.writeline("\t", "sgyrorel", str(sgyrorel))
                f.writeline("\t", "mu", *map(str, calcMu(gyro, sgyro)))
                f.writeline("\t", "gI", *map(str, calcNucGFactor(gyro, sgyro)))

            c.Update()
            c.Print("../img/03-%s.pdf" % file, "pdf")
Exemplo n.º 20
0
def evalDiode():
    datalist = loadCSVToList('../data/part1/Kennlinie.txt')
    data = DataErrors()
    U0 = datalist[0][1]
    sU0 = 0.05 + 0.01 * U0
    for I, u in datalist:
        U = u - U0
        su = 5 + 0.01 * u
        sU = sqrt(su**2 + sU0**2)
        data.addPoint(I, U, 0.1, sU)
    xmin, xmax = 53, 71.5

    c = TCanvas('c_diode', '', 1280, 720)
    g = data.makeGraph('g_diode', "Laserstrom I_{L} / mA",
                       "Photodiodenspannung U_{ph} / mV")
    g.GetXaxis().SetRangeUser(-5, 90)
    g.SetMinimum(-50)
    g.SetMaximum(1400)
    g.Draw('APX')

    # y=0 line
    line = TLine(-5, 0, 90, 0)
    line.SetLineColor(OPData.CH2ECOLOR)
    line.Draw()

    data.filterX(xmin, xmax)
    g2 = data.makeGraph('g_diode_2', "Laserstrom I_{L} / mA",
                        "Photodiodenspannung U_{ph} / mV")
    g2.SetMarkerColor(OPData.CH1COLOR)
    g2.SetLineColor(OPData.CH1COLOR)

    fit = Fitter('fit_diode', '[0] * (x-[1])')
    fit.function.SetNpx(1000)
    fit.setParam(0, 'a', 1)
    fit.setParam(1, 'I_{th}', 50)
    fit.fit(g2, 40, 77)
    fit.saveData('../fit/part1/kennlinie.txt')

    l = TLegend(0.15, 0.55, 0.4, 0.85)
    l.SetTextSize(0.03)
    l.AddEntry(g, 'Laserdiodenkennlinie', 'p')
    l.AddEntry(g2, 'Ausschnitt zum Fitten', 'p')
    l.AddEntry(fit.function, 'Fit mit U_{ph} = a (I_{ L} - I_{ th} )', 'l')
    fit.addParamsToLegend(l, (('%.1f', '%.1f'), ('%.2f', '%.2f')),
                          chisquareformat='%.2f',
                          units=['mV/mA', 'mA'])
    l.Draw()

    g.Draw('P')
    g2.Draw('P')

    c.Update()
    c.Print('../img/part1/diodenkennlinie.pdf', 'pdf')
Exemplo n.º 21
0
def makeCSGraph(ctype, startGammaEE=None):
    data = loadCrossSection(ctype)
    c = TCanvas('c_%s' % ctype, '', 1280, 720)
    g = data.makeGraph('g_%s' % ctype, '#sqrt{s} / GeV', '#sigma / nb')
    g.Draw('AP')
    
    if not startGammaEE:
        fit = Fitter('fit_%s' % ctype, '(12*pi / [0]^2) * (x^2 * [1]^2) / ((x^2-[0]^2)^2 + x^4 * [2]^2 / [0]^2) * 0.3894*10^6')  #  GeV^-2 = 0.3894 mb 
        fitfuncstring = "#frac{12#pi}{M_{Z}^{2}} #frac{s #Gamma_{%s}^{2}}{(s-M_{Z}^{2})^{2} + s^{2} #Gamma_{Z}^{2} / M_{Z}^{2}}" % ctype[0]
    else:
        fit = Fitter('fit_%s' % ctype, '(12*pi / [0]^2) * (x^2 * [1] * [2]) / ((x^2-[0]^2)^2 + x^4 * [3]^2 / [0]^2) * 0.3894*10^6')
        fitfuncstring = "#frac{12#pi}{M_{Z}^{2}} #frac{s #Gamma_{m} #Gamma_{%s}}{(s-M_{Z}^{2})^{2} + s^{2} #Gamma_{Z}^{2} / M_{Z}^{2}}" % ctype[0]
    fit.setParam(0, 'M_{Z}', 91.2)
    fit.setParamLimits(0, 0, 1000)
    if not startGammaEE:
        fit.setParam(1, '#Gamma_{%s}' % ctype[0], 0.08)
        fit.setParamLimits(1, 0, 1000)
        fit.setParam(2, '#Gamma_{Z}', 2.5)
        fit.setParamLimits(2, 0, 1000)
    else:
        fit.setParam(1, '#Gamma_{m}', startGammaEE, True)
        fit.setParam(2, '#Gamma_{%s}' % ctype[0], 1.5)
        fit.setParam(3, '#Gamma_{Z}', 2.5)
        fit.setParamLimits(2, 0, 1000)
    fit.fit(g, 88, 94, '')
    fit.saveData('../fit/crosssections_%s.txt' % ctype)
    
    l = TLegend(0.625, 0.6, 0.98, 0.975)
    l.SetTextSize(0.03)
    l.AddEntry(g, "%s Wirkungsquerschnitte" % ctype, 'p')
    l.AddEntry(fit.function, "Fit mit #sigma(s) = %s" % fitfuncstring, 'l')
    l.AddEntry(None, "", '')
    if not startGammaEE:
        fit.addParamsToLegend(l, [('%.3f', '%.3f'), ('%.4f', '%.4f'), ('%.3f', '%.3f')], chisquareformat='%f', units=['GeV / c^{2}', 'GeV', 'GeV'])
    else:
        fit.addParamsToLegend(l, [('%.3f', '%.3f'), '%.4f', ('%.3f', '%.3f'), ('%.3f', '%.3f')], chisquareformat='%f', units=['GeV/c^{2}', 'GeV', 'GeV', 'GeV'])
    l.Draw()

    c.Update()
    if not DEBUG:
        c.Print('../img/crosssections_%s.pdf' % ctype, 'pdf')
        
    if not startGammaEE:
        result = [(fit.params[0]['value'], fit.params[0]['error']), 
                  (fit.params[1]['value'], fit.params[1]['error']), 
                  (fit.params[2]['value'], fit.params[2]['error'])]
    else:
        result = [(fit.params[0]['value'], fit.params[0]['error']), 
                  (fit.params[2]['value'], fit.params[2]['error']), 
                  (fit.params[3]['value'], fit.params[3]['error'])]
    
    return result
Exemplo n.º 22
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)))
Exemplo n.º 23
0
def printGraph(datas, phi, name='', fit=False):
    """make graph with measured taus for one specific angle phi

    Arguments:
    datas -- datalists (sorted by series in dictonary)
    phi   -- angle
    name  -- additional name for file name
    fit   -- if true fit data with linear model (default=False)
    """
    # setup canvas and legend
    c = TCanvas('c_%d' % phi, '', 1280, 720)
    if fit:
        l = TLegend(0.6, 0.15, 0.85, 0.5)
    else:
        l = TLegend(0.65, 0.15, 0.85, 0.35)
    l.SetTextSize(0.03)
    # make and draw graphs, graphs are organized by TMultiGraph
    graphs = TMultiGraph()
    for s, datalist in datas.iteritems():
        data = DataErrors.fromLists(*zip(*datalist))
        g = data.makeGraph('g_%d_%d' % (phi, s))
        g.SetMarkerColor(seriescolors[s])
        g.SetLineColor(seriescolors[s])
        l.AddEntry(g, serieslabels[s], 'p')
        graphs.Add(g)
    graphs.Draw('AP')
    gPad.Update()
    setMultiGraphTitle(graphs, 'Druck p / mPa', '#tau / ns')

    # fit data with linear fit
    if fit:
        fit = Fitter('fit_%d' % phi, 'pol1(0)')
        fit.function.SetNpx(1000)
        fit.setParam(0, '#tau_{0}', 119)
        fit.setParam(1, 'm', 0.5)
        fit.fit(graphs, 0, 225, 'M')
        fit.saveData('../calc/fit_tau_%02d%s.txt' % (phi, name), 'w')
        l.AddEntry(fit.function, 'Fit mit #tau(p) = #tau_{0} + m * p', 'l')
        fit.addParamsToLegend(l, [('%.1f', '%.1f'), ('%.2f', '%.2f')], chisquareformat='%.2f',
                              advancedchi=True, units=['ns', 'ns / mPa'])

    # draw legend and print canvas to file
    l.Draw()
    c.Update()
    c.Print('../img/taus_%02d%s.pdf' % (phi, name), 'pdf')

    # return required fit parameter
    if fit:
        return fit.params[0]['value'], fit.params[0]['error']
Exemplo n.º 24
0
def evalDiode():
    datalist = loadCSVToList('../data/part1/Kennlinie.txt')
    data = DataErrors()
    U0 = datalist[0][1]
    sU0 = 0.05 + 0.01 * U0
    for I, u in datalist:
        U = u - U0
        su = 5 + 0.01 * u
        sU = sqrt(su ** 2 + sU0 ** 2)
        data.addPoint(I, U, 0.1, sU)
    xmin, xmax = 53, 71.5

    c = TCanvas('c_diode', '', 1280, 720)
    g = data.makeGraph('g_diode', "Laserstrom I_{L} / mA", "Photodiodenspannung U_{ph} / mV")
    g.GetXaxis().SetRangeUser(-5, 90)
    g.SetMinimum(-50)
    g.SetMaximum(1400)
    g.Draw('APX')

    # y=0 line
    line = TLine(-5, 0, 90, 0)
    line.SetLineColor(OPData.CH2ECOLOR)
    line.Draw()

    data.filterX(xmin, xmax)
    g2 = data.makeGraph('g_diode_2', "Laserstrom I_{L} / mA", "Photodiodenspannung U_{ph} / mV")
    g2.SetMarkerColor(OPData.CH1COLOR)
    g2.SetLineColor(OPData.CH1COLOR)

    fit = Fitter('fit_diode', '[0] * (x-[1])')
    fit.function.SetNpx(1000)
    fit.setParam(0, 'a', 1)
    fit.setParam(1, 'I_{th}', 50)
    fit.fit(g2, 40, 77)
    fit.saveData('../fit/part1/kennlinie.txt')

    l = TLegend(0.15, 0.55, 0.4, 0.85)
    l.SetTextSize(0.03)
    l.AddEntry(g, 'Laserdiodenkennlinie', 'p')
    l.AddEntry(g2, 'Ausschnitt zum Fitten', 'p')
    l.AddEntry(fit.function, 'Fit mit U_{ph} = a (I_{ L} - I_{ th} )', 'l')
    fit.addParamsToLegend(l, (('%.1f', '%.1f'), ('%.2f', '%.2f')), chisquareformat='%.2f', units=['mV/mA', 'mA'])
    l.Draw()

    g.Draw('P')
    g2.Draw('P')

    c.Update()
    c.Print('../img/part1/diodenkennlinie.pdf', 'pdf')
Exemplo n.º 25
0
def makeGraph(channel):
    data = MyonData.fromPath('../data/energieaufloesung_%s.TKA' % channel)
    data.convertToCountrate()

    c = TCanvas('c_%s' % channel, '', 1280, 720)
    g = data.makeGraph('g%s' % channel, 'channel c', 'countrate n / (1/s)')
    prepareGraph(g)
    g.GetXaxis().SetRangeUser(0, 700)
    g.Draw('APX')

    ch = int(channel)
    if ch < 100:
        xmin, xmax = ch - 25, ch + 25
    elif ch < 120:
        xmin, xmax = ch - 50, ch + 40
    elif ch < 200:
        xmin, xmax = ch - 50, ch + 50
    elif ch < 600:
        xmin, xmax = 0, 700
    else:
        xmin, xmax = 0, ch + 45

    fit = Fitter('fit_%s' % channel, '[0] + gaus(1)')
    fit.function.SetNpx(1000)
    fit.setParam(0, 'b', 0)  # offset
    fit.setParam(1, 'A', data.getMaxY())  # amplitude
    fit.setParam(2, 'x', ch)  # channel
    fit.setParam(3, '#sigma', 50)  # sigma
    #fit.setParamLimits(0, 0, 1000)
    fit.fit(g, xmin, xmax)
    fit.saveData('../fit/energieaufloesung_%s.txt' % channel)

    if ch > 350:
        l = TLegend(0.15, 0.5, 0.45, 0.85)
    else:
        l = TLegend(0.55, 0.5, 0.85, 0.85)
    l.SetTextSize(0.03)
    l.AddEntry(g, "measurement", 'p')
    l.AddEntry(fit.function, "fit with n(c) =", 'l')
    l.AddEntry(None, "b + A gaus(c; x, #sigma)", '')
    fit.addParamsToLegend(l, (('%.4f', '%.4f'), ('%.2f', '%.2f'), ('%.2f', '%.2f'), ('%.2f', '%.2f'),),
                          chisquareformat='%.2f', units=['1/s', '1/s', '', ''], lang='en')
    l.Draw()

    g.Draw('P')
    c.Update()
    c.Print('../img/energieaufloesung_%s.pdf' % channel, 'pdf')
    return (fit.params[2]['value'], fit.params[2]['error'], abs(fit.params[3]['value']), fit.params[3]['error'])  # abs(sigma)
Exemplo n.º 26
0
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'])
Exemplo n.º 27
0
def makeFranzenFit(n, plotParams):
    data = OPData.fromPath(DIR + '%02d.tab' % n, 1)
    xmin, xmax = plotParams[:2]
    fitparams = plotParams[2:]

    c = TCanvas('c_%d' % n, '', 1280, 720)
    g = data.makeGraph('g_%d' % n, 'Zeit t / s', 'U_{ph} / V')
    prepareGraph(g, 2)
    g.GetXaxis().SetRangeUser(xmin, xmax)
    g.Draw('APX')

    fit = Fitter('fit%d' % n, franzenFunc, (xmin, xmax, 6))
    fit.function.SetNpx(1000)
    paramnames = ["A", "u", "#mu", "#sigma", "B", "#lambda"]
    for i in range(6):
        fit.setParam(i, paramnames[i], fitparams[3 * i])
        fit.setParamLimits(i, fitparams[3 * i + 1], fitparams[3 * i + 2])
        print(fitparams[3 * i], fitparams[3 * i + 1], fitparams[3 * i + 2])
    fit.fit(g, xmin, xmax)
    fit.saveData('../fit/part6/%02d.txt' % n)

    fermi = TF1('func', fermiFunc, xmin, xmax, 5)
    fermi.SetNpx(1000)
    fermi.SetLineColor(getRootColor(0))
    fermi.SetLineWidth(1)
    for i in range(5):
        fermi.SetParameter(i, fit.params[i]['value'])
    fermi.Draw('SAME')

    g.Draw('P')

    l = TLegend(0.4, 0.15, 0.85, 0.65)
    l.SetTextSize(0.03)
    l.AddEntry(g, "Spannung Photodiode U_{ph}", 'l')
    l.AddEntry(fit.function, 'Fit mit U_{ph}(t) = U_{F}(t; A, u, #mu, #sigma) + U_{E}(t; #mu, B, #lambda)', 'l')
    l.AddEntry(fermi, 'Fermi-Verteilung', 'l')
    fit.addParamsToLegend(l, [('%.4f', '%.4f'), ('%.4f', '%.4f'), ('%.5f', '%.5f'), ('%.2f', '%.2f'), ('%.4f', '%.4f'), ('%.3f', '%.3f')],
                          chisquareformat='%.2f', units=["V", "V", "ms", "#mus", "V", "1/ms"])
    l.Draw()

    c.Update()
    c.Print('../img/part6/%02d.pdf' % n, 'pdf')

    result = []
    exportvals = [2, 3, 4]  # mu, sigma, B
    for e in exportvals:
        result.append((fit.params[e]['value'], fit.params[e]['error']))
    return result
Exemplo n.º 28
0
def evalFlythroughSpectrum(name, xmin, xmax):
    data = MyonData.fromPath('../data/%s.TKA' % name)
    data.convertToCountrate()

    c = TCanvas('c_%s' % name, '', 1280, 720)
    g = data.makeGraph('g_%s' % name, 'channel c', 'countrate n / (1/s)')
    prepareGraph(g)
    g.GetXaxis().SetRangeUser(0, 700)
    g.GetYaxis().SetTitleOffset(1.2)
    g.Draw('APX')  # don't draw error bars => fit function in front

    maxY = data.getByY(data.getMaxY())[0]
    area = g.Integral(xmin, xmax)

    print('start fitting %s' % name)
    t1 = datetime.datetime.now()
    fit = Fitter('fit_%s' % name, langaufun, (xmin, xmax, 4))
    fit.setParam(0, 's', 1)
    fit.setParam(1, 'm', maxY)
    fit.setParam(2, 'A', area)
    fit.setParam(3, '#sigma', 30)
    fit.fit(g, xmin, xmax, 'RBO')
    t2 = datetime.datetime.now()
    delta = t2 - t1
    print('fitted in %d s' % int(delta.total_seconds()))
    fit.saveData('../fit/%s.txt' % name)

    if not name == "energiekalibration_100":
        l = TLegend(0.5, 0.55, 0.85, 0.85)
    else:
        l = TLegend(0.15, 0.55, 0.5, 0.85)
    l.SetTextSize(0.03)
    l.AddEntry(g, 'flight through with %s%% energy' % name.split('_')[1], 'p')
    l.AddEntry(fit.function, 'fit with n(c) =', 'l')
    l.AddEntry(None, '(landau(m, s) * gaus(0, #sigma))(c)', '')
    fit.addParamsToLegend(l, (('%.2f', '%.2f'), ('%.2f', '%.2f'),
                              ('%.3f', '%.3f'), ('%.2f', '%.2f')),
                          chisquareformat='%.2f',
                          lang='en')
    l.Draw()

    g.Draw('P')  # redraw points with error bars
    c.Update()
    c.Print('../img/%s.pdf' % name, 'pdf')

    return ((fit.params[1]['value'], fit.params[1]['error']),
            (fit.params[3]['value'], fit.params[3]['error']))
Exemplo n.º 29
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')
Exemplo n.º 30
0
def evalFlythroughSpectrum(name, xmin, xmax):
    data = MyonData.fromPath('../data/%s.TKA' % name)
    data.convertToCountrate()

    c = TCanvas('c_%s' % name, '', 1280, 720)
    g = data.makeGraph('g_%s' % name, 'channel c', 'countrate n / (1/s)')
    prepareGraph(g)
    g.GetXaxis().SetRangeUser(0, 700)
    g.GetYaxis().SetTitleOffset(1.2)
    g.Draw('APX')  # don't draw error bars => fit function in front

    maxY = data.getByY(data.getMaxY())[0]
    area = g.Integral(xmin, xmax)

    print('start fitting %s' % name)
    t1 = datetime.datetime.now()
    fit = Fitter('fit_%s' % name, langaufun, (xmin, xmax, 4))
    fit.setParam(0, 's', 1)
    fit.setParam(1, 'm', maxY)
    fit.setParam(2, 'A', area)
    fit.setParam(3, '#sigma', 30)
    fit.fit(g, xmin, xmax, 'RBO')
    t2 = datetime.datetime.now()
    delta = t2 - t1
    print('fitted in %d s' % int(delta.total_seconds()))
    fit.saveData('../fit/%s.txt' % name)
    
    if not name == "energiekalibration_100":
        l = TLegend(0.5, 0.55, 0.85, 0.85)
    else:
        l = TLegend(0.15, 0.55, 0.5, 0.85)
    l.SetTextSize(0.03)
    l.AddEntry(g, 'flight through with %s%% energy' % name.split('_')[1], 'p')
    l.AddEntry(fit.function, 'fit with n(c) =', 'l')
    l.AddEntry(None, '(landau(m, s) * gaus(0, #sigma))(c)', '')
    fit.addParamsToLegend(l, (('%.2f', '%.2f'), ('%.2f', '%.2f'), ('%.3f', '%.3f'), ('%.2f', '%.2f')), chisquareformat='%.2f', lang='en')
    l.Draw()

    g.Draw('P')  # redraw points with error bars
    c.Update()
    c.Print('../img/%s.pdf' % name, 'pdf')

    return ((fit.params[1]['value'], fit.params[1]['error']), (fit.params[3]['value'], fit.params[3]['error']))
Exemplo n.º 31
0
def fitXc(volts, times, d, sd):
    listx, listsx = zip(*times)
    listy = []
    listsy = []
    for u, su in volts:  # convert u to 1/u
        y = 1. / u
        sy = su / (u ** 2)
        listy.append(y)
        listsy.append(sy)
    data = DataErrors.fromLists(listx, listy, listsx, listsy)

    c = TCanvas('cXc', '', 1280, 720)
    g = data.makeGraph('xc', 'Zeit t / s', 'reziproke Treibspannung 1/U_{T} / (1/V)')
    g.GetYaxis().SetTitleOffset(1.25)
    g.Draw('AP')

    fit = Fitter('fitXc', '1/[0] + [1]*x')
    fit.setParam(0, 'U_{0}', -150)
    fit.setParam(1, 'm', 3e-3)
    fit.fit(g, 8e-6, 18e-6)
    fit.saveData('../calc/part2/volt_fit_xc.txt')

    l = TLegend(0.15, 0.55, 0.4, 0.85)
    l.SetTextSize(0.03)
    l.AddEntry('xc', 'Messung', 'p')
    l.AddEntry(fit.function, 'Fit mit #frac{1}{U_{T}} = m*t + #frac{1}{U_{0}}', 'l')
    l.AddEntry(0, '', '')
    fit.addParamsToLegend(l, [('%.0f', '%.0f'), ('%.0f', '%.0f')], chisquareformat='%.2f')
    l.Draw()

    if PRINTGRAPHS or True:
        c.Update()
        c.Print('../img/part2/volt_fitXc.pdf', 'pdf')

    # calculate mu
    m, sm = fit.params[1]['value'], fit.params[1]['error']
    l = 30
    mu = m * l * d / 100  # /100 -> from mm in cm
    smu = mu * np.sqrt((sm / m) ** 2 + (sd / d) ** 2)
    with TxtFile('../calc/part2/volt_mu.txt', 'w') as f:
        f.writeline('\t', str(mu), str(smu))
        
    return mu, smu
Exemplo n.º 32
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)))
Exemplo n.º 33
0
def makeCSGraphUnderground(ctype, startGammaEE=None):
    data = loadCrossSection(ctype)
    c = TCanvas('c_%s' % ctype, '', 1280, 720)
    g = data.makeGraph('g_%s' % ctype, '#sqrt{s} / GeV', '#sigma / nb')
    g.Draw('AP')
    
    if not startGammaEE:
        fit = Fitter('fit_%s' % ctype, '[0] + [1] * x + 12*pi / [2]^2 * x^2 * [3]^2 / ((x^2-[2]^2)^2 + x^4 * [4]^2 / [2]^2) * 0.3894e6')
        fitfuncstring = "a + b#sqrt{s} + #frac{12#pi}{M_{Z}^{2}} #frac{s #Gamma_{%s}^{2}}{(s-M_{Z}^{2})^{2} + s^{2} #Gamma_{Z}^{2} / M_{Z}^{2}}" % ctype[0]
    else:
        fit = Fitter('fit_%s' % ctype, '[0] + [1] * x + 12*pi / [2]^2 * x^2 * [3] * [5] / ((x^2-[2]^2)^2 + x^4 * [4]^2 / [2]^2) * 0.3894e6')
        fitfuncstring = "a + b#sqrt{s} + #frac{12#pi}{M_{Z}^{2}} #frac{s #Gamma_{e} #Gamma_{%s}}{(s-M_{Z}^{2})^{2} + s^{2} #Gamma_{Z}^{2} / M_{Z}^{2}}" % ctype[0]
    fit.setParam(0, 'a', 0)
    fit.setParam(1, 'b', 0)
    fit.setParam(2, 'M_{Z}', 91.2)
    fit.setParam(4, '#Gamma_{Z}', 2.5)
    if not startGammaEE:
        fit.setParam(3, '#Gamma_{%s}' % ctype[0], 0.08)
    else:
        fit.setParam(3, '#Gamma_{e}', startGammaEE, True)
        fit.setParam(5, '#Gamma_{%s}' % ctype[0], 2)
    fit.fit(g, 88, 94)
    fit.saveData('../fit/crosssections_%s.txt' % ctype)
    
    l = TLegend(0.625, 0.575, 0.98, 0.98)
    l.SetTextSize(0.03)
    l.AddEntry(g, "%s Wirkungsquerschnitte" % ctype, 'p')
    l.AddEntry(fit.function, "Fit mit #sigma(s) = ", 'l')
    l.AddEntry(None, "", '')
    l.AddEntry(None, fitfuncstring, '')
    l.AddEntry(None, "", '')
    if not startGammaEE:
        fit.addParamsToLegend(l, [('%.3f', '%.3f'), ('%.3f', '%.3f'), ('%.3f', '%.3f'), ('%.3f', '%.3f'), ('%.3f', '%.3f')], chisquareformat='%f', units=['nb', 'nb/GeV', 'GeV / c^{2}', 'GeV', 'GeV'])
    else:
        fit.addParamsToLegend(l, [('%.3f', '%.3f'), ('%.3f', '%.3f'), ('%.3f', '%.3f'), '%.4f', ('%.3f', '%.3f'), ('%.3f', '%.3f')], chisquareformat='%f', units=['nb', 'nb/GeV', 'GeV/c^{2}', 'GeV', 'GeV', 'GeV'])
    l.Draw()

    c.Update()
    c.Print('../img/crosssections_%s.pdf' % ctype, 'pdf')
    
    return fit.params[3]['value']
Exemplo n.º 34
0
def stFit(data, energie, xmin, xmax, binsize):
    datacut = data.cut(CUTS[0][1])  # ee-cut

    c = TCanvas('c', '', 1280, 720)
    hist = datacut.makeHistogramm('hist_%f' % energie, 'cos_thet', binsize, -1, 1)
    setHistTitle(hist, "cos #Theta", "Anzahl der Ereignisse N")
    hist.Draw()

    fit = Fitter('f', '[0] * (1 + x^2) + [1] * (1-x)^(-2)')
    fit.setParam(0, 's', 100)
    fit.setParam(1, 't', 10)
    fit.fit(hist, xmin, xmax)
    fit.saveData('../fit/s_t_fit_%.2f.txt' % energie)

    sfunc = TF1('sfunc', '[0]*(1+x^2)', xmin, xmax)
    sfunc.SetParameter(0, fit.params[0]['value'])
    sfunc.SetLineWidth(1)
    sfunc.SetLineColor(3)
    sfunc.Draw('same')

    tfunc = TF1('tfunc', '[0]*(1-x)^(-2)', xmin, xmax)
    tfunc.SetParameter(0, fit.params[1]['value'])
    tfunc.SetLineWidth(1)
    tfunc.SetLineColor(4)
    tfunc.Draw('same')

    l = TLegend(0.15, 0.5, 0.55, 0.85)
    l.SetTextSize(0.03)
    l.AddEntry(hist, "Echte Daten (#sqrt{s} = %.2f GeV) mit ee-cut" % energie, 'l')
    l.AddEntry(fit.function, 'Fit mit N(#Theta) = s (1 + cos^{2}#Theta) + t (1 - cos#Theta)^{-2}', 'l')
    fit.addParamsToLegend(l, [('%.2f', '%.2f'), ('%.2f', '%.2f')], chisquareformat='%.2f')
    l.AddEntry(sfunc, 's (1 + cos^{2}#Theta)', 'l')
    l.AddEntry(tfunc, 't (1 - cos#Theta)^{-2}', 'l')
    l.Draw()

    c.Update()
    s = '%.2f' % energie
    if not DEBUG:
        c.Print('../img/s_t_fit_%s.pdf' % s.replace('.', '-'), 'pdf')

    return ((fit.params[0]["value"], fit.params[0]["error"]), (fit.params[1]["value"], fit.params[1]["error"]))
Exemplo n.º 35
0
def makeFermiKuriePlot():
    data = MyonData.fromPath('../data/betaspektrum.TKA')
    data.convertToCountrate()
    data.convertChannelToEnergy()
    data = calcFermiKuriePlot(data)

    c = TCanvas('c', '', 1280, 720)
    g = data.makeGraph('g', 'energy E / MeV', '#sqrt{n/E^{2}}')
    prepareGraph(g)
    g.GetXaxis().SetRangeUser(0, 150)
    g.SetMaximum(0.004)
    g.GetYaxis().SetTitleOffset(1.3)
    g.Draw('APX')
    g.Draw('P')
    c.Update()
    c.Print('../img/betaspectrum_FermiKurie.pdf', 'pdf')

    g.GetXaxis().SetRangeUser(0, 80)
    g.SetMaximum(3e-3)

    fit = Fitter('fit', '[0]*(x-[1])*1e-6')
    fit.setParam(0, 'a', -0.3)
    fit.setParam(1, 'b', 55)
    fit.fit(g, 23, 45)
    fit.saveData('../fit/FermiKurie.txt')

    l = TLegend(0.65, 0.6, 0.85, 0.85)
    l.SetTextSize(0.03)
    l.AddEntry(g, 'Fermi-Kurie plot', 'p')
    l.AddEntry(fit.function, 'fit with a(E-b)', 'l')
    fit.addParamsToLegend(l, (('%.2f', '%.2f'), ('%.2f', '%.2f')),
                          chisquareformat='%.2f',
                          units=["10^{-6}", ""],
                          lang='en')
    l.Draw()

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

    return fit.params[1]["value"], fit.params[1]["error"]
Exemplo n.º 36
0
def makeEnergyGauge(detector, peaks, litvals):
    x, sx = zip(*peaks)
    data = DataErrors.fromLists(x, litvals, sx, [0] * len(x))
    c = TCanvas('c_eg_%s' % detector, '', 1280, 720)
    g = data.makeGraph('g_eg_%s' % detector, 'Kanal k', 'Energie E / eV')
    g.Draw('AP')

    fit = Fitter('f_eg_%s' % detector, 'pol1(0)')
    fit.setParam(0, 'a', 0)
    fit.setParam(1, 'b')
    fit.fit(g, x[0] - 20, x[-1] + 20)
    fit.saveData('../calc/part3/energygauge_%s.txt' % detector, 'w')

    l = TLegend(0.15, 0.6, 0.4, 0.85)
    l.AddEntry(g, 'Messwerte', 'p')
    l.AddEntry(fit.function, 'Fit mit E(k) = a + b*k', 'l')
    fit.addParamsToLegend(l, [('%.2f', '%.2f'), ('%.4f', '%.4f')], chisquareformat='%.2f')
    l.Draw()

    c.Update()
    if PRINTGRAPHS:
        c.Print('../img/part3/energygauge_%s.pdf' % detector, 'pdf')
Exemplo n.º 37
0
def evalDistance(n, params):
    xmin, xmax = params[1:]
    deltax = abs(xmax - xmin) * 0.1

    data = P2SemiCon.fromPath('../data/part2/length/ALL%04.d/F%04dCH1.CSV' % (n, n))
    g = data.makeGraph('g%d' % n, 'Zeit t / s', 'Spannung U / V')
    c = TCanvas('c%d' % n, '', 1280, 720)
    g.SetMarkerStyle(1)
    g.GetXaxis().SetRangeUser(xmin - deltax, xmax + deltax)
    closex = min(getByCloseX(data, xmin)[1], getByCloseX(data, xmax)[1])
    if closex > 0:
        ymin = closex * 0.95
    else:
        ymin = closex * 1.1
    g.SetMinimum(ymin)
    g.GetYaxis().SetTitleOffset(1.2)
    g.Draw('APX')

    fit = Fitter('f', 'pol1(0) + 1/(sqrt(2*pi*[4]^2))*gaus(2)')
    fit.function.SetNpx(1000)
    paramname = ['a', 'b', 'A', 't_{c}', '#sigma']
    for i, param in enumerate(params[0]):
        fit.setParam(i, paramname[i], param)
    fit.fit(g, xmin, xmax)
    fit.saveData('../calc/part2/dist%02d.txt' % n, 'w')

    l = TLegend(0.625, 0.6, 0.99, 0.99)
    l.SetTextSize(0.03)
    l.AddEntry(g, 'Messung', 'p')
    l.AddEntry(fit.function, 'Fit mit U(t) = a + b*t + #frac{A}{#sqrt{2#pi*#sigma^{2}}} e^{- #frac{1}{2} (#frac{t - t_{c}}{#sigma})^{2}}', 'l')
    l.AddEntry(0, '', '')
    fit.addParamsToLegend(l, [('%.2e', '%.2e')] * len(params[0]), chisquareformat='%.2f')
    l.Draw()

    if PRINTGRAPHS:
        c.Update()
        c.Print('../img/part2/dist%02d.pdf' % n, 'pdf')

    return data, fit.params, fit.getCorrMatrix(), params[1], params[2]
Exemplo n.º 38
0
def main():
    times = [2.4, 4.5, 6.25, 8.6]
    times_error = [0.02] * len(times)
    channels = [113, 223, 315.5, 441]
    channels_error = [0.5] * len(times)
    
    with TxtFile('../src/tab_timecalibration.tex', 'w') as f:
        f.write2DArrayToLatexTable(list(zip(*[times, times_error, channels, channels_error])),
                                   ["$t$ / \\textmu s", "$s_t$ / \\textmu s", "$c$", "$s_c$"], 
                                   ["%.2f", "%.2f", "%.1f", "%.1f"], 
                                   "Measured times and channels with errors for the time calibration.", "tab:tcal")

    data = DataErrors.fromLists(channels, times, channels_error, times_error)
    c = TCanvas('c', '', 1280, 720)
    g = data.makeGraph('g', 'channel c', 'time t / #mus')
    g.Draw('APX')

    fit = Fitter('fit', 'pol1(0)')
    fit.setParam(0, 'a', 0)
    fit.setParam(1, 'b', 50)
    fit.fit(g, 100, 450)
    fit.saveData('../fit/timeCalibration.txt')

    l = TLegend(0.15, 0.6, 0.5, 0.85)
    l.SetTextSize(0.03)
    l.AddEntry(g, 'measurement', 'p')
    l.AddEntry(fit.function, 'fit with t(c) = a + b * c', 'l')
    fit.addParamsToLegend(l, (('%.2f', '%.2f'), ('%.5f', '%.5f')), chisquareformat='%.2f', units=('#mus', '#mus/channel'), lang='en')
    l.Draw()

    g.Draw('P')
    c.Update()
    c.Print('../img/timeCalibration.pdf', 'pdf')

    with TxtFile('../calc/timeCalibration.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)))
Exemplo n.º 39
0
def fitXc(dists, times):
    listx, listsx = zip(*times)
    listy, listsy = zip(*dists)
    data = DataErrors.fromLists(listx, listy, listsx, listsy)

    c = TCanvas('cXc', '', 1280, 720)
    g = data.makeGraph('xc', 'Zeit t / s', 'x_{c} / mm')
    g.SetLineWidth(0)
    g.Draw('AP')

    fit = Fitter('fitXc', 'pol1(0)')
    fit.setParam(0, 'x_{0}', 1)
    fit.setParam(1, 'm', 0.5e-6)
    fit.fit(g, 1e-6, 23e-6)
    fit.saveData('../calc/part2/dist_fit_xc.txt')

    l = TLegend(0.15, 0.625, 0.4, 0.85)
    l.SetTextSize(0.03)
    l.AddEntry('xc', 'Messung', 'p')
    l.AddEntry(fit.function, 'Fit mit x_{c}(t) = x_{0}+m*t', 'l')
    l.AddEntry(0, '', '')
    fit.addParamsToLegend(l, [('%.3f', '%.3f'), ('%.2e', '%.2e')], chisquareformat='%.2f')
    l.Draw()

    if PRINTGRAPHS or True:
        c.Update()
        c.Print('../img/part2/dist_fitXc.pdf', 'pdf')

    # calculate mu
    m, sm = fit.params[1]['value'], fit.params[1]['error']
    U, sU = 48.8, P2SemiCon.UERROR
    l = 30
    mu = m * l / U / 100  # /100 -> from mm in cm
    smu = mu * np.sqrt((sm / m) ** 2 + (sU / U) ** 2)
    with TxtFile('../calc/part2/dist_mu.txt', 'w') as f:
        f.writeline('\t', str(mu), str(smu))

    return mu, smu
Exemplo n.º 40
0
def evalAngleDependency():
    datalist = loadCSVToList(DIR + 'Winkelabh.txt')
    data = DataErrors()
    strel = 0.01
    sI = 1
    for t2, t1, n, phi in datalist:
        f, sf = calcPrecissionFreq(t2, t1, n)
        data.addPoint(phi, f, 0.5, sf)

    c = TCanvas('c_phi', '', 1280, 720)
    g = data.makeGraph('g_phi', 'Rotation des Strahlengangs #varphi / #circ',
                       'Praezessionsfrequenz f / kHz')
    g.GetXaxis().SetRangeUser(-15, 15)
    g.SetMinimum(0)
    g.Draw('APX')

    fit = Fitter('fit_phi', '[0] * abs(sin((x-[1])*pi/180))')
    fit.function.SetNpx(1000)
    fit.setParam(0, '#beta', 1)
    fit.setParam(1, '#phi_{0}', 0)
    fit.fit(g, -15, 15)
    fit.saveData('../fit/part4/winkel.txt')

    g.Draw('P')

    l = TLegend(0.7, 0.15, 0.95, 0.5)
    l.SetTextSize(0.03)
    l.AddEntry(g, 'Praezessionsfrequenz', 'p')
    l.AddEntry(fit.function, 'Fit mit f = #beta |sin(#varphi + #varphi_{0})|',
               'l')
    fit.addParamsToLegend(l, (('%.1f', '%.1f'), ('%.2f', '%.2f')),
                          chisquareformat='%.2f',
                          units=['kHz/#muT', '#circ'])
    l.Draw()

    c.Update()
    c.Print('../img/part4/winkel.pdf', 'pdf')
Exemplo n.º 41
0
def makeFBAFit(energy, data, binsize):
    cutdata = data.cut(CUTS[1][1])
    c = TCanvas('c_%f' % energy, '', 1280, 720)
    hist = cutdata.makeHistogramm('hist_%f' % energy, 'cos_thet', binsize, -1,
                                  1)
    hist.Draw()

    if energy in [90.22720, 91.23223, 91.97109]:
        #fit = Fitter('fit_%d' % round(energy*100), "pi * (1/128.9)^2 / (2 * %f) * ([0]*(1+x^2) + 2 * [1] * x)" % (energy ** 2))
        fit = Fitter('fit_%d' % round(energy * 100),
                     "[0]*(1+x^2) + 2 * [1] * x")
        fit.setParam(0, 'F_{1}', 1e10)
        fit.setParam(1, 'F_{2}', -4e8)
        fit.fit(hist, -0.9, 0.9, "M")

        l = TLegend(0.65, 0.75, 0.98, 0.98)
        l.SetTextSize(0.03)
        l.AddEntry(hist, 'daten_1 (mit mm-cut)', 'l')
        l.AddEntry(fit.function, 'Fit mit F_{1} (1 + x^{2}) + 2 F_{2} x', 'l')
        fit.addParamsToLegend(l, (('%.3f', '%.3f'), ('%.3f', '%.3f')),
                              chisquareformat='%.2f')
        l.Draw()
        F1, sF1 = fit.params[0]["value"], fit.params[0]["error"]
        F2, sF2 = fit.params[1]["value"], fit.params[1]["error"]
        A = 3 / 4 * F2 / F1
        sA = abs(A) * sqrt((sF1 / F1)**2 + (sF2 / F2)**2)
        sinW = 1 / 4 * (1 - sqrt(abs(A) / 3))
        ssinW = sA / (8 * sqrt(3 * abs(A)))
        res = A, sA, sinW, ssinW
    else:
        res = None

    c.Update()
    s = '%.5f' % energy
    c.Print("../img/FBA_%.5f.pdf" % s.replace('.', '-'), 'pdf')
    return res
Exemplo n.º 42
0
def evalSpinPrecission(name):
    datalist = loadCSVToList(DIR + name + '.txt')
    data = DataErrors()
    sI = 1
    for t2, t1, n, I in datalist:
        f, sf = calcPrecissionFreq(t2, t1, n)
        B, sB = inductorIToB(4, I * 1e-3, sI * 1e-3)
        data.addPoint(B * 1e6, f, sB * 1e6, sf)

    if len(name) == 4:
        xmin, xmax = 0, 50
    else:
        xmin, xmax = 0, 80

    c = TCanvas('c_%s' % name, '', 1280, 720)
    g = data.makeGraph('g_%s' % name,
                       'Zusaetzliches Vertikalfeld B_{S, v} / #muT',
                       'Praezessionsfrequenz f / kHz')
    g.GetXaxis().SetRangeUser(xmin, xmax)
    g.Draw('APX')

    fit1 = Fitter('fit1_%s' % name, '[0] * abs([1]-x)')
    fit1.function.SetNpx(1000)
    fit1.setParam(0, '#alpha', 1)
    fit1.setParam(1, 'B_{E, v}', 40)
    fit1.fit(g, xmin, xmax)
    fit1.saveData('../fit/part4/fit1_%s' % name)

    fit2 = Fitter('fit1_%s' % name, '[0] * (abs([1]-x) + [2])')
    fit2.function.SetNpx(1000)
    fit2.function.SetLineColor(3)
    fit2.setParam(0, '#alpha', 1)
    fit2.setParam(1, 'B_{E, v}', 40)
    fit2.setParam(2, 'B_{E,h,s}', 20)
    fit2.setParamLimits(2, 0, 100)
    fit2.fit(g, xmin, xmax, '+')
    fit2.saveData('../fit/part4/fit2_%s' % name)

    g.Draw('P')

    if len(name) == 4:
        l = TLegend(0.6, 0.4, 0.975, 0.95)
    else:
        l = TLegend(0.325, 0.475, 0.725, 0.99)
    l.SetTextSize(0.03)
    l.AddEntry(g, 'Praezessionsfrequenzen', 'p')
    l.AddEntry(fit1.function,
               'Fit mit f_{1}(B_{S, v}) = #alpha |B_{E, v} - B_{S, v}|', 'l')
    fit1.addParamsToLegend(l, (('%.2f', '%.2f'), ('%.2f', '%.2f')),
                           chisquareformat='%.2f',
                           units=['kHz/#muT', '#muT'])
    l.AddEntry(
        fit2.function,
        'Fit mit f_{2}(B_{S, v}) = #alpha (|B_{E, v} - B_{S, v}| + B_{E,h,s})',
        'l')
    fit2.addParamsToLegend(l, (('%.2f', '%.2f'), ('%.2f', '%.2f'),
                               ('%.2f', '%.2f')),
                           chisquareformat='%.2f',
                           units=['kHz/#muT', '#muT', '#muT'])
    l.Draw()

    c.Update()
    c.Print('../img/part4/%s.pdf' % name, 'pdf')
Exemplo n.º 43
0
def makeCSGraph(ctype, startGammaEE=None):
    data = loadCrossSection(ctype)
    c = TCanvas('c_%s' % ctype, '', 1280, 720)
    g = data.makeGraph('g_%s' % ctype, '#sqrt{s} / GeV', '#sigma / nb')
    g.Draw('AP')

    if not startGammaEE:
        fit = Fitter(
            'fit_%s' % ctype,
            '(12*pi / [0]^2) * (x^2 * [1]^2) / ((x^2-[0]^2)^2 + x^4 * [2]^2 / [0]^2) * 0.3894*10^6'
        )  #  GeV^-2 = 0.3894 mb
        fitfuncstring = "#frac{12#pi}{M_{Z}^{2}} #frac{s #Gamma_{%s}^{2}}{(s-M_{Z}^{2})^{2} + s^{2} #Gamma_{Z}^{2} / M_{Z}^{2}}" % ctype[
            0]
    else:
        fit = Fitter(
            'fit_%s' % ctype,
            '(12*pi / [0]^2) * (x^2 * [1] * [2]) / ((x^2-[0]^2)^2 + x^4 * [3]^2 / [0]^2) * 0.3894*10^6'
        )
        fitfuncstring = "#frac{12#pi}{M_{Z}^{2}} #frac{s #Gamma_{m} #Gamma_{%s}}{(s-M_{Z}^{2})^{2} + s^{2} #Gamma_{Z}^{2} / M_{Z}^{2}}" % ctype[
            0]
    fit.setParam(0, 'M_{Z}', 91.2)
    fit.setParamLimits(0, 0, 1000)
    if not startGammaEE:
        fit.setParam(1, '#Gamma_{%s}' % ctype[0], 0.08)
        fit.setParamLimits(1, 0, 1000)
        fit.setParam(2, '#Gamma_{Z}', 2.5)
        fit.setParamLimits(2, 0, 1000)
    else:
        fit.setParam(1, '#Gamma_{m}', startGammaEE, True)
        fit.setParam(2, '#Gamma_{%s}' % ctype[0], 1.5)
        fit.setParam(3, '#Gamma_{Z}', 2.5)
        fit.setParamLimits(2, 0, 1000)
    fit.fit(g, 88, 94, '')
    fit.saveData('../fit/crosssections_%s.txt' % ctype)

    l = TLegend(0.625, 0.6, 0.98, 0.975)
    l.SetTextSize(0.03)
    l.AddEntry(g, "%s Wirkungsquerschnitte" % ctype, 'p')
    l.AddEntry(fit.function, "Fit mit #sigma(s) = %s" % fitfuncstring, 'l')
    l.AddEntry(None, "", '')
    if not startGammaEE:
        fit.addParamsToLegend(l, [('%.3f', '%.3f'), ('%.4f', '%.4f'),
                                  ('%.3f', '%.3f')],
                              chisquareformat='%f',
                              units=['GeV / c^{2}', 'GeV', 'GeV'])
    else:
        fit.addParamsToLegend(l, [('%.3f', '%.3f'), '%.4f', ('%.3f', '%.3f'),
                                  ('%.3f', '%.3f')],
                              chisquareformat='%f',
                              units=['GeV/c^{2}', 'GeV', 'GeV', 'GeV'])
    l.Draw()

    c.Update()
    if not DEBUG:
        c.Print('../img/crosssections_%s.pdf' % ctype, 'pdf')

    if not startGammaEE:
        result = [(fit.params[0]['value'], fit.params[0]['error']),
                  (fit.params[1]['value'], fit.params[1]['error']),
                  (fit.params[2]['value'], fit.params[2]['error'])]
    else:
        result = [(fit.params[0]['value'], fit.params[0]['error']),
                  (fit.params[2]['value'], fit.params[2]['error']),
                  (fit.params[3]['value'], fit.params[3]['error'])]

    return result