Пример #1
0
    def __call__(self, data):
        pdf_pars = self.__pdf.getParameters(data.get())
        if not self.__parameters:
            self.__parameters = pdf_pars
            self.__parameters = [p for p in pdf_pars] + [self.__status]
        else:
            for p in self.__parameters:
                pdf_par = pdf_pars.find(p.GetName())
                if not pdf_par:
                    continue
                pdf_par.setVal(p.getVal())
                pdf_par.setError(p.getError())

        success = False
        status = 4
        for i in range(3):
            self.__result = self.__pdf.fitTo(data, **self.__fit_opts)
            status = self.__result.status()
            if status == 0:
                success = True
                break

        if status < 4:
            self.__status.setIndex(self.__result.status())
        else:
            self.__status.setIndex(4)
        if success:
            from P2VV.Utilities.SWeights import SData

            self.__sData = SData(Pdf=self.__pdf, Data=data, Name="MassSPlot")
            data = self.__sData.data(self.__comp)
            if self.__correct_weights:
                from P2VV.Utilities.DataHandling import correctWeights

                data = correctWeights(data, splitCatNames=None, ImportIntoWS=False)
            return data
        else:
            return None
Пример #2
0
from ROOT import TCanvas
corr_canvas = TCanvas('corr_canvas', 'corr_canvas', 1000, 500)
corr_canvas.Divide(2, 1)
from ROOT import gStyle
gStyle.SetPalette(1)

## Plot correlation histogram
corr_canvas.cd(1)
corr_hist_sWmass = sWeight_mass_result.correlationHist()
corr_hist_sWmass.GetXaxis().SetLabelSize(0.03)
corr_hist_sWmass.GetYaxis().SetLabelSize(0.03)
corr_hist_sWmass.SetContour(20)
corr_hist_sWmass.Draw('colz')

from P2VV.Utilities.SWeights import SData
sData = SData(Pdf = sWeight_mass_pdf, Data = data, Name = 'SimulMassSPlot')
sig_sdata = sData.data('signal')
bkg_sdata = sData.data('background')

# Plot mass pdf

paper_calibration = FormulaVar(Name = 'st_calibration', Formula = '1.45 * @0', Arguments = [st])
dg_calibration = FormulaVar(Name = 'dg_calibration', Formula = "-6.81838 * @0 * @0 + 1.72 * @0", Arguments = [st])
sg_calibration = FormulaVar(Name = 'sg_calibration', Formula = "-0.00455 + 1.92 * @0-9.9352 * @0 * @0", Arguments = [st])
linear_calibration = FormulaVar(Name = 'linear_calibration', Formula = "0.00555 + 1.267 * @0", Arguments = [st])
from P2VV.Dilution import dilution
r = signal_dilution(psi_sdata, st, paper_calibration)
r = signal_dilution(psi_sdata, st, dg_calibration)
# r = signal_dilution(sig_sdata, st, sg_calibration)
# r = signal_dilution(sig_sdata, st, linear_calibration)
Пример #3
0
    def __init__(self, time, masses, t_diff = None, MassResult = None,
                 InputFile = "/bfys/raaij/p2vv/data/Bs2JpsiPhiPrescaled_2011.root",
                 Workspace = 'Bs2JpsiPhiPrescaled_2011_workspace', Data = 'data',
                 UseKeysPdf = False, Weights = 'B', Draw = False, Reweigh = {}):
        assert(Weights in ShapeBuilder.__weights)
        self.__weights = Weights
        self.__time = time
        self.__t_diff = t_diff
        pos = Workspace.find('201')
        self.__year = Workspace[pos : pos + 4]
        self.__input_ws = None
        self.__ws = RooObject().ws()
        self.__shapes = {}
        self.__diff__shapes = {}

        self.__masses = masses

        self._sig = Component('wpv_signal', [], Yield = (1000, 10, 5e5))
        self._psi = Component('wpv_jpsi',   [], Yield = (5000, 10, 5e5))
        self._bkg = Component('wpv_bkg',    [], Yield = (5000, 10, 5e5))

        if 'B' in masses:
            ## m_sig_mean  = RealVar('wpv_m_sig_mean',   Unit = 'MeV', Value = 5365, MinMax = (5363, 5372))
            ## m_sig_sigma = RealVar('wpv_m_sig_sigma',  Unit = 'MeV', Value = 10, MinMax = (1, 20))
            ## from ROOT import RooGaussian as Gaussian
            ## self._sig_mass = Pdf(Name = 'wpv_sig_m', Type = Gaussian, Parameters = (masses['B'], m_sig_mean, m_sig_sigma ))
            self._sig_mass = BMassPdf(masses['B'], Name = 'wpv_sig_mass', ParNamePrefix = "wpv",
                                      AvSigParameterisation = True)
            self._bkg_mass = BBkgPdf(masses['B'],  Name = 'wpv_bkg_mass', ParNamePrefix = "wpv",
                                     m_bkg_exp = dict(Name = 'm_bkg_exp', Value = -0.0017,
                                                      MinMax = (-0.01, -0.00001)))
            self._sig[masses['B']] = self._sig_mass.pdf()
            self._psi[masses['B']] = self._bkg_mass.pdf()
            self._bkg[masses['B']] = self._bkg_mass.pdf()
        if 'jpsi' in masses:
            self._sig_mpsi = PsiMassPdf(masses['jpsi'], Name = 'wpv_sig_mpsi', ParNamePrefix = "wpv")
            self._bkg_mpsi = PsiBkgPdf(masses['jpsi'], Name = 'wpv_bkg_mpsi', ParNamePrefix = "wpv")
            self._sig[masses['jpsi']] = self._sig_mpsi.pdf()
            self._psi[masses['jpsi']] = self._sig_mpsi.pdf()
            self._bkg[masses['jpsi']] = self._bkg_mpsi.pdf()

        self.__components = {'jpsi' : dict(jpsi = self._psi, bkg = self._bkg),
                             'B'    : dict(B = self._sig, bkg = self._bkg),
                             'both' : dict(B = self._sig, jpsi = self._psi, bkg = self._bkg)}
        self.__pdf = buildPdf(self.__components[Weights].values(), Observables = masses.values(),
                             Name = 'wpv_mass_pdf')
        if MassResult:
            ## Use the provided mass result to set all the parameter values, only float the yields
            pdf_params = self.__pdf.getParameters(RooArgSet(*masses.values()))
            for p in MassResult.floatParsFinal():
                ## ignore yields
                if any((p.GetName().startswith(n) for n in ['N_', 'mpsi_c'])):
                    continue
                ## Find pdf parameter, add "wpv_" prefix
                pdf_p = pdf_params.find('wpv_' + p.GetName())
                if pdf_p:
                    pdf_p.setVal(p.getVal())
                    pdf_p.setError(p.getError())
                    pdf_p.setConstant(True)

        self.__pdf.Print("t")

        from ROOT import TFile
        input_file = TFile.Open(InputFile)
        if not input_file or not input_file.IsOpen():
            raise OSError

        if Workspace:
            self.__input_ws = input_file.Get(Workspace)
            if not self.__input_ws:
                print 'Cannot find workspace %s in mixing file.' % Workspace
                raise RuntimeError
            self._data = self.__input_ws.data(Data)
            if not self._data:
                print 'Cannot find data in workspace %s.' % Workspace
                raise RuntimeError
        else:
            self._data = input_file.Get(Data)

        if not self._data.get().find(time.GetName()) and "refit" in time.GetName():
            from ROOT import RooFormulaVar, RooArgList
            def __add_alias(name, obs):
                obs_name = obs.GetName()[:-6]
                do = self._data.get().find(obs_name)
                rf = RooFormulaVar(name, name, "@0", RooArgList(do))
                a = self._data.addColumn(rf)
                a.setMin(obs.getMin())
                a.setMax(obs.getMax())
                return a

            ## Add refit observables
            time = __add_alias("time_refit", time)
            self.__time = time
            self.__time.Print()
            if t_diff:
                t_diff = __add_alias("time_diff_refit", t_diff)
                self.__t_diff = t_diff

        if t_diff:
            self._data = self._data.reduce("{0} > {1} && {0} < {2} && {3} > {4} && {3} < {5}".format(time.GetName(), time.getMin(), time.getMax(), t_diff.GetName(), t_diff.getMin(), t_diff.getMax()))
        else:
            self._data = self._data.reduce("{0} > {1} && {0} < {2}".format(time.GetName(), time.getMin(), time.getMax()))

        # self._data = self._data.reduce("mass > 5348 && mass < 5388")
        fitOpts = dict(NumCPU = 4, Save = True, Minimizer = 'Minuit2', Optimize = 2)
        self.__result = self.__pdf.fitTo(self._data, **fitOpts)

        from P2VV.Utilities.SWeights import SData
        for p in self.__pdf.Parameters(): p.setConstant(not p.getAttribute('Yield'))
        splot = SData(Pdf = self.__pdf, Data = self._data, Name = 'MixingMassSplot')
        self.__sdatas = {}
        self.__reweigh_weights = {}
        for key, c in self.__components[Weights].iteritems():
            sdata = splot.data(c.GetName())

            if 'Data' in Reweigh and key in Reweigh['Data']:
                from array import array
                from ROOT import RooBinning

                source = Reweigh['Data'][key]
                binning = Reweigh['Binning']
                if type(binning) == array:
                    binning = RooBinning(len(binning) - 1, binning)
                    binning.SetName('reweigh')
                    Reweigh['DataVar'].setBinning(binning, 'reweigh')

                source_obs = source.get().find('nPV')
                cat_name = 'nPVs_' + key
                source_cat = source.get().find(cat_name)
                if source_cat:
                    # Remove previous weights to make sure we get it right
                    new_vars = source.get()
                    new_vars.remove(source_cat)
                    source = source.reduce(new_vars)
                    source_obs = source.get().find(source_obs.GetName())

                source_obs.setBinning(binning, 'reweigh')                
                source_cat = BinningCategory(Name = cat_name, Observable = source_obs,
                                             Binning = binning, Data = source, Fundamental = True)
                from P2VV.Reweighing import reweigh
                sdata, weights = reweigh(sdata, sdata.get().find('nPV'),
                                         source, source_cat)
                self.__reweigh_weights[key] = weights

            sdata = self.__ws.put(sdata)
            self.__sdatas[c] = sdata

        rho_keys = dict((v, k) for k, v in self.__components[Weights].iteritems())
        self.__shapes = {}
        self.__diff_shapes = {}
        for c, sdata in self.__sdatas.iteritems():
            if UseKeysPdf:
                rk = rho_keys[c]
                rho = ShapeBuilder.__rho[rk] if rk in ShapeBuilder.__rho else 1.
                time_shape = KeysPdf(Name = 'wpv_%s_pdf' % c.GetName(), Observable = time, Data = sdata, Rho = rho)
                if t_diff:
                    diff_shape = KeysPdf(Name = 'wpv_%s_diff_pdf' % c.GetName(), Observable = t_diff, Data = sdata)

            else:
                time_shape = HistPdf(Name = 'wpv_%s_pdf' % c.GetName(), Observables = [time],
                                Data = sdata, Binning = {time : 35})
                if t_diff:
                    diff_shape = HistPdf(Name = 'wpv_%s_diff_pdf' % c.GetName(), Observables = [t_diff],
                                         Data = sdata, Binning = {time : 35})
            self.__shapes[c] = time_shape
            if t_diff:
                self.__diff_shapes[c] = diff_shape
        if Draw:
            self.__draw()
Пример #4
0
if parFileOut :
    # write parameters to file
    pdfConfig.getParametersFromPdf( sWeightMassPdf, preDataSet )
    pdfConfig.writeParametersToFile( filePath = parFileOut )


###########################################################################################################################################
## compute sWeights ##
######################

print 120 * '='
print 'P2VV - INFO: createBs2JpsiKKDataSet: computing sWeights'

# compute sWeights
from P2VV.Utilities.SWeights import SData
sWeightsBuilder = SData( Pdf = sWeightMassPdf, Data = preDataSet, Name = 'JpsiKK' )
preSDataSet = sWeightsBuilder.data()

# import sWeight variables
weightVars = [ ]
for wName in sWeightNames :
    ws.put( preSDataSet.get().find(wName) )
    weightVars.append( RealVar(wName) )


###################################################################################################################################
## add tagging observables to data sets ##
##########################################

print 120 * '='
print 'P2VV - INFO: createBs2JpsiKKDataSet: building tagging categories'
Пример #5
0
fitOpts = dict(NumCPU = 4, Timer = 1, Save = True, Optimize = 2,
               Strategy = 2, Offset = True, Minimizer = 'Minuit2')

# Acceptance data
from ROOT import TFile
f= TFile.Open('Bs2JpsiPhi_DataSet.root')
assert f
workspace = f.Get('Bs2JpsiPhi_workspace')
data = workspace.data('data')
pdf.fitTo(data, **fitOpts)


# sPlot
from P2VV.Utilities.SWeights import SData
sData = SData(Pdf = pdf, Data = data, Name = 'splot')

# Observables
observables = data.get()

# Mapping for Fit
ranges = [o for o in observables if o.GetName().find('tp') != -1 ]
datas = dict([(c.GetName(), sData.data(c.GetName())) for c in (signal, comb_background, psi_background)])
yields = dict([(c.GetName(), c.getYield()) for c in (signal, comb_background, psi_background)])
weights = dict([( n, observables.find(o.GetName() + '_sw') ) for n, o in yields.iteritems()])

ranges.sort()
range_names = []
for i in range(0, len(ranges), 2):
    l = ranges[i]
    r = ranges[i + 1]
Пример #6
0
class SWeightTransform(object):
    def __init__(self, pdf, component, fit_opts, correct_weights=True):
        self.__comp = component
        self.__pdf = pdf
        self.__fit_opts = fit_opts
        self.__result = None
        self.__correct_weights = correct_weights

        from ROOT import RooCategory

        self.__status = RooCategory("sweight_status", "sweight fit status")
        self.__status.defineType("success", 0)
        self.__status.defineType("one", 1)
        self.__status.defineType("two", 2)
        self.__status.defineType("three", 3)
        self.__status.defineType("other", 4)
        self.__parameters = None

    def __call__(self, data):
        pdf_pars = self.__pdf.getParameters(data.get())
        if not self.__parameters:
            self.__parameters = pdf_pars
            self.__parameters = [p for p in pdf_pars] + [self.__status]
        else:
            for p in self.__parameters:
                pdf_par = pdf_pars.find(p.GetName())
                if not pdf_par:
                    continue
                pdf_par.setVal(p.getVal())
                pdf_par.setError(p.getError())

        success = False
        status = 4
        for i in range(3):
            self.__result = self.__pdf.fitTo(data, **self.__fit_opts)
            status = self.__result.status()
            if status == 0:
                success = True
                break

        if status < 4:
            self.__status.setIndex(self.__result.status())
        else:
            self.__status.setIndex(4)
        if success:
            from P2VV.Utilities.SWeights import SData

            self.__sData = SData(Pdf=self.__pdf, Data=data, Name="MassSPlot")
            data = self.__sData.data(self.__comp)
            if self.__correct_weights:
                from P2VV.Utilities.DataHandling import correctWeights

                data = correctWeights(data, splitCatNames=None, ImportIntoWS=False)
            return data
        else:
            return None

    def gen_params(self, observables=None):
        from ROOT import RooArgSet

        if self.__parameters:
            return self.__parameters
        else:
            if observables and not isinstance(observables, RooArgSet):
                obs = RooArgSet()
                for o in observables:
                    obs.add(o._target_() if hasattr(o, "_target_") else o)
                observables = obs
            params = self.__pdf.getParameters(observables)
            self.__parameters = [p for p in params] + [self.__status]
            return self.__parameters

    def result_params(self):
        if not self.__result:
            return []
        else:
            return [p for p in self.__result.floatParsFinal()] + [self.__status]

    def set_params(self, data_params):
        from ROOT import RooCategory

        for trans_param in self.result_params():
            data_param = data_params.find(trans_param.GetName())
            if isinstance(trans_param, RooCategory):
                data_param.setIndex(trans_param.getIndex())
            else:
                data_param.setVal(trans_param.getVal())
                # This sets a symmetric error, but since we don't run Minos, that's ok
                data_param.setError(trans_param.getError())
Пример #7
0
                  xTitle = 'M_{#mu^{+}#mu^{-}} [MeV/c^{2}]',
                  yTitle = 'Candidates / (%3.2f MeV/c^{2})' % ((mass_obs.getMax() - mass_obs.getMin()) / 50),
                  yTitleOffset = 1 / 0.7)
        plots[''].append(ps)
        from P2VV.Utilities.Resolution import plot_dir
        if signal_MC:
            plot_name = 'prescaled_%s_B_mass.pdf'
        else:
            plot_name = 'prescaled_%s_Jpsi_mass.pdf'
        
        mass_canvas.Print(os.path.join(plot_dir, plot_name % args[0]), EmbedFonts = True)
        
    from P2VV.Utilities.SWeights import SData
    from P2VV.Utilities.DataHandling import correctWeights
    data_clone = data.Clone(data.GetName())
    sData = SData(Pdf = mass_pdf, Data = data_clone, Name = 'MassSPlot')
    ## single_bin_sig_sdata = correctWeights(sData.data(signal_name), splitCatNames = None, ImportIntoWS = False)
    ## single_bin_bkg_sdata = correctWeights(sData.data('background'), splitCatNames = None, ImportIntoWS = False)
    single_bin_sig_sdata = sData.data(signal_name)
    single_bin_bkg_sdata = sData.data('background')
    del sData
    sdatas = {'sig_sdata' : single_bin_sig_sdata,
              'bkg_sdata' : single_bin_bkg_sdata}
    ## Mass PDF is still connected to data_clone, redirect and delete data_clone
    mass_pdf.recursiveRedirectServers(data.get())
    del data_clone
    gc.collect()

if fit_mass and options.simultaneous:
    from P2VV.Utilities.General import getSplitPar
    # categories for splitting the PDF
Пример #8
0
    simMassFitResult.correlationMatrix().Print()

else :
    massPdfPars    = massPdf.getVariables()
    sWeightMassPdf = massPdf


###########################################################################################################################################
## compute sWeights ##
######################

print 'P2VV - INFO: createB2CCFitNTuple: computing sWeights'

# compute sWeights
from P2VV.Utilities.SWeights import SData
sWeightsBuilder = SData( Pdf = sWeightMassPdf, Data = dataSets['pre'][0], Name = 'JpsiKK' )
dataSets['preS'] = ( sWeightsBuilder.data(), [ ] )

# import sWeight variables
weightVars = [ ]
for wName in [ 'N_sigMass_sw', 'N_cbkgMass_sw' ] :
    ws.put( dataSets['preS'][0].get().find(wName) )
    weightVars.append( RealVar(wName) )


###########################################################################################################################################
## create signal and background data sets and print event yields ##
###################################################################

print 120 * '='
print 'P2VV - INFO: createB2CCFitNTuple: creating data set'
Пример #9
0
        sigYield.setMin(0.0)
        sigYield.setMax(nEvBin)
        bkgYield.setVal(bkgYield.getVal() * nEvBin / nEv)
        bkgYield.setError(sqrt(bkgYield.getVal()))
        bkgYield.setMin(0.0)
        bkgYield.setMax(nEvBin)

    # determine mass parameters in each sub-sample with a fit
    sim_mass_result = sWeight_mass_pdf.fitTo(data, **fitOpts)
    sweight_pdf = sWeight_mass_pdf
else:
    sweight_pdf = mass_pdf

from P2VV.Utilities.SWeights import SData

sdata = SData(Pdf=sweight_pdf, Data=data, Name="mass_sdata")
sig_sdata = sdata.data("signal")
bkg_sdata = sdata.data("background")

from ROOT import TFile

f = TFile.Open(input_file, "update")
tree = f.Get("DecayTree")

from ROOT import addVertexErrors, addJpsiDLS
from ROOT import std

dss = std.list("RooDataSet*")()
dss.push_back(sig_sdata)
dss.push_back(bkg_sdata)
if options.dls:
Пример #10
0
        sigYield.setMin(0.)
        sigYield.setMax(nEvBin)
        bkgYield.setVal( bkgYield.getVal() * nEvBin / nEv )
        bkgYield.setError( sqrt( bkgYield.getVal() ) )
        bkgYield.setMin(0.)
        bkgYield.setMax(nEvBin)
    
    # determine mass parameters in each sub-sample with a fit
    sim_mass_result = sWeight_mass_pdf.fitTo(data, **fitOpts)
    sweight_pdf = sWeight_mass_pdf
else:
    sweight_pdf = mass_pdf

from P2VV.Utilities.SWeights import SData
from P2VV.Utilities.DataHandling import correctWeights
sdata = SData( Pdf = sweight_pdf, Data = data, Name = 'mass_sdata')

sig_sdata = correctWeights(sdata.data('signal'), splitCatNames = [excl_biased.GetName()],
                           ImportIntoWS = False)
bkg_sdata = correctWeights(sdata.data('background'), splitCatNames = [excl_biased.GetName()],
                           ImportIntoWS = False)

from array import array
weights = array('d')

from ROOT import TFile
f = TFile.Open(input_file, "read")
tree = f.Get("DecayTree")

from ROOT import gDirectory
tree.Draw(">>elist", cut, "entrylist")
Пример #11
0
            pdfOpts  = dict()
            plot(p, o, pdf = mass_pdf, data = data
                 , dataOpts = dict(MarkerSize = 0.8, MarkerColor = kBlack)
                 , pdfOpts  = dict(LineWidth = 2, **pdfOpts)
                 , plotResidHist = True
                 , components = { 'bkg_*'     : dict( LineColor = kRed,   LineStyle = kDashed ),
                                  ## 'psi_*'  : dict( LineColor = kGreen, LineStyle = kDashed ),
                                  'sig_*'     : dict( LineColor = kBlue,  LineStyle = kDashed )
                                  }
                 )
        # Do the sWeights
        # make sweighted dataset. TODO: use mumu mass as well...
        from P2VV.Utilities.SWeights import SData

        for p in mass_pdf.Parameters() : p.setConstant( not p.getAttribute('Yield') )
        splot = SData(Pdf = mass_pdf, Data = data, Name = 'MassSplot')
        data = splot.data('signal')
        ## psi_sdata = splot.data('psi_background')
        bkg_sdata = splot.data('background')

        if 'MC' in args[0]:
            import random
            ## Set more events to be unbiased, so we get some HLT2 exclusive biased
            ## sample.
            new_data = RooDataSet("new_data", "new_data", data.get())
            for i, obs in enumerate(data):
                b2 = obs.find('hlt2_biased')
                ub2 = obs.find('hlt2_unbiased')
                eb2 = obs.find('hlt2_excl_biased')
                if b2.getIndex() == 0:
                    pass