Ejemplo n.º 1
0
def fit_2d():
    #variable inizialization
    im = ROOT.RooRealVar('im', 'im', 2.42, 2.52)
    m23 = ROOT.RooRealVar('m23', 'm23', 0.80, 1.00)

    #open and reduce dataset
    rfile = ROOT.TFile("../datasets/test_xic_100invpb.root", "READ")
    ds = rfile["da_lc"]
    ds = ds.reduce("im > 2.42 && im < 2.52 && m23 > 0.8 && m23 < 1.")
    dh = (ds.reduce(ROOT.RooArgSet(im, m23), "im>0 && m23>0")).binnedClone()

    #model creation
    signal_im = Models.Gauss_pdf('Gauss_x',
                                 xvar=im,
                                 mean=(2.45, 2.48),
                                 sigma=(0.001, 0.01))
    signal_m23 = Models.Gauss_pdf('Gauss_y',
                                  xvar=m23,
                                  mean=(0.8, 1.),
                                  sigma=(0.001, 0.01))
    bkg_poly_im = Models.Bkg_pdf('BkgGauss_x', xvar=im, power=0.)
    bkg_poly_m23 = Models.Bkg_pdf('BkgGauss_y', xvar=m23, power=0.)
    model_gauss = Models.Fit2D(signal_x=signal_im,
                               signal_y=signal_m23,
                               bkg_1x=bkg_poly_im,
                               bkg_1y=bkg_poly_m23)

    #model fitting
    result, frame = model_gauss.fitTo(dh)
    result, frame = model_gauss.fitTo(ds, draw=True)
    result.draw()
Ejemplo n.º 2
0
def test_morphing1():

    logger = getLogger('test_morphing1')
    if ROOT.gROOT.GetVersionInt() < 62301:
        logger.warning('Test is disabled for ROOT version %s' %
                       ROOT.gROOT.GetVersion())
        return

    pdf1 = Models.Gauss_pdf('G1', xvar=mass, mean=10, sigma=1)
    pdf2 = Models.Gauss_pdf('G2', xvar=mass, mean=10, sigma=2)
    pdf3 = Models.Gauss_pdf('G3', xvar=mass, mean=10, sigma=3)
    pdf4 = Models.Gauss_pdf('G4', xvar=mass, mean=10, sigma=4)

    pdf = Morphing1D_pdf('M1', {
        1.0: pdf1,
        2.0: pdf2,
        3.0: pdf3,
        4.0: pdf4,
    },
                         xvar=mass)

    for mu in vrange(1, 3, 6):
        pdf.mu = mu
        logger.info('Mu= %s' % mu)
        pdf.draw()

    r, f = pdf.fitHisto(h1, draw=True, nbins=100, silent=True)
    logger.info('Morphing: \n%s' % r.table(prefix="# "))
Ejemplo n.º 3
0
def test_simfit2 ( ) :
    
    # =========================================================================    
    signal1  = Models.Gauss_pdf ( 'G1'                 ,
                                  xvar  = mass1        ,
                                  mean  = (1.5 , 6.5 ) ,
                                  sigma = (0.1 , 2.5 ) )
    
    model1   = Models.Fit1D ( suffix = 'M1' , signal = signal1 ,  background = -1 )
    model1.S = NS1
    model1.B = NB1 
    
    
    mean2    = signal1.vars_add      ( signal1.mean  , 10.0 )
    sigma2   = signal1.vars_multiply ( signal1.sigma , 0.5  )
    
    signal2  = Models.Gauss_pdf ( 'G2'            ,
                                  xvar  = mass2   ,
                                  mean  = mean2   ,
                                  sigma = sigma2  )
    
    model2  = Models.Fit1D ( suffix = 'M2' , signal = signal2 ,  background = -1  )
    model2.S = NS2
    model2.B = NB2 
    
    # =========================================================================
    ## fit 1 
    r1 , f1 = model1.fitTo ( dataset1 , draw = True , nbins = 50 , silent = True )
    
    ## fit 2
    r2 , f2 = model2.fitTo ( dataset2 , draw = True , nbins = 50 , silent = True )
    # =========================================================================
    
    ## combine data
    sample  = ROOT.RooCategory ('sample','sample'  , 'A' , 'B' )
    
    ## combine datasets
    from ostap.fitting.simfit import combined_data 
    vars    = ROOT.RooArgSet ( mass1 , mass2 )
    dataset = combined_data  ( sample , vars , { 'A' : dataset1 , 'B' : dataset2 } )
    
    
    ## combine PDFs
    model_sim  = Models.SimFit (
        sample , { 'A' : model1  , 'B' : model2 } , name = 'X'
        )
    
    # =========================================================================
    r , f = model_sim.fitTo ( dataset , silent = True )
    r , f = model_sim.fitTo ( dataset , silent = True )
    
    fA    = model_sim.draw ( 'A' , dataset , nbins = 50 )
    fB    = model_sim.draw ( 'B' , dataset , nbins = 50 )
    
    fNLL  = model_sim.draw_nll ( 'SM2' , dataset , range =   (0,1000)  )
    
    ## significance 
    wilks = model_sim.wilks    ( 'SM2' , dataset  )
    
    logger.info ( 'Fit  results are: %s ' % r )
Ejemplo n.º 4
0
def test_simfit2():

    logger = getLogger('test_simfit2')
    # =========================================================================
    signal1 = Models.Gauss_pdf('G1',
                               xvar=mass1,
                               mean=(1.5, 6.5),
                               sigma=(0.1, 2.5))

    model1 = Models.Fit1D(suffix='M1', signal=signal1, background=-1)
    model1.S = NS1
    model1.B = NB1

    mean2 = signal1.vars_add(signal1.mean, 10.0)
    sigma2 = signal1.vars_multiply(signal1.sigma, 0.5)

    signal2 = Models.Gauss_pdf('G2', xvar=mass2, mean=mean2, sigma=sigma2)

    model2 = Models.Fit1D(suffix='M2', signal=signal2, background=-1)
    model2.S = NS2
    model2.B = NB2

    with use_canvas('test_simfit2'):
        # =========================================================================
        ## fit 1
        with wait(1):
            r1, f1 = model1.fitTo(dataset1, draw=True, nbins=50, silent=True)
            title = 'Results of fit to dataset1'
            logger.info('%s\n%s' % (title, r1.table(title=title, prefix='# ')))
        ## fit 2
        with wait(1):
            r2, f2 = model2.fitTo(dataset2, draw=True, nbins=50, silent=True)
            title = 'Results of fit to dataset2'
            logger.info('%s\n%s' % (title, r2.table(title=title, prefix='# ')))
        # =========================================================================

    ## combine data
    sample = ROOT.RooCategory('sample', 'sample', 'A', 'B')

    ## combine datasets
    from ostap.fitting.simfit import combined_data
    vars = ROOT.RooArgSet(mass1, mass2)
    dataset = combined_data(sample, vars, {'A': dataset1, 'B': dataset2})

    ## combine PDFs
    model_sim = Models.SimFit(sample, {'A': model1, 'B': model2}, name='X')

    # =========================================================================
    r, f = model_sim.fitTo(dataset, silent=True)
    r, f = model_sim.fitTo(dataset, silent=True)

    title = 'Results of simultaneous fit'
    logger.info('%s\n%s' % (title, r.table(title=title, prefix='# ')))

    with use_canvas('test_simfit2'):
        with wait(1):
            fA = model_sim.draw('A', dataset, nbins=50)
        with wait(1):
            fB = model_sim.draw('B', dataset, nbins=50)
Ejemplo n.º 5
0
def test_simfit1():

    logger = getLogger('test_simfit1')

    signal1 = Models.Gauss_pdf('G1',
                               xvar=mass,
                               mean=(0.5, 2.5),
                               sigma=(0.1, 1.0))

    model1 = Models.Fit1D(suffix='M1', signal=signal1, background=-1)
    model1.S = NS1
    model1.B = NB1

    mean2 = signal1.vars_add(signal1.mean, 1.0)
    sigma2 = signal1.vars_multiply(signal1.sigma, 0.5)

    signal2 = Models.Gauss_pdf('G2', xvar=mass, mean=mean2, sigma=sigma2)

    model2 = Models.Fit1D(suffix='M2',
                          signal=signal2,
                          background=model1.background)
    model2.S = NS2
    model2.B = NB2

    with use_canvas('test_simfit1'):
        # =========================================================================
        ## fit 1
        with wait(1):
            r1, f1 = model1.fitTo(dataset1, draw=True, nbins=50, silent=True)

        ## fit 2
        with wait(1):
            r2, f2 = model2.fitTo(dataset2, draw=True, nbins=50, silent=True)
        # =========================================================================

    ## combine data

    sample = ROOT.RooCategory('sample', 'sample', 'A', 'B')

    ## combine datasets
    from ostap.fitting.simfit import combined_data
    vars = ROOT.RooArgSet(mass)
    dataset = combined_data(sample, vars, {'A': dataset1, 'B': dataset2})

    ## combine PDFs
    model_sim = Models.SimFit(sample, {'A': model1, 'B': model2}, name='X')

    # =========================================================================
    r, f = model_sim.fitTo(dataset, silent=True)
    r, f = model_sim.fitTo(dataset, silent=True)

    with use_canvas('test_simfit1'):
        with wait(1):
            fA = model_sim.draw('A', dataset, nbins=50)
        with wait(1):
            fB = model_sim.draw('B', dataset, nbins=50)
            logger.info('Fit  results are: %s ' % r)
Ejemplo n.º 6
0
def test_model_13():

    logger.info(
        'Non-factorizeable fit component:  ( Gauss + expo*P1 ) (x) ( Gauss + expo*P1 ) + (Expo*PS)**2'
    )
    PS = Ostap.Math.PhaseSpaceNL(1.0, 5.0, 2, 5)
    model = Models.Fit2D(suffix='_13',
                         signal_1=Models.Gauss_pdf('Gx',
                                                   m_x.getMin(),
                                                   m_x.getMax(),
                                                   mass=m_x),
                         signal_2=Models.Gauss_pdf('Gy',
                                                   m_y.getMin(),
                                                   m_y.getMax(),
                                                   mass=m_y),
                         power1=1,
                         power2=1,
                         bkg2D=Models.ExpoPSPol2D_pdf('P2D13',
                                                      m_x,
                                                      m_y,
                                                      psy=PS,
                                                      nx=1,
                                                      ny=1))

    model.signal1.sigma.fix(m.error())
    model.signal2.sigma.fix(m.error())
    model.signal1.mean.fix(m.value())
    model.signal2.mean.fix(m.value())
    model.signal1.mean.fix(m.value())
    model.signal2.mean.fix(m.value())
    model.bkg1.tau.fix(0)
    model.bkg2.tau.fix(0)

    ## fit with fixed mass and sigma
    with rooSilent():
        result, frame = model.fitTo(dataset)
        model.signal1.sigma.release()
        model.signal2.sigma.release()
        model.signal1.mean.release()
        model.signal2.mean.release()
        result, frame = model.fitTo(dataset)

    if 0 != result.status() or 3 != result.covQual():
        logger.warning('Fit is not perfect MIGRAD=%d QUAL=%d ' %
                       (result.status(), result.covQual()))
        print result
    else:
        logger.info('S1xS2 : %20s' % result(model.ss)[0])
        logger.info('S1xB2 : %20s' % result(model.sb)[0])
        logger.info('B1xS2 : %20s' % result(model.bs)[0])
        logger.info('B1xB2 : %20s' % result(model.bb)[0])

    models.add(model)
Ejemplo n.º 7
0
def test_model_15():

    logger.info(
        'Non-factorized symmetric background component (spline):  ( Gauss + expo*P1 ) (x) ( Gauss + expo*P1 ) + Spline2Dsym'
    )
    SPLINES = Ostap.Math.Spline2DSym(spline1)
    model = Models.Fit2D(suffix='_15',
                         signal_1=Models.Gauss_pdf('Gx',
                                                   m_x.getMin(),
                                                   m_x.getMax(),
                                                   mass=m_x),
                         signal_2=Models.Gauss_pdf('Gy',
                                                   m_y.getMin(),
                                                   m_y.getMax(),
                                                   mass=m_y),
                         power1=1,
                         power2=1,
                         bkg2D=Models.Spline2Dsym_pdf('P2D15',
                                                      m_x,
                                                      m_y,
                                                      spline=SPLINES))

    model.signal1.sigma.fix(m.error())
    model.signal2.sigma.fix(m.error())
    model.signal1.mean.fix(m.value())
    model.signal2.mean.fix(m.value())
    model.signal1.mean.fix(m.value())
    model.signal2.mean.fix(m.value())
    model.bkg1.tau.fix(0)
    model.bkg2.tau.fix(0)

    ## fit with fixed mass and sigma
    with rooSilent():
        result, frame = model.fitTo(dataset)
        model.signal1.sigma.release()
        model.signal2.sigma.release()
        model.signal1.mean.release()
        model.signal2.mean.release()
        result, frame = model.fitTo(dataset)

    if 0 != result.status() or 3 != result.covQual():
        logger.warning('Fit is not perfect MIGRAD=%d QUAL=%d ' %
                       (result.status(), result.covQual()))
        print result
    else:
        logger.info('S1xS2 : %20s' % result(model.ss)[0])
        logger.info('S1xB2 : %20s' % result(model.sb)[0])
        logger.info('B1xS2 : %20s' % result(model.bs)[0])
        logger.info('B1xB2 : %20s' % result(model.bb)[0])

    models.add(model)
Ejemplo n.º 8
0
def test_psxps_BBsym():
    logger.info(
        'Simmetric fit model with non-factorizeable background component:  ( Gauss + expo*P1 ) (x) ( Gauss + expo*P1 ) + (PS*P1)**2'
    )
    PS = Ostap.Math.PhaseSpaceNL(1.0, 5.0, 2, 5)
    model = Models.Fit2DSym(suffix='_12',
                            signal_1=Models.Gauss_pdf('Gx',
                                                      m_x.getMin(),
                                                      m_x.getMax(),
                                                      mass=m_x),
                            signal_2=Models.Gauss_pdf('Gy',
                                                      m_y.getMin(),
                                                      m_y.getMax(),
                                                      mass=m_y),
                            bkg1=1,
                            bkg2D=Models.PSPol2Dsym_pdf('P2D12',
                                                        m_x,
                                                        m_y,
                                                        ps=PS,
                                                        n=1))

    model.signal1.sigma.fix(m.error())
    model.signal2.sigma.fix(m.error())
    model.signal1.mean.fix(m.value())
    model.signal2.mean.fix(m.value())
    model.signal1.mean.fix(m.value())
    model.signal2.mean.fix(m.value())
    model.bkg1.tau.fix(0)
    model.bkg2.tau.fix(0)

    ## fit with fixed mass and sigma
    with rooSilent():
        result, frame = model.fitTo(dataset)
        model.signal1.sigma.release()
        model.signal2.sigma.release()
        model.signal1.mean.release()
        model.signal2.mean.release()
        result, frame = model.fitTo(dataset)

    if 0 != result.status() or 3 != result.covQual():
        logger.warning('Fit is not perfect MIGRAD=%d QUAL=%d ' %
                       (result.status(), result.covQual()))
        print result
    else:
        logger.info('S1xS2 : %20s' % result(model.ss)[0])
        logger.info('S1xB2 : %20s' % (result(model.sb)[0] / 2))
        logger.info('B1xS2 : %20s' % (result(model.bs)[0] / 2))
        logger.info('B1xB2 : %20s' % result(model.bb)[0])

    models.add(model)
Ejemplo n.º 9
0
def test_p1xp1_BB():
    logger.info(
        'Simplest non-factorized fit model:  ( Gauss + P1 ) (x) ( Gauss + P1 ) + BB'
    )
    model = Models.Fit2D(suffix='_3',
                         signal_1=Models.Gauss_pdf('Gx',
                                                   m_x.getMin(),
                                                   m_x.getMax(),
                                                   mass=m_x),
                         signal_2=Models.Gauss_pdf('Gy',
                                                   m_y.getMin(),
                                                   m_y.getMax(),
                                                   mass=m_y),
                         power1=1,
                         power2=1,
                         bkg2D=Models.PolyPos2D_pdf('P2D',
                                                    m_x,
                                                    m_y,
                                                    nx=2,
                                                    ny=2))

    model.signal1.sigma.fix(m.error())
    model.signal2.sigma.fix(m.error())
    model.signal1.mean.fix(m.value())
    model.signal2.mean.fix(m.value())
    model.signal1.mean.fix(m.value())
    model.signal2.mean.fix(m.value())
    model.bkg1.tau.fix(0)
    model.bkg2.tau.fix(0)

    ## fit with fixed mass and sigma
    with rooSilent():
        result, frame = model.fitTo(dataset)
        model.signal1.sigma.release()
        model.signal2.sigma.release()
        model.signal1.mean.release()
        model.signal2.mean.release()
        result, frame = model.fitTo(dataset)

    if 0 != result.status() or 3 != result.covQual():
        logger.warning('Fit is not perfect MIGRAD=%d QUAL=%d ' %
                       (result.status(), result.covQual()))
        print result
    else:
        logger.info('S1xS2 : %20s' % result(model.ss)[0])
        logger.info('S1xB2 : %20s' % result(model.sb)[0])
        logger.info('B1xS2 : %20s' % result(model.bs)[0])
        logger.info('B1xB2 : %20s' % result(model.bb)[0])

    models.add(model)
Ejemplo n.º 10
0
def test_p1xp1_BBss():
    logger.info(
        'Symmetrised fit model with non-factorized symmetric background:  ( Gauss + P1 ) (x) ( Gauss + P1 ) + BBsym'
    )
    sb = ROOT.RooRealVar('sb', 'SB', 0, 10000)
    model = Models.Fit2D(suffix='_5',
                         signal_1=Models.Gauss_pdf('Gx',
                                                   m_x.getMin(),
                                                   m_x.getMax(),
                                                   mass=m_x),
                         signal_2=Models.Gauss_pdf('Gy',
                                                   m_y.getMin(),
                                                   m_y.getMax(),
                                                   mass=m_y),
                         power1=1,
                         power2=1,
                         bkg2D=Models.PolyPos2Dsym_pdf('P2Ds', m_x, m_y, n=2),
                         sb=sb,
                         bs=sb)

    model.signal1.sigma.fix(m.error())
    model.signal2.sigma.fix(m.error())
    model.signal1.mean.fix(m.value())
    model.signal2.mean.fix(m.value())
    model.signal1.mean.fix(m.value())
    model.signal2.mean.fix(m.value())
    model.bkg1.tau.fix(0)
    model.bkg2.tau.fix(0)

    ## fit with fixed mass and sigma
    with rooSilent():
        result, frame = model.fitTo(dataset)
        model.signal1.sigma.release()
        model.signal2.sigma.release()
        model.signal1.mean.release()
        model.signal2.mean.release()
        result, frame = model.fitTo(dataset)

    if 0 != result.status() or 3 != result.covQual():
        logger.warning('Fit is not perfect MIGRAD=%d QUAL=%d ' %
                       (result.status(), result.covQual()))
        print result
    else:
        logger.info('S1xS2 : %20s' % result(model.ss)[0])
        logger.info('S1xB2 : %20s' % result(model.sb)[0])
        logger.info('B1xS2 : %20s' % result(model.bs)[0])
        logger.info('B1xB2 : %20s' % result(model.bb)[0])

    models.add(model)
Ejemplo n.º 11
0
def test_pbxpb_BBs():
    logger.info(
        'Non-factorizeable background component:  ( Gauss + expo*P1 ) (x) ( Gauss + expo*P1 ) + Sym(expo*P1)**2'
    )
    model = Models.Fit2D(suffix='_8',
                         signal_1=Models.Gauss_pdf('Gx',
                                                   m_x.getMin(),
                                                   m_x.getMax(),
                                                   mass=m_x),
                         signal_2=Models.Gauss_pdf('Gy',
                                                   m_y.getMin(),
                                                   m_y.getMax(),
                                                   mass=m_y),
                         power1=1,
                         power2=1,
                         bkg2D=Models.ExpoPol2Dsym_pdf('P2D8', m_x, m_y, n=1))

    model.signal1.sigma.fix(m.error())
    model.signal2.sigma.fix(m.error())
    model.signal1.mean.fix(m.value())
    model.signal2.mean.fix(m.value())
    model.signal1.mean.fix(m.value())
    model.signal2.mean.fix(m.value())
    model.bkg1.tau.fix(0)
    model.bkg2.tau.fix(0)

    ## fit with fixed mass and sigma
    with rooSilent():
        result, frame = model.fitTo(dataset)
        model.signal1.sigma.release()
        model.signal2.sigma.release()
        model.signal1.mean.release()
        model.signal2.mean.release()
        result, frame = model.fitTo(dataset)

    if 0 != result.status() or 3 != result.covQual():
        logger.warning('Fit is not perfect MIGRAD=%d QUAL=%d ' %
                       (result.status(), result.covQual()))
        print result
    else:
        logger.info('S1xS2 : %20s' % result(model.ss)[0])
        logger.info('S1xB2 : %20s' % result(model.sb)[0])
        logger.info('B1xS2 : %20s' % result(model.bs)[0])
        logger.info('B1xB2 : %20s' % result(model.bb)[0])

    models.add(model)
Ejemplo n.º 12
0
def test_const():

    logger.info(
        'Simplest (factorized) fit model:  ( Gauss + const ) x ( Gauss + const ) '
    )
    model = Models.Fit2D(signal_1=Models.Gauss_pdf('Gx',
                                                   m_x.getMin(),
                                                   m_x.getMax(),
                                                   mass=m_x),
                         signal_2=Models.Gauss_pdf('Gy',
                                                   m_y.getMin(),
                                                   m_y.getMax(),
                                                   mass=m_y))

    model.signal1.sigma.fix(m.error())
    model.signal2.sigma.fix(m.error())
    model.signal1.mean.fix(m.value())
    model.signal2.mean.fix(m.value())
    model.signal1.mean.fix(m.value())
    model.signal2.mean.fix(m.value())
    model.bkg1.tau.fix(0)
    model.bkg2.tau.fix(0)
    model.bkgA.tau.fix(0)
    model.bkgB.tau.fix(0)

    ## fit with fixed mass and sigma
    with rooSilent():
        result, frame = model.fitTo(dataset)
        model.signal1.sigma.release()
        model.signal2.sigma.release()
        model.signal1.mean.release()
        model.signal2.mean.release()
        result, frame = model.fitTo(dataset)

    if 0 != result.status() or 3 != result.covQual():
        logger.warning('Fit is not perfect MIGRAD=%d QUAL=%d ' %
                       (result.status(), result.covQual()))
        print result
    else:
        logger.info('S1xS2 : %20s' % result(model.ss)[0])
        logger.info('S1xB2 : %20s' % result(model.sb)[0])
        logger.info('B1xS2 : %20s' % result(model.bs)[0])
        logger.info('B1xB2 : %20s' % result(model.bb)[0])

    models.add(model)
Ejemplo n.º 13
0
def test_significance_toys():
    """Perform toy-study for significance of the signal 
    - generate `nToys` pseudoexperiments using background-only hypothesis 
    - fit each experiment with signal+background hypothesis
    - store  fit results
    - fill distributions for fit results
    """

    logger = getLogger('test_significance_toys')

    ## only background hypothesis
    bkg_only = Models.Bkg_pdf("BKG", xvar=mass, power=0, tau=0)

    signal = Models.Gauss_pdf('S', xvar=mass, mean=0.5, sigma=0.1)

    signal.mean.fix(0.4)
    signal.sigma.fix(0.1)

    ## signal + background hypothesis
    model = Models.Fit1D(signal=signal, background=1)
    model.background.tau.fix(0)

    results, stats = Toys.make_toys2(
        gen_pdf=bkg_only,
        fit_pdf=model,
        nToys=1000,
        data=[mass],
        gen_config={
            'nEvents': 100,
            'sample': True
        },
        fit_config={'silent': True},
        gen_pars={'tau_BKG': 0.},  ## initial values for generation 
        fit_pars={
            'B': 100,
            'S': 10,
            'phi0_Bkg_S': 0.0
        },  ## initial fit values for parameters 
        silent=True,
        progress=True)

    for p in stats:
        logger.info("Toys: %-20s : %s" % (p, stats[p]))

    h_S = ROOT.TH1F(hID(), '#S', 60, 0, 60)

    for r in results['S']:
        h_S.Fill(r)

    for h in (h_S, ):

        h.draw()
        logger.info("%s  :\n%s" % (h.GetTitle(), h.dump(30, 10)))
        time.sleep(1)
Ejemplo n.º 14
0
def test_morphing1():

    pdf1 = Models.Gauss_pdf('G1', xvar=mass, mean=10, sigma=1)
    pdf2 = Models.Gauss_pdf('G2', xvar=mass, mean=10, sigma=2)
    pdf3 = Models.Gauss_pdf('G3', xvar=mass, mean=10, sigma=3)
    pdf4 = Models.Gauss_pdf('G4', xvar=mass, mean=10, sigma=4)

    pdf = Morphing1D_pdf('M', {
        1.0: pdf1,
        2.0: pdf2,
        3.0: pdf3,
        4.0: pdf4,
    },
                         xvar=mass)

    for mu in vrange(1, 3, 6):
        pdf.mu = mu
        logger.info('Mu= %s' % mu)
        pdf.draw()

    r, f = pdf.fitHisto(h1, draw=True, nbins=100, silent=True)
    logger.info('Morphing: \n%s' % r.table(prefix="# "))
Ejemplo n.º 15
0
def test_transform():

    logger = getLogger('test_transform')

    if not 62000 <= ROOT.gROOT.GetVersionInt():
        logger.info("Not for this version of ROOT")
        return

    x = ROOT.RooRealVar('x', '', 1, 100000)
    mean = 1000
    sigma = 1000

    ## book very simple data set
    varset = ROOT.RooArgSet(x)
    dataset = ROOT.RooDataSet(dsID(), 'Test Data set', varset)
    while len(dataset) < 5000:
        v = random.gauss(mean, sigma)
        if v in x:
            x.value = v
            dataset.add(varset)

    dataset.add_var('lx', 'log10(x)')
    dataset.lx.setMin(0)
    dataset.lx.setMax(5)

    ## original PDF
    gauss = Models.Gauss_pdf('G',
                             xvar=x,
                             mean=(mean, mean / 2, mean * 2),
                             sigma=(sigma, sigma / 2, sigma * 2))

    with use_canvas('test_transform'), wait(1):
        r1, f1 = gauss.fitTo(dataset, draw=True, silent=True)
        logger.info('Fit x:\n%s' % r1.table())

    lx = dataset.lx
    LX = Fun1D(lx, lx)
    NX = 10**LX

    ## transformed PDF
    tgauss = TrPDF(pdf=gauss, new_var=NX)

    with use_canvas('test_transform'), wait(1):
        r2, f2 = tgauss.fitTo(dataset, draw=True, silent=True)
        logger.info('Fit log10(x):\n%s' % r2.table())
Ejemplo n.º 16
0
def fit_gaus():
    im = ROOT.RooRealVar('im', 'im', 2.42, 2.52)
    sig_ap = Models.Gauss_pdf('Gauss',
                              xvar=im,
                              mean=(2.46, 2.47),
                              sigma=(0.001, 0.01))
    bkg0 = Models.Bkg_pdf('bkg0', xvar=im, power=1.)

    model = Models.Fit1D(signal=sig_ap, background=bkg0)

    rfile = ROOT.TFile("../datasets/test_xic_100invpb.root", "READ")
    ds = rfile["da_lc"]
    ds = ds.reduce("im > 2.42 && im < 2.52")
    dh = (ds.reduce(ROOT.RooArgSet(im), "im>0")).binnedClone()

    r, w = model.fitTo(dh)
    r, w = model.fitTo(ds, draw=True, nbins=300, ncpu=4)

    pull = model.pull(ds)
    f, r, pull = model.draw(ds, nbins=100, residual='P', pull='P')
    return w, pull
Ejemplo n.º 17
0
        m_x.value = random.uniform(*m_x.minmax())
        m_y.value = m.gauss()
        dataset.add(varset)

## fill it : 1000 events  const * const *Gauss
    for i in range(0, N_bb):

        m_x.value = random.uniform(*m_x.minmax())
        m_y.value = random.uniform(*m_y.minmax())
        dataset.add(varset)

logger.info('Dataset: %s' % dataset)

## various fit components
signal_x1 = Models.Gauss_pdf('G1x',
                             xvar=m_x,
                             mean=m1.value(),
                             sigma=m1.error())
signal_y1 = signal_x1.clone(name='G1y', xvar=m_y)

signal_x2 = Models.Gauss_pdf(name='G2x',
                             xvar=m_x,
                             mean=m2.value(),
                             sigma=m2.error())
signal_y2 = signal_x2.clone(name='G2y', xvar=m_y)

bkg_x = make_bkg(-1, 'Bx', m_x)
bkg_y = bkg_x.clone(name='By', xvar=m_y)

# S(x)*S(y) component
ss_cmp = signal_x2 * signal_y2
Ejemplo n.º 18
0
def test_simfit4():

    # =========================================================================
    VARS = MakeVar()

    ## MC/DATA ratio for signal widths
    Rs = ROOT.RooRealVar('Rs', 'MC/DATA ratio for signal widths', 1.0, 0.2,
                         3.0)

    ## sigma for normalization peak: sigma from MC multiplied by a factor
    sigma_N = VARS.vars_multiply(Rs, sigma1, name='sigma_N')

    ## sigma for signal peak: sigma from MC multiplied by the same factor
    sigma_S = VARS.vars_multiply(Rs, sigma2, name='sigma_S')

    ## Normalization peak:
    signal_N = Models.Gauss_pdf('GN', xvar=mass1, mean=(3, 8), sigma=sigma_N)

    ## mean of low-statistics signal is constrained to the mean of high statistic signal
    mean_S = VARS.vars_sum(signal_N.mean, mean2 - mean1)

    ## low statistic signal :
    signal_S = Models.Gauss_pdf('GS', xvar=mass2, mean=mean_S, sigma=sigma_S)

    # =========================================================================
    ## model for fitting of normalization channel
    model_N = Models.Fit1D(suffix='N', signal=signal_N,
                           background=-2)  ## 2nd order positive polynomial
    model_N.S = NS1
    model_N.B = NB1

    ## model for fitting of low-statistic signal channel
    model_S = Models.Fit1D(suffix='S', signal=signal_S,
                           background=-2)  ## 2nd order positive polynomial

    model_S.S = NS2
    model_S.B = NB2

    # =========================================================================
    ## make fit for thew normalization channel only
    # =========================================================================
    rN, fN = model_N.fitTo(dataset1, draw=None, silent=True)
    rN, fN = model_N.fitTo(dataset1, draw=None, silent=True)
    rN, fN = model_N.fitTo(dataset1, draw=True, nbins=50, silent=True)

    logger.info('Fit results for normalization sample only: %s' % rN)

    # =========================================================================
    ## make fit for the low-statistic signal channel only
    # =========================================================================
    rS, fS = model_S.fitTo(dataset2, draw=None, silent=True)
    rS, fS = model_S.fitTo(dataset2, draw=None, silent=True)
    rS, fS = model_S.fitTo(dataset2, draw=True, nbins=50, silent=True)

    logger.info('Fit results for low-statistic signal only: %s' % rS)

    # =========================================================================
    ## combine data for simultaneous  fit
    # =========================================================================

    sample = ROOT.RooCategory('sample', 'sample', 'S', 'N')

    ## combine datasets
    from ostap.fitting.simfit import combined_data
    vars = ROOT.RooArgSet(mass1, mass2)
    dataset = combined_data(sample, vars, {'N': dataset1, 'S': dataset2})

    ## combine PDFs
    model_sim = Models.SimFit(sample, {'S': model_S, 'N': model_N}, name='X')

    # =========================================================================
    rC, fC = model_sim.fitTo(dataset, silent=True)
    rC, fC = model_sim.fitTo(dataset, silent=True)
    rC, fC = model_sim.fitTo(dataset, silent=True)

    fN = model_sim.draw('N', dataset, nbins=50)
    fS = model_sim.draw('S', dataset, nbins=50)

    logger.info('Combined fit  results are: %s ' % rC)

    logger.info(' Value |        Simple fit         |    Combined fit ')
    logger.info(' #N    | %25s | %-25s ' % (rS.SS * 1, rC.SS * 1))
    logger.info(' mean  | %25s | %-25s ' % (rS.mean_GN * 1, rC.mean_GN * 1))
    logger.info(' Rs    | %25s | %-25s ' % (rS.Rs * 1, rC.Rs * 1))
Ejemplo n.º 19
0
for i in range(0, 5000):
    mass.value = m.gauss()
    dataset0.add(varset0)

for i in range(0, 500):
    mass.value = random.uniform(mmin, mmax)
    dataset0.add(varset0)

logger.info('DATASET\n%s' % dataset0)

models = set()

## signal component
signal_gauss = Models.Gauss_pdf(
    name='Gauss',  ## the name 
    xvar=mass,  ## the variable 
    mean=m.value(),  ## mean value (fixed)
    sigma=m.error())  ## sigma      (fixed)

## construct composite model: signal + background
model_gauss = Models.Fit1D(
    signal=signal_gauss,
    background=Models.Bkg_pdf('BkgGauss', xvar=mass, power=0),
)

S = model_gauss.S
B = model_gauss.B


# =============================================================================
## gauss PDF
Ejemplo n.º 20
0
def test_fitting_components_3D():

    logger = getLogger('test_fitting_components_3D')
    ## make simple test mass
    m_x = ROOT.RooRealVar('mass_x', 'Some test mass(X)', 0, 10)
    m_y = ROOT.RooRealVar('mass_y', 'Some test mass(Y)', 0, 10)
    m_z = ROOT.RooRealVar('mass_z', 'Some test mass(z)', 0, 10)

    ## book very simple data set
    varset = ROOT.RooArgSet(m_x, m_y, m_z)
    dataset = ROOT.RooDataSet(dsID(), 'Test Data set-1', varset)

    m1 = VE(3, 0.10**2)
    m2 = VE(7, 0.20**2)

    ## fill it

    N_sss = 5000
    N_ssb = 500
    N_sbs = 500
    N_bss = 1000

    N_bbs = 500
    N_bsb = 100
    N_sbb = 100

    N_bbb = 250

    random.seed(0)

    ## fill it : 5000 events  Gauss * Gauss *Gauss
    for m in (m1, m2):

        ##  S x S x S
        for i in range(N_sss):

            m_x.value = m.gauss()
            m_y.value = m.gauss()
            m_z.value = m.gauss()

            dataset.add(varset)

        ## S x S x B
        for i in range(0, N_bss):

            m_x.value = m.gauss()
            m_y.value = m.gauss()
            m_z.value = random.uniform(*m_z.minmax())

            dataset.add(varset)

        ## S x B x S
        for i in range(N_ssb):

            m_x.value = m.gauss()
            m_y.value = random.uniform(*m_y.minmax())
            m_z.value = m.gauss()

            dataset.add(varset)

        ## B x S x S
        for i in range(N_sbs):
            m_x.value = random.uniform(*m_x.minmax())
            m_y.value = m.gauss()
            m_z.value = m.gauss()
            dataset.add(varset)

        ## B x B X S
        for i in range(N_sbb):

            m_x.value = random.uniform(*m_x.minmax())
            m_y.value = random.uniform(*m_y.minmax())
            m_z.value = m.gauss()
            dataset.add(varset)

        ## B  x S x B
        for i in range(N_bsb):

            m_x.value = random.uniform(*m_x.minmax())
            m_y.value = m.gauss()
            m_z.value = random.uniform(*m_y.minmax())
            dataset.add(varset)

        ## S x B x B
        for i in range(N_sbb):

            m_x.value = m.gauss()
            m_y.value = random.uniform(*m_y.minmax())
            m_z.value = random.uniform(*m_y.minmax())

            dataset.add(varset)

        ## B x B x B
        for i in range(N_bbb):

            m_x.value = random.uniform(*m_x.minmax())
            m_y.value = random.uniform(*m_y.minmax())
            m_z.value = random.uniform(*m_y.minmax())

            dataset.add(varset)

    logger.info('Dataset:\n%s' % dataset.table(prefix='# '))

    ## various fit components for main fit model :

    signal_x1 = Models.Gauss_pdf('G1x',
                                 xvar=m_x,
                                 mean=m1.value(),
                                 sigma=m1.error())
    signal_y1 = signal_x1.clone(name='G1y', xvar=m_y)
    signal_z1 = signal_x1.clone(name='G1z', xvar=m_z)

    bkg_x = make_bkg(-1, 'Bx', m_x)
    bkg_y = bkg_x.clone(name='By', xvar=m_y)
    bkg_z = bkg_x.clone(name='Bz', xvar=m_z)

    ## construct other components

    signal_x2 = Models.Gauss_pdf(name='G2x',
                                 xvar=m_x,
                                 mean=m2.value(),
                                 sigma=m2.error())
    signal_y2 = signal_x2.clone(name='G2y', xvar=m_y)
    signal_z2 = signal_x2.clone(name='G2z', xvar=m_z)

    ## S(x) * S(y) components
    ss_cmp = signal_x2 * signal_y2

    ## S(x) * B(y) component
    sb_cmp = signal_x2 * bkg_y

    ## B(x) * S(y) component
    bs_cmp = bkg_x * signal_y2

    ## B(x) * B(y) component
    bb_cmp = bkg_x * bkg_y

    ## S(x) * S(y) * S(z) component
    sss_cmp = ss_cmp * signal_z2

    ## S(x) * S(y) * B(z) component
    ssb_cmp = ss_cmp * bkg_z

    ## S(x) * B(y) * S(z) component
    sbs_cmp = sb_cmp * signal_z2

    ## S(x) * B(y) * S(z) component
    bss_cmp = bs_cmp * signal_z2

    ## S(x) * B(y) * B(z) component
    sbb_cmp = sb_cmp * bkg_z

    ## B(x) * S(y) * B(z) component
    bsb_cmp = bs_cmp * bkg_z

    ## B(x) * B(y) * S(z) component
    bbs_cmp = bs_cmp * signal_z2

    model = Models.Fit3D(
        name='fit_comp',
        signal_x=signal_x1,
        signal_y=signal_y1,
        signal_z=signal_z1,
        bkg_1x=bkg_x,
        bkg_1y=bkg_y,
        bkg_1z=bkg_z,
        suffix="_1",
        ##
        components=[
            sss_cmp, ssb_cmp, sbs_cmp, bss_cmp, sbb_cmp, bsb_cmp, bbs_cmp
        ])

    model.SSS = N_sss

    model.SSB = N_ssb
    model.SBS = N_sbs
    model.BSS = N_bss

    model.BBS = N_bbs
    model.BSB = N_bsb
    model.SBB = N_sbb

    model.BBB = N_bbb

    model.C = N_sss, N_ssb, N_sbs, N_sbb, N_bss, N_sbs, N_bbs

    r = model.fitTo(dataset, silent=True)
    r = model.fitTo(dataset, silent=True)

    with use_canvas('test_fitting_components_3D'):
        with wait(2):
            model.draw1(dataset)
        with wait(2):
            model.draw2(dataset)
        with wait(2):
            model.draw3(dataset)

    logger.info('Model %s Fit result\n%s ' %
                (model.name, r.table(prefix='# ')))
Ejemplo n.º 21
0
def test_toys_simfit_1():

    ## make simple test mass
    mass = ROOT.RooRealVar('test_mass', 'Some test mass', 0, 5)

    ## book very simple data set:
    varset1 = ROOT.RooArgSet(mass)
    dataset1 = ROOT.RooDataSet(dsID(), 'Test Data set-1', varset1)

    ## book very simple data set:
    varset2 = ROOT.RooArgSet(mass)
    dataset2 = ROOT.RooDataSet(dsID(), 'Test Data set-2', varset2)

    ## high statistic, low-background "control channel"
    mean1 = 2.0
    sigma1 = 0.50
    NS1 = 1000
    NB1 = 250

    for i in range(NS1):
        v1 = random.gauss(mean1, sigma1)
        if v1 in mass:
            mass.setVal(v1)
            dataset1.add(varset1)

    for i in range(NB1):
        v1 = random.uniform(0, 5)
        if v1 in mass:
            mass.setVal(v1)
            dataset1.add(varset1)

    ## low statistic, high-background "control channel"
    NS2 = 250
    NB2 = 1000
    mean2 = mean1 + 1.0
    sigma2 = sigma1 * 0.5

    for i in range(NS2):
        v2 = random.gauss(mean2, sigma2)
        if v2 in mass:
            mass.setVal(v2)
            dataset2.add(varset2)
    for i in range(NB2):
        v2 = random.uniform(0, 5)
        if v2 in mass:
            mass.setVal(v2)
            dataset2.add(varset2)

    signal1 = Models.Gauss_pdf('G1',
                               xvar=mass,
                               mean=(0.5, 2.5),
                               sigma=(0.1, 1.0))

    model1 = Models.Fit1D(suffix='M1', signal=signal1, background=-1)
    model1.S = NS1
    model1.B = NB1

    mean2 = signal1.vars_add(signal1.mean, 1.0)
    sigma2 = signal1.vars_multiply(signal1.sigma, 0.5)

    signal2 = Models.Gauss_pdf('G2', xvar=mass, mean=mean2, sigma=sigma2)

    model2 = Models.Fit1D(suffix='M2',
                          signal=signal2,
                          background=model1.background)
    model2.S = NS2
    model2.B = NB2

    # =========================================================================
    ## fit 1
    r1, f1 = model1.fitTo(dataset1, draw=True, nbins=50, silent=True)

    ## fit 2
    r2, f2 = model2.fitTo(dataset2, draw=True, nbins=50, silent=True)
    # =========================================================================

    ## combine data
    sample = ROOT.RooCategory('sample', 'sample', 'A', 'B')

    ## combine datasets
    from ostap.fitting.simfit import combined_data
    vars = ROOT.RooArgSet(mass)
    dataset = combined_data(sample, vars, {'A': dataset1, 'B': dataset2})

    ## combine PDFs
    model_sim = Models.SimFit(sample, {'A': model1, 'B': model2}, name='X')

    # =========================================================================
    r, f = model_sim.fitTo(dataset, silent=True)
    r, f = model_sim.fitTo(dataset, silent=True)

    fA = model_sim.draw('A', dataset, nbins=50)
    fB = model_sim.draw('B', dataset, nbins=50)

    logger.info('Fit  results are: %s ' % r.table(prefix="# "))

    ## Make toys
    results, stats = Toys.make_toys(pdf=model_sim,
                                    nToys=100,
                                    data=[mass],
                                    gen_config={
                                        'nEvents': (NS1 + NB1, NS2 + NB2),
                                        'sample': True
                                    },
                                    fit_config={'silent': True},
                                    init_pars={
                                        'mean_G1': mean1,
                                        'BM1': NB1,
                                        'BM2': NB2,
                                        'sigma_G1': sigma1,
                                        'SM1': NS1,
                                        'SM2': NS2,
                                        'phi0_Bkg_FitG1_M1': 0
                                    },
                                    silent=True,
                                    progress=True)
Ejemplo n.º 22
0
# =============================================================================
# logging
# =============================================================================
from ostap.logger.logger import getLogger
if '__main__' == __name__ or '__builtin__' == __name__:
    logger = getLogger('test_fitting_toys')
else:
    logger = getLogger(__name__)
# =============================================================================
import ROOT, time
from ostap.core.pyrouts import hID
import ostap.fitting.models as Models
import ostap.parallel.parallel_toys as Toys

mass = ROOT.RooRealVar('mass', '', 0, 1)
gen_gauss = Models.Gauss_pdf('GG', xvar=mass)
fit_gauss = Models.Gauss_pdf('FG', xvar=mass)
gen_gauss.mean = 0.4
gen_gauss.sigma = 0.1


# ==============================================================================
## Perform toy-study for possible fit bias and correct uncertainty evaluation
#  - generate <code>nToys</code> pseudoexperiments with some PDF <code>pdf</code>
#  - fit teach experiment with the same PDF
#  - store  fit results
#  - calculate staistics of pulls
#  - fill distributions for fit results
#  - fill distribution of pulls
def test_parallel_toys():
    """Perform toys-study for possible fit bias and correct uncertainty evaluation
Ejemplo n.º 23
0
def test_simfit4():

    logger = getLogger('test_simfit4')
    # =========================================================================
    VARS = MakeVar()

    ## MC/DATA ratio for signal widths
    Rs = ROOT.RooRealVar('Rs', 'MC/DATA ratio for signal widths', 1.0, 0.2,
                         3.0)

    ## sigma for normalization peak: sigma from MC multiplied by a factor
    sigma_N = VARS.vars_multiply(Rs, sigma1, name='sigma_N')

    ## sigma for signal peak: sigma from MC multiplied by the same factor
    sigma_S = VARS.vars_multiply(Rs, sigma2, name='sigma_S')

    ## Normalization peak:
    signal_N = Models.Gauss_pdf('GN', xvar=mass1, mean=(3, 8), sigma=sigma_N)

    ## mean of low-statistics signal is constrained to the mean of high statistic signal
    mean_S = VARS.vars_sum(signal_N.mean, mean2 - mean1)

    ## low statistic signal :
    signal_S = Models.Gauss_pdf('GS', xvar=mass2, mean=mean_S, sigma=sigma_S)

    # =========================================================================
    ## 3rd order positive polynomial
    bkg_N = Models.make_bkg(-3, 'Bkg_N', mass1)
    ## model for fitting of normalization channel
    model_N = Models.Fit1D(suffix='N', signal=signal_N, background=bkg_N)
    model_N.S = NS1
    model_N.B = NB1

    ## 3rd order positive polynomial
    bkg_S = Models.make_bkg(-3, 'Bkg_S', mass2)
    ## model for fitting of low-statistic signal channel
    model_S = Models.Fit1D(suffix='S', signal=signal_S, background=bkg_S)

    model_S.S = NS2
    model_S.B = NB2

    # =========================================================================
    ## make fit for thew normalization channel only
    # =========================================================================
    with use_canvas('test_simfit4'):
        rN, fN = model_N.fitTo(dataset1, draw=None, silent=True)
        rN, fN = model_N.fitTo(dataset1, draw=None, silent=True)
        rN, fN = model_N.fitTo(dataset1, draw=True, nbins=50, silent=True)

    title = 'Fit to high-statistic normalisation sample'
    logger.info('Fit results for normalization sample only: %s' %
                rN.table(title=title, prefix='# '))

    # =========================================================================
    ## make fit for the low-statistic signal channel only
    # =========================================================================
    with use_canvas('test_simfit4'):
        rS, fS = model_S.fitTo(dataset2, draw=None, silent=True)
        rS, fS = model_S.fitTo(dataset2, draw=None, silent=True)
        rS, fS = model_S.fitTo(dataset2, draw=True, nbins=50, silent=True)

    title = 'Fit to low-statistics sample'
    logger.info('Fit results for low-statistic signal only:\n%s' %
                rS.table(title=title, prefix='# '))

    # =========================================================================
    ## combine data for simultaneous  fit
    # =========================================================================

    sample = ROOT.RooCategory('sample', 'sample', 'S', 'N')

    ## combine datasets
    from ostap.fitting.simfit import combined_data
    vars = ROOT.RooArgSet(mass1, mass2)
    dataset = combined_data(sample, vars, {'N': dataset1, 'S': dataset2})

    ## combine PDFs
    model_sim = Models.SimFit(sample, {'S': model_S, 'N': model_N}, name='X')

    # =========================================================================
    rC, fC = model_sim.fitTo(dataset, silent=True)
    rC, fC = model_sim.fitTo(dataset, silent=True)
    rC, fC = model_sim.fitTo(dataset, silent=True)
    rC, fC = model_sim.fitTo(dataset, silent=True)

    with use_canvas('test_simfit4'):
        with wait(1):
            fN = model_sim.draw('N', dataset, nbins=50)
        with wait(1):
            fS = model_sim.draw('S', dataset, nbins=50)

    title = 'Simultaneous fit'
    logger.info('Combined fit  results are:\n%s ' %
                rC.table(title=title, prefix='#'))
Ejemplo n.º 24
0
def test_splot():

    logger = getLogger('test_splot')

    ## make simple test mass
    mass = ROOT.RooRealVar('test_mass', 'Some test mass', 0, 10)
    tau = ROOT.RooRealVar('test_tau', 'Some test tau', 0, 10)

    ## book very simple data set
    varset = ROOT.RooArgSet(mass, tau)
    dataset = ROOT.RooDataSet(dsID(), 'Test Data set', varset)

    mmin, mmax = mass.minmax()
    tmin, tmax = tau.minmax()

    m0 = VE(3, 0.2**2)
    taus = 6
    taub = 0.4
    NS = 5000
    NB = 5000

    ## generate signal
    for i in range(0, NS):
        m = m0.gauss()
        while not mmin < m < mmax:
            m = m0.gauss()
        t = random.expovariate(1. / taus)
        while not tmin < t < tmax:
            t = random.expovariate(1. / taus)
        mass.value = m
        tau.value = t
        dataset.add(varset)

    ## generate background
    for i in range(0, NB):
        m = random.expovariate(1. / 5)
        while not mmin < m < mmax:
            m = random.expovariate(1. / 3)
        t = random.expovariate(1. / taub)
        while not tmin < t < tmax:
            t = random.expovariate(1. / taus)
        mass.value = m
        tau.value = t
        dataset.add(varset)

    logger.info("Original dataset\n%s" % dataset.table(prefix='# '))

    signal = Models.Gauss_pdf('G',
                              xvar=mass,
                              mean=(3, 2, 4),
                              sigma=(0.2, 0.1, 0.5))

    model = Models.Fit1D(signal=signal, background=1)
    model.S = NS
    model.B = NB

    signal.mean.fix(m0.value())
    signal.sigma.fix(m0.error())
    model.fitTo(dataset, silent=True)
    signal.mean.release()
    signal.sigma.release()

    model.fitTo(dataset, silent=True)
    with use_canvas('test_splot'):
        r, f = model.fitTo(dataset, silent=True, draw=True, nbins=50)
    logger.info("Mass fit : fit results\n%s" %
                r.table(title='Mass fit', prefix='# '))

    ## make splot analysis
    model.sPlot(dataset)
    logger.info("Dataset after sPlot\n%s" % dataset.table(prefix='# '))

    ## make signal-weighted dataset
    ds_signal = dataset.makeWeighted('S_sw')

    ## make background-weighted dataset
    ds_bkg = dataset.makeWeighted('B_sw')

    logger.info("Signal-weighted dataset\n%s" % ds_signal.table(prefix='# '))
    logger.info("Background-weighted dataset\n%s" % ds_bkg.table(prefix='# '))

    ##  make exponential fits fot signal and background samples
    TS = Models.Bkg_pdf('TS', xvar=tau, power=0)
    TB = Models.Bkg_pdf('TB', xvar=tau, power=0)

    TS.fitTo(ds_signal, silent=True)
    TS.fitTo(ds_signal, silent=True)
    with use_canvas('test_splot'):
        rS, f = TS.fitTo(ds_signal, silent=True, draw=True, nbins=100)
    logger.info("Tau/signal fit : fit results\n%s" %
                rS.table(title='Tau signal fit', prefix='# '))

    TB.fitTo(ds_bkg, silent=True)
    TB.fitTo(ds_bkg, silent=True)
    with use_canvas('test_splot'):
        rB, f = TB.fitTo(ds_bkg, silent=True, draw=True, nbins=100)
    logger.info("Tau/bkg fit : fit results\n%s" %
                rB.table(title='Tau bkg fit', prefix='# '))

    logger.info("Tau/signal : %28s vs %s" % (abs(1.0 / rS.tau_TS), taus))
    logger.info("Tau/bkg    : %28s vs %s" % (abs(1.0 / rB.tau_TB), taub))
Ejemplo n.º 25
0
from ostap.logger.logger import getLogger
if '__main__' ==  __name__ : logger = getLogger ( 'ostap.test_math_interpolation2' ) 
else                       : logger = getLogger ( __name__                         )
# =============================================================================

# =============================================================================
## def test_fitresults ()  :
if 1 < 2 : 

    sigma = lambda x : 5 * math.exp  ( x / 100.0 )

    logger = getLogger ( 'test_fitresults' )
    logger.info ( 'Test interpolation for fit results' )
    
    g1 = M.Gauss_pdf ( 'G' ,
                       xvar  = ( 0 ,    100   ) ,
                       mean  = ( 50 , 1 , 99  ) ,
                       sigma = ( 10 ,  1 , 20  ) )
    g1.mean.fix ( 50 )

    results = {}
    
    low, high, N = 0 , 100 ,  8
    
    gr    = ROOT.TGraphErrors ( N + 1 ) 
    ## for i , m in enumerate ( vrange ( low , high , N ) ) :
    ## for i , m in enumerate ( chebyshev_abscissas ( low , high , N ) ) :
    for i , m in enumerate ( lobatto_abscissas ( low , high , N ) ) :
        
        g1.sigma.fix ( sigma ( m ) )
        g1.mean.fix ( 50 )
        ds = g1.generate ( 5000 )
Ejemplo n.º 26
0
# Prepare dataset and datahist
# Prepare a composite model
import ostap.fitting.models as Models
x = ROOT.RooRealVar("x","x",-12,12)
#
sig = Models.Gauss_pdf( 'sig', xvar=x,
                              mean      = (0, -1, 1) ,
                              sigma     = (1,0.001, 3.) )
#
bkg = Models.Gauss_pdf( 'bkg', xvar=x,
                              mean      = (0, -1, 1) ,
                              sigma     = (4,3.5, 10.) )
#
model = Models.Fit1D   ( signal = sig , background = bkg , extended = False )
#
ds = sig.generate(100)
ds = ds + bkg.generate(150)
# Fit
r, w = model.fitTo( ds , draw=True, silent=True)
print(r)
w.Draw()
canvas >> "TEMP"
nll , f1 = model.draw_nll ( 'sigma_sig' ,  ds )
f1.Draw()
canvas >> "TEMP"
nllp , f2 = model.draw_nll ( 'sigma_sig' ,  ds, profile = True )
f1.Draw()
f2.Draw("same")
canvas >> "TEMP"
Ejemplo n.º 27
0
    m_y.value = m.gauss()
    dataset.add(varset)

## fill it : 5000 events  const * const
for i in range(0, N_bb):

    m_x.value = random.uniform(*m_x.minmax())
    m_y.value = random.uniform(*m_y.minmax())
    dataset.add(varset)

logger.info('Dataset:%s ' % dataset)

models = set()
# =============================================================================

signal1 = Models.Gauss_pdf('Gx', xvar=m_x)
signal2 = Models.Gauss_pdf('Gy', xvar=m_y)
signal2s = signal1.clone(name='GyS', xvar=m_y)

signal1.mean = m.value()
signal1.sigma = m.error()
signal2.mean = m.value()
signal2.sigma = m.error()

knots = std.vector('double')()
knots.push_back(m_x.xmin())
knots.push_back(0.5 * (m_x.xmin() + m_x.xmax()))
knots.push_back(m_x.xmax())
spline1 = Ostap.Math.BSpline(knots, 2)

Ejemplo n.º 28
0
from ostap.core.core import VE
from ostap.utils.timing import timing
from ostap.plotting.canvas import use_canvas
from ostap.utils.utils import wait
# =============================================================================
# logging
# =============================================================================
from ostap.logger.logger import getLogger
if '__main__' == __name__ or '__builtin__' == __name__:
    logger = getLogger('test_fitting_constraints')
else:
    logger = getLogger(__name__)
# =============================================================================
## make
x = ROOT.RooRealVar('x', 'test', 0, 10)
signal = Models.Gauss_pdf('Gauss', xvar=x, mean=(5, 2, 8), sigma=(1, 0.01, 5))
background = Models.Bkg_pdf('Bkg', xvar=x, power=1)
background.tau.fix(0)

model = Models.Fit1D(signal=signal, background=background)
model.S = 100
model.B = 1000

data = model.generate(4 * 1100)


# =============================================================================
# use some functions  to parameterize efficiciency
def test_constraint():

    logger = getLogger('test_constraint')
Ejemplo n.º 29
0
w2 = VE(6.0, 4**2)
n1 = VE(2.0, 1**2)
n2 = VE(4.0, 1**2)

for i in xrange(1000):
    for w in (w1, w2, n1, n2):
        v = w.gauss()
        if v in mass:
            mass.value = v
            dataset.add(varset)

logger.info('Dataset: %s' % dataset)

## various fit components

signal_1 = Models.Gauss_pdf('G1', xvar=mass, mean=m1.value(), sigma=m1.error())
signal_2 = Models.Gauss_pdf('G2', xvar=mass, mean=m2.value(), sigma=m2.error())
signal_3 = Models.Gauss_pdf('G3', xvar=mass, mean=m3.value(), sigma=m3.error())

wide_1 = Models.Gauss_pdf('GW1', xvar=mass, mean=4.0, sigma=4)
wide_2 = Models.Gauss_pdf('GW2', xvar=mass, mean=6.0, sigma=4)

narrow_1 = Models.Gauss_pdf('GN1', xvar=mass, mean=2.0, sigma=1)
narrow_2 = Models.Gauss_pdf('GN2', xvar=mass, mean=4.0, sigma=1)


# =============================================================================
## Test     extended multi-component fit'
def test_extended1():

    logger.info('Test     extended multi-component fit')
Ejemplo n.º 30
0
from ostap.logger.logger import getLogger
if '__main__' == __name__ or '__builtin__' == __name__:
    logger = getLogger('test_fitting_jackknife')
else:
    logger = getLogger(__name__)
# =============================================================================
from ostap.core.pyrouts import hID, VE
import ostap.fitting.models as Models
import ostap.fitting.toys as Toys
import ostap.histos.histos
from ostap.utils.timing import timing
from ostap.plotting.canvas import use_canvas
from ostap.utils.utils import wait
# =============================================================================
mass = ROOT.RooRealVar('mass', '', 0, 1)
gauss = Models.Gauss_pdf('G', xvar=mass)
gauss.mean = 0.4
gauss.sigma = 0.1
## model       = Models.Fit1D ( signal = gauss )
## model.S     = 100
## model.B     = 100
model = gauss


# ==============================================================================
## Perform jackknife study for possible fit bias and correct uncertainty evaluation
def test_jackknife():
    """Perform toys-study for possible fit bias and correct uncertainty evaluation
    - generate `nToys` pseudoexperiments with some PDF `pdf`
    - fit teach experiment with the same PDF
    - store  fit results