Esempio n. 1
0
def tau_from_L_curve(unfoldingObject):
    '''
    Get best tau via l curve method
    Not tested
    '''
    lCurve = TGraph()
    logTauX = TSpline3()
    logTauY = TSpline3()
    iBest = unfoldingObject.ScanLcurve(500, 0., 0., lCurve, logTauX, logTauY)

    # Additional info, plots
    t = Double(0)
    x = Double(0)
    y = Double(0)
    logTauX.GetKnot(iBest, t, x)
    logTauY.GetKnot(iBest, t, y)

    bestLcurve = Graph(1)
    bestLcurve.SetPoint(1, x, y)
    lCurve.SetMarkerColor(600)
    lCurve.SetMarkerSize(1)
    lCurve.SetMarkerStyle(5)

    # lCurve.Draw("AP");
    bestLcurve.markercolor = 'red'
    # bestLcurve.Draw("*");

    return unfoldingObject.GetTau()
Esempio n. 2
0
    def setSpline(self, x, y, title='attenuation'):
        """
	Initialize a spline that is multiplied to the intrinsic spectrum 
	(e.g. for EBL absorption)

	Parameters
	----------
	x:	n-dim np.array with energies in TeV
	y:	n-dim np.array with values of Spline (e.g. EBL attenuation)

	kwargs
	------
	title:	str, title of spline
	"""
        self._spline = TSpline3(title, x, y, x.shape[0])
        self._useSpline = True
        self._xMin = np.min(x)
        self._xMax = np.max(x)
        return
Esempio n. 3
0
    def __init__(self, irf, **kwargs):
        """
	Init the observation simulation class

	Parameters
	----------
	irf: str
	    full path to CTA IRF root file

	kwargs
	------
	threshold:	float
	    energy threshold in TeV (default: 0.1)
	eMin:		float
	    minimum energy in TeV (default: 0.05)
	eMin:		float
	    maximum energy in TeV (default: 30.)
	"""
        kwargs.setdefault('threshold', 0.1)
        #kwargs.setdefault('specBinningOut',100)
        kwargs.setdefault('eMin', 0.05)
        kwargs.setdefault('eMax', 30.)

        self.__dict__.update(kwargs)

        if not exists(irf):
            raise IOError('IRF file not found at {0:s}'.format(irf))

        self._threshold = Double(self.threshold)
        self._irf = irf
        self._irfFile = TFile(irf)
        self._useSpline = False
        self._xMin = 1e16  # dummy, very big
        self._xMax = 1e-16  # dummy, very small
        self._spline = TSpline3()

        return
Esempio n. 4
0
                    y_points[x_points.index(
                        graph.GetX()[i_point])] += graph.GetY()[i_point]
                    samples_counter_points[x_points.index(
                        graph.GetX()[i_point])] += 1
            for i_point in range(len(y_points)):
                y_points[i_point] /= float(samples_counter_points[i_point])
            x_points, y_points = zip(*sorted(zip(x_points, y_points)))
            x_points_array = array("d", x_points)
            y_points_array = array("d", y_points)
            averaged_graphs[graphs_name] = TGraph(len(x_points),
                                                  x_points_array,
                                                  y_points_array)
            averaged_graphs[graphs_name].GetXaxis().SetRangeUser(
                0,
                max(x_points_array) * 1.10)
            # err_function = TF1("err_function","[0]*TMath::Erf((x-[1])/[2])", 0, max(x_points_array))
            # sigmoid_function = TF1("sigmoid_function","([0]/(1+ TMath::Exp(-[1]*(x-[2]))", 0, max(x_points_array))
            sigmoid_function = TF1("sigmoid_function",
                                   "(1/(1+ TMath::Exp(-[0]*(x-[1]))))", 0,
                                   max(x_points_array))
            pol_function = TF1("pol_function", "pol6", 0, max(x_points_array))
            averaged_graphs[graphs_name].Fit(pol_function)
            spline = TSpline3("spline", averaged_graphs[graphs_name])
            averaged_graphs[graphs_name].SetMarkerStyle(kFullDotLarge)
            averaged_graphs[graphs_name].SetMarkerSize(1)
            averaged_graphs[graphs_name].SetTitle(graphs_name)
            averaged_graphs[graphs_name].Draw("AP")
            spline.Draw("LSAME")
            debug_canvas.Update()
            input("PRESS")
Esempio n. 5
0
hPtGenAcc = infileAcc.Get('hPtGenAcc')
hPtGenLimAcc = infileAcc.Get('hPtGenLimAcc')

FONLL = ReadFONLL(inputCfg['filenameFONLL'])
TAMU = ReadTAMU(inputCfg['filenameRaaPredTAMU'])
PHSD = ReadPHSD(inputCfg['filenameRaaPredPHSD'])
Gossiaux = ReadGossiaux(inputCfg['filenameRaaPredGossiaux'])
Catania = ReadCatania(inputCfg['filenameRaaPredCatania'])

outfile = TFile('%s.root' % outFileName, 'recreate')

sTAMU, sGossiaux, sPHSD, sCatania = ({} for iDic in range(4))
for iRaaTAMU in TAMU:
    if iRaaTAMU != 'PtCent':
        sTAMU[iRaaTAMU] = TSpline3('sTAMU%s' % iRaaTAMU,
                                   array.array('d', TAMU['PtCent']),
                                   array.array('d', TAMU[iRaaTAMU]),
                                   len(TAMU['PtCent']))
for iRaaPHSD in PHSD:
    if iRaaPHSD != 'PtCent':
        sPHSD[iRaaPHSD] = TSpline3('sPHSD%s' % iRaaPHSD,
                                   array.array('d', PHSD['PtCent']),
                                   array.array('d', PHSD[iRaaPHSD]),
                                   len(PHSD['PtCent']))
for iRaaGossiaux in Gossiaux:
    if iRaaGossiaux != 'PtCent':
        sGossiaux[iRaaGossiaux] = TSpline3(
            'sGossiaux%s' % iRaaGossiaux, array.array('d', Gossiaux['PtCent']),
            array.array('d', Gossiaux[iRaaGossiaux]), len(Gossiaux['PtCent']))
for iRaaCatania in Catania:
    if iRaaCatania != 'PtCent':
        sCatania[iRaaCatania] = TSpline3(
Esempio n. 6
0
def test_evaluate():
    # create functions and histograms
    f1 = TF1("f1", "x")
    f2 = TF2("f2", "x*y")
    f3 = TF3("f3", "x*y*z")
    h1 = TH1D("h1", "", 10, 0, 1)
    h1.FillRandom("f1")
    h2 = TH2D("h2", "", 10, 0, 1, 10, 0, 1)
    h2.FillRandom("f2")
    h3 = TH3D("h3", "", 10, 0, 1, 10, 0, 1, 10, 0, 1)
    h3.FillRandom("f3")
    # generate random arrays
    arr_1d = np.random.rand(5)
    arr_2d = np.random.rand(5, 2)
    arr_3d = np.random.rand(5, 3)
    arr_4d = np.random.rand(5, 4)
    # evaluate the functions
    assert_array_equal(rnp.evaluate(f1, arr_1d), map(f1.Eval, arr_1d))
    assert_array_equal(rnp.evaluate(f1.GetTitle(), arr_1d),
                       map(f1.Eval, arr_1d))
    assert_array_equal(rnp.evaluate(f2, arr_2d),
                       [f2.Eval(*x) for x in arr_2d])
    assert_array_equal(rnp.evaluate(f2.GetTitle(), arr_2d),
                       [f2.Eval(*x) for x in arr_2d])
    assert_array_equal(rnp.evaluate(f3, arr_3d),
                       [f3.Eval(*x) for x in arr_3d])
    assert_array_equal(rnp.evaluate(f3.GetTitle(), arr_3d),
                       [f3.Eval(*x) for x in arr_3d])
    # 4d formula
    f4 = TFormula('test', 'x*y+z*t')
    assert_array_equal(rnp.evaluate(f4, arr_4d),
                       [f4.Eval(*x) for x in arr_4d])
    # evaluate the histograms
    assert_array_equal(rnp.evaluate(h1, arr_1d),
                       [h1.GetBinContent(h1.FindBin(x)) for x in arr_1d])
    assert_array_equal(rnp.evaluate(h2, arr_2d),
                       [h2.GetBinContent(h2.FindBin(*x)) for x in arr_2d])
    assert_array_equal(rnp.evaluate(h3, arr_3d),
                       [h3.GetBinContent(h3.FindBin(*x)) for x in arr_3d])
    # create a graph
    g = TGraph(2)
    g.SetPoint(0, 0, 1)
    g.SetPoint(1, 1, 2)
    assert_array_equal(rnp.evaluate(g, [0, .5, 1]), [1, 1.5, 2])
    from ROOT import TSpline3
    s = TSpline3("spline", g)
    assert_array_equal(rnp.evaluate(s, [0, .5, 1]), map(s.Eval, [0, .5, 1]))
    # test exceptions
    assert_raises(TypeError, rnp.evaluate, object(), [1, 2, 3])
    assert_raises(ValueError, rnp.evaluate, h1, arr_2d)
    assert_raises(ValueError, rnp.evaluate, h2, arr_3d)
    assert_raises(ValueError, rnp.evaluate, h2, arr_1d)
    assert_raises(ValueError, rnp.evaluate, h3, arr_1d)
    assert_raises(ValueError, rnp.evaluate, h3, arr_2d)
    assert_raises(ValueError, rnp.evaluate, f1, arr_2d)
    assert_raises(ValueError, rnp.evaluate, f2, arr_3d)
    assert_raises(ValueError, rnp.evaluate, f2, arr_1d)
    assert_raises(ValueError, rnp.evaluate, f3, arr_1d)
    assert_raises(ValueError, rnp.evaluate, f3, arr_2d)
    assert_raises(ValueError, rnp.evaluate, g, arr_2d)
    assert_raises(ValueError, rnp.evaluate, s, arr_2d)
    assert_raises(ValueError, rnp.evaluate, "f", arr_1d)
    assert_raises(ValueError, rnp.evaluate, "x*y", arr_1d)
    assert_raises(ValueError, rnp.evaluate, "x", arr_2d)
    assert_raises(ValueError, rnp.evaluate, "x*y", arr_3d)
Esempio n. 7
0
                break
        if (rec / gen >= required_eff
                and count == 0):  #conservative estimation
            cospa_bin_list.append(cospa_bin)

    ct_array = ct_bins + ct_step_size / 2
    cospa_array = cospa_bins[cospa_bin_list -
                             1] + cospa_step_size[cospa_bin_list - 1] / 2
    graph_eff = TGraph(len(cospa_array), ct_array, cospa_array)
    graph_eff.SetName(f"{required_eff}")
    graph_eff.SetMarkerColor(kRed)
    graph_eff.SetMarkerStyle(8)
    graph_eff.SetMarkerSize(0.5)
    tcanvas_list.append(TCanvas(f"eff{required_eff}"))
    graph_list.append(graph_eff)

#write histo file
tfile = TFile('splines.root', 'recreate')
for eff, graph, cv in zip(required_eff_list, graph_list, tcanvas_list):
    spl = TSpline3(f"spline_{eff}", graph)
    spl.SetLineColor(kOrange)
    spl.SetLineWidth(3)
    cv.cd()
    hist_cosPA.Draw("colz")
    graph.Draw("p")
    spl.Draw("same")
    cv.Write()
    cv.Close()
    spl.Write(f"spline_{eff}")
tfile.Close()
    reguScan= False
    fixedTau = False
    noReg = True

    if reguScan:
    ##Regularize Curvature (it is done when the spectrum is rapidly falling)
        for b in range(2,nbinsGen):
            fnlbins = b
            down = dLevelMC.GetBinContent(fnlbins-1)
            up = dLevelMC.GetBinContent(fnlbins+1)
            
        unfold.RegularizeCurvature(b-1, b, b+1, 1.00/down,1.00/up)
        
        nScan=30;
        logTauX = TSpline3()
        logTauY = TSpline3()
        lCurve = TGraph()
        
        iBest=unfold.ScanLcurve(nScan,1e-04,1e-03,lCurve,logTauX,logTauY);
        print "( " + str(unfold.GetChi2A()) + "+" + str(unfold.GetChi2L()) +  ") / " +  str(unfold.GetNdf())
        print "Tau : ", unfold.GetTau()
        
        folderName = "ReguScan_"+str(unfold.GetTau())+"y-fineGEN"+label
        subprocess.call(["mkdir",folderName])
        
        l =[0.00,0.00]
        x=array('d', l)
        y=array('d', l)
        t=array('d', l)
Esempio n. 9
0
Nexp = inputCfg['nExpectedEvents']
Taa = inputCfg['Taa']
BR = inputCfg['BR']
fractoD = inputCfg['fractoD']

if inputCfg['PredForFprompt']['estimateFprompt']:
    infilePred = TFile.Open(inputCfg['PredForFprompt']['filename'])
    hPredPrompt = infilePred.Get(inputCfg['PredForFprompt']['histonamePrompt'])
    hPredFD = infilePred.Get(inputCfg['PredForFprompt']['histonameFD'])
    RatioRaaFDPrompt = inputCfg['PredForFprompt']['RatioRaaFDPrompt']

FONLL = ReadFONLL(inputCfg['filenameFONLL'])
TAMU = ReadTAMU(
    inputCfg['filenameRaaPredTAMU'])  #optimisation performed using TAMU
sTAMUmin = TSpline3('sTAMUmin', array.array('d', TAMU['PtCent']),
                    array.array('d', TAMU['Min']), len(TAMU['PtCent']))
sTAMUmax = TSpline3('sTAMUmax', array.array('d', TAMU['PtCent']),
                    array.array('d', TAMU['Max']), len(TAMU['PtCent']))

infileAcc = TFile(inputCfg['filenameAcc'])
hPtGenAcc = infileAcc.Get('hPtGenAcc')
hPtGenLimAcc = infileAcc.Get('hPtGenLimAcc')

cutVars = inputCfg['cutvars']
PtMin = inputCfg['PtMin']
PtMax = inputCfg['PtMax']

ranges = []
axesnum = []
upperlowercuts = []
steps = []
Esempio n. 10
0
def tau_from_scan(unfoldingObject, regularisation_settings):
    variable = regularisation_settings.variable

    # Plots that get outputted by the scan
    lCurve = TGraph()
    scanResult = TSpline3()
    d = 'signal'
    a = ''

    # Parameters of scan
    # Number of points to scan, and min/max tau
    nScan = 200
    minTau = 1.E-6
    maxTau = 1.E-0

    if variable == 'abs_lepton_eta':
        minTau = 1.E-8
        maxTau = 1.E-3
    elif variable == 'lepton_pt':
        minTau = 1.E-6
        maxTau = 1.E-2
    elif variable == 'NJets':
        minTau = 1.E-6
        maxTau = 1.E-2

    # Scan is performed here
    iBest = unfoldingObject.ScanTau(nScan, minTau, maxTau, scanResult,
                                    TUnfoldDensity.kEScanTauRhoSquareAvg)

    # Plot the scan result
    # Correlation as function of log tau
    canvas = TCanvas()

    # Add point corresponding to optimum tau
    t = Double(0)
    x = Double(0)
    scanResult.GetKnot(iBest, t, x)

    bestTau = Graph(1)
    bestTau.SetPoint(1, t, x)
    bestTau.markercolor = 'red'
    bestTau.SetMarkerSize(1.5)
    bestTau.SetMarkerStyle(34)
    bestTau.GetXaxis().SetTitle('log(#tau)')
    bestTau.GetYaxis().SetTitle(
        'Average global correlation coefficient squared')
    bestTau.SetTitle('{0} {1}'.format(variable,
                                      regularisation_settings.channel))
    bestTau.GetYaxis().SetRangeUser(x * 0.8, 0.95)
    bestTau.GetXaxis().SetLimits(log(minTau, 10), log(maxTau, 10))

    bestTau.Draw('AP')

    scanResult.SetMarkerColor(600)
    scanResult.SetMarkerSize(0.5)
    scanResult.SetMarkerStyle(20)
    scanResult.Draw('LPSAME')
    # Redraw to get it to appear on top of TSpline3...
    bestTau.Draw('PSAME')

    # Write to file
    output_dir = regularisation_settings.output_folder
    make_folder_if_not_exists(output_dir)
    canvas.SaveAs(
        output_dir +
        '/{0}_{1}.png'.format(variable, regularisation_settings.channel))

    return unfoldingObject.GetTau()
Esempio n. 11
0
def draw(mode, patch):
    if mode == 'total':
        xmin = 4.17
        xmax = 4.71
        step = (xmax - xmin) / 100
        # N = 19 + 6 + 6 + 6# 19: 703p01, 6: 705, 4: 705 above 4600
        N = 19 + 6 + 6  # 19: 703p01, 6: 705, 4: 705 above 4600
    if mode == 'psipp':
        xmin = 4.17
        xmax = 4.71
        step = (xmax - xmin) / 100
        # N = 19 + 6 + 6 + 6# 19: 703p01, 6: 705, 4: 705 above 4600
        N = 19 + 6 + 6  # 19: 703p01, 6: 705, 4: 705 above 4600
    if mode == 'DDPIPI':
        xmin = 4.17
        xmax = 4.71
        step = (xmax - xmin) / 100
        # N = 19 + 6 + 6 + 6# 19: 703p01, 6: 705, 4: 705 above 4600
        N = 19 + 6 + 6  # 19: 703p01, 6: 705, 4: 705 above 4600
    if mode == 'D1_2420':
        # N = 19 + 6 + 6 + 6# 18: 703p01, 6: 705, 4: 705 above 4600
        N = 19 + 6 + 6  # 18: 703p01, 6: 705, 4: 705 above 4600
    sys_err = array('f', N * [0])
    ecms = array('f', N * [0])
    ecms_err = array('f', N * [0])
    xs = array('f', N * [0])
    xs_err = array('f', N * [0])
    path = './txts/xs_' + mode + '_' + patch + '_plot.txt'

    mbc = TCanvas('mbc', 'mbc', 800, 600)
    set_canvas_style(mbc)
    hr = mbc.DrawFrame(4.17, -0.1, 4.71, 100)

    f = open(path, 'r')
    lines = f.readlines()
    count = 0
    for line in lines:
        rs = line.rstrip('\n')
        rs = filter(None, rs.split(' '))
        ecms[count] = ECMS(int(float(rs[0]) * 1000))
        ecms_err[count] = 0.0022
        xs[count] = round(float(rs[1]), 2)
        xs_err[count] = round(float(rs[2]), 2)
        count += 1

    grerr = TGraphErrors(N, ecms, xs, ecms_err, xs_err)
    # grerr = TGraph(N, ecms, xs)
    xtitle = '#sqrt{s}(GeV)'
    if mode == 'D1_2420':
        ytitle = '#sigma(e^{+}e^{-}#rightarrowD_{1}(2420)D)(pb)'
    if mode == 'psipp':
        ytitle = '#sigma(e^{+}e^{-}#rightarrow#psi(3770)#pi^{+}#pi^{-})(pb)'
    if mode == 'DDPIPI':
        ytitle = '#sigma(e^{+}e^{-}#rightarrowD^{+}D^{-}#pi^{+}#pi^{-})(PHSP)(pb)'
    if mode == 'total':
        ytitle = '#sigma(e^{+}e^{-}#rightarrow#pi^{+}#pi^{-}D^{+}D^{-})(pb)'
    hr.SetXTitle(xtitle)
    hr.SetYTitle(ytitle)
    set_graph_style(grerr, xtitle, ytitle)
    grerr.Draw('AP')
    spline = TSpline3('tspline', grerr)
    spline.SetLineColor(ROOT.kRed)
    spline.Draw('same')

    with open('./txts/xs_user_spline_' + str(mode) + '.txt', 'w') as f:
        for i in xrange(100):
            val = xmin + step * i
            f.write(str(val) + '\t' + str(spline.Eval(val)) + '\n')

    mbc.Update()

    if not os.path.exists('./figs/'):
        os.makedirs('./figs/')
    mbc.SaveAs('./figs/xs_' + mode + '_' + patch + '.pdf')

    raw_input('Enter anything to end...')
    for i in range(len(xlist) / smoothF)
]
grSmooth = TGraph(len(xlistSmooth), array("d", xlistSmooth),
                  array("d", pulseShapeSmooth))

c2 = TCanvas("c2", "c2", 700, 500)
h1.SetMinimum(-0.2)
h1.SetMaximum(1.1)
h1.DrawCopy("")

line = TLine(-30, 0, 100, 0)
line.SetLineColor(4)
line.Draw("same")

gr.Draw("same")
spline = TSpline3("spline", grSmooth)
spline.SetLineColor(2)
spline.Draw("same")

c2.Modified()
c2.Update()

## LOAD the old shape

Tprev = [
    3.22188688e-05, 3.22145863e-05, 3.22145863e-05, 3.22145863e-05,
    3.22145863e-05, 3.22145863e-05, 3.22145863e-05, 3.22145863e-05,
    3.22145863e-05, 3.22145863e-05, 3.22145863e-05, 3.22145863e-05,
    3.22145863e-05, 3.22145863e-05, 3.22145863e-05, 3.22145863e-05,
    3.22145863e-05, 3.22145863e-05, 3.22145863e-05, 3.22145863e-05,
    3.22145863e-05, 3.22145863e-05, 3.22145863e-05, 3.22145863e-05,
Esempio n. 13
0
    hDiff_tmp = TH1F("diff_bin" + str(ibin),
                     "; unfolded-truth; number of events", 100, -1, 1)
    hDiff_bin.append(hDiff_tmp)

lowedge = 399.
highedge = 1199.

for itoy in xrange(0, ntoys):

    unfold_tmp = TUnfoldDensity(Hres, TUnfold.kHistMapOutputVert,
                                TUnfold.kRegModeCurvature,
                                TUnfold.kEConstraintNone,
                                TUnfoldDensity.kDensityModeBinWidth)
    unfold_tmp.SetInput(hToy_i[itoy])
    if options.regType == "LCurve":
        logTauX_tmp = TSpline3()
        logTauY_tmp = TSpline3()
        lCurve_tmp = TGraph()
        unfold_tmp.ScanLcurve(30, 0., 0., lCurve_tmp, logTauX_tmp, logTauY_tmp)
    else:
        scanResult = TSpline3()
        unfold_tmp.ScanTau(100, 0.0001, 0.1, scanResult,
                           TUnfoldDensity.kEScanTauRhoAvg)

    hReco_tmp = unfold_tmp.GetOutput("tmp_output")

    for ibin in range(0, nbinsTrue):
        if thisTrue.GetBinLowEdge(
                ibin + 1) > lowedge and thisTrue.GetBinLowEdge(ibin +
                                                               1) < highedge:
            hDiff_bin[ibin].Fill((thisTrue.GetBinContent(ibin + 1) -