예제 #1
0
def main(argv):

    clock = TStopwatch()

    argc = len(argv)

    if (argc != 5):
        return usage()

    fileName = argv[1]
    the_type = argv[2]
    requireTree = argv[3]
    verbosity = argv[4]

    if the_type != "event" and the_type != "basket":
        return usage()

    if requireTree != "true" and requireTree != "false":
        return usage()

    if verbosity == "on":
        msg.setLevel(logging.DEBUG)
    elif verbosity == "off":
        msg.setLevel(logging.INFO)
    else:
        return usage()

    rc = checkFile(fileName, the_type, requireTree)
    msg.debug('Returning %s' % rc)

    clock.Stop()
    clock.Print()

    return rc
예제 #2
0
    def execute(self, ws, debug = 0):
        print self.legend, 'Profile Likelihood calculation started...'

        # time the action
        t = TStopwatch()
        t.Start()

        # model config is guaranteed to be here
        # the action won't configure without it
        # and this code will never run unless valid model config is found
        mconf = ws.obj(self._model_config_name)
            
        _poi = mconf.GetParametersOfInterest()

        plcInt = self._plc.GetInterval()

        # stop watch and print how long it took to get the interval
        t.Print()

        # iterate over all parameters of interest and print out the intervals
        # (could there be more than one?)
        _iter = _poi.createIterator()
        while True:
            _poi_name = _iter().GetTitle()
            
            lower_limit = plcInt.LowerLimit( _poi[_poi_name] )
            upper_limit = plcInt.UpperLimit( _poi[_poi_name] )
            
            print self.legend, 'Profile Likelihood interval for', _poi_name, 'is ['+ \
                  str(lower_limit) + ', ' + \
                  str(upper_limit) + ']'

            if _iter.Next() == None:
                break
            

        if self._scan_plot:
            # draw scan plot

            print self.legend, 'making the likelihood scan plot'
            _plot_name = _poi_name+'_plc_scan_exost.'+self._plot_format
            c1 = TCanvas("c1", "c1", 600, 600)
            plcPlot = RooStats.LikelihoodIntervalPlot(plcInt)
            gROOT.SetStyle("Plain")
            plcPlot.Draw()
            c1.SaveAs(_plot_name)
            
        return (lower_limit, upper_limit)
예제 #3
0
def main(argv):

    import logging
    msg = logging.getLogger(__name__)
    ch = logging.StreamHandler(sys.stdout)
    #    ch.setLevel(logging.DEBUG)
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    ch.setFormatter(formatter)
    msg.addHandler(ch)

    clock = TStopwatch()

    argc = len(argv)

    if (argc != 5):
        return usage()

    fileName = argv[1]
    type = argv[2]
    tree = argv[3]
    verbosity = argv[4]

    if type != "event" and type != "basket":
        return usage()

    if tree == "true":
        requireTree = True
    elif tree == "false":
        requireTree = False
    else:
        return usage()

    if verbosity == "on":
        msg.setLevel(logging.DEBUG)
    elif verbosity == "off":
        msg.setLevel(logging.INFO)
    else:
        return usage()

    rc = checkFile(fileName, type, requireTree, msg)
    msg.debug('Returning %s' % rc)

    clock.Stop()
    clock.Print()

    return rc
예제 #4
0
    def execute(self, ws, debug=0):
        print self.legend, 'Feldman-Cousins calculation started...'

        # time the action
        t = TStopwatch()
        t.Start()

        # model config is guaranteed to be here
        # the action won't configure without it
        # and this code will never run unless valid model config is found
        mconf = ws.obj(self._model_config_name)

        _poi = mconf.GetParametersOfInterest()

        fcInt = self._fc.GetInterval()

        # stop watch and print how long it took to get the interval
        t.Print()

        # iterate over all parameters of interest and print out the intervals
        # (could there be more than one?)
        _iter = _poi.createIterator()
        while True:
            _poi_name = _iter().GetTitle()

            lower_limit = fcInt.LowerLimit(_poi[_poi_name])
            upper_limit = fcInt.UpperLimit(_poi[_poi_name])

            print self.legend, 'Feldman-Cousins interval for', _poi_name, 'is ['+ \
                  str(lower_limit) + ', ' + \
                  str(upper_limit) + ']'

            if _iter.Next() == None:
                break

        return (lower_limit, upper_limit)
예제 #5
0
def main():

    try:
        # Retrive command line options
        shortopts = "m:i:t:o:vh?"
        longopts = [
            "methods=", "inputfile=", "inputtrees=", "outputfile=", "verbose",
            "help", "usage"
        ]
        opts, args = getopt.getopt(sys.argv[1:], shortopts, longopts)

    except getopt.GetoptError:
        # Print help information and exit:
        print "ERROR: unknown options in argument %s" % sys.argv[1:]
        usage()
        sys.exit(1)

    infname = DEFAULT_INFNAME
    treeNameSig = DEFAULT_TREESIG
    treeNameBkg = DEFAULT_TREEBKG
    outfname = DEFAULT_OUTFNAME
    methods = DEFAULT_METHODS
    verbose = False
    for o, a in opts:
        if o in ("-?", "-h", "--help", "--usage"):
            usage()
            sys.exit(0)
        elif o in ("-m", "--methods"):
            methods = a
        elif o in ("-i", "--inputfile"):
            infname = a
        elif o in ("-o", "--outputfile"):
            outfname = a
        elif o in ("-t", "--inputtrees"):
            a.strip()
            trees = a.rsplit(' ')
            trees.sort()
            trees.reverse()
            if len(trees) - trees.count('') != 2:
                print "ERROR: need to give two trees (each one for signal and background)"
                print trees
                sys.exit(1)

            treeNameSig = trees[0]
            treeNameBkg = trees[1]
        elif o in ("-v", "--verbose"):
            verbose = True

    # Print methods
    mlist = methods.replace(' ', ',').split(',')
    print "=== TMVApplication: use method(s)..."
    for m in mlist:
        if m.strip() != '':
            print "=== - <%s>" % m.strip()

    # Import ROOT classes
    from ROOT import gSystem, gROOT, gApplication, TFile, TTree, TCut, TH1F, TStopwatch

    # check ROOT version, give alarm if 5.18
    if gROOT.GetVersionCode() >= 332288 and gROOT.GetVersionCode() < 332544:
        print "*** You are running ROOT version 5.18, which has problems in PyROOT such that TMVA"
        print "*** does not run properly (function calls with enums in the argument are ignored)."
        print "*** Solution: either use CINT or a C++ compiled version (see TMVA/macros or TMVA/examples),"
        print "*** or use another ROOT version (e.g., ROOT 5.19)."
        sys.exit(1)

    # Logon not automatically loaded through PyROOT (logon loads TMVA library) load also GUI
    gROOT.SetMacroPath("../macros/")
    gROOT.Macro("../macros/TMVAlogon.C")

    # Import TMVA classes from ROOT
    from ROOT import TMVA

    # Create the Reader object
    reader = TMVA.Reader("!Color")

    # Create a set of variables and declare them to the reader
    # - the variable names must corresponds in name and type to
    # those given in the weight file(s) that you use

    # what to do ???
    var1 = array('f', [0])
    var2 = array('f', [0])
    var3 = array('f', [0])
    var4 = array('f', [0])
    reader.AddVariable("var1+var2", var1)
    reader.AddVariable("var1-var2", var2)
    reader.AddVariable("var3", var3)
    reader.AddVariable("var4", var4)

    # book the MVA methods
    dir = "weights/"
    prefix = "TMVAnalysis_"

    for m in mlist:
        reader.BookMVA(m + " method", dir + prefix + m + ".weights.txt")

    #######################################################################
    # For an example how to apply your own plugin method, please see
    # TMVA/macros/TMVApplication.C
    #######################################################################

    # Book output histograms
    nbin = 80

    histList = []
    for m in mlist:
        histList.append(TH1F(m, m, nbin, -3, 3))

    # Book example histogram for probability (the other methods would be done similarly)
    if "Fisher" in mlist:
        probHistFi = TH1F("PROBA_MVA_Fisher", "PROBA_MVA_Fisher", nbin, 0, 1)
        rarityHistFi = TH1F("RARITY_MVA_Fisher", "RARITY_MVA_Fisher", nbin, 0,
                            1)

    # Prepare input tree (this must be replaced by your data source)
    # in this example, there is a toy tree with signal and one with background events
    # we'll later on use only the "signal" events for the test in this example.
    #
    fname = "./tmva_example.root"
    print "--- Accessing data file: %s" % fname
    input = TFile.Open(fname)
    if not input:
        print "ERROR: could not open data file: %s" % fname
        sys.exit(1)

    #
    # Prepare the analysis tree
    # - here the variable names have to corresponds to your tree
    # - you can use the same variables as above which is slightly faster,
    #   but of course you can use different ones and copy the values inside the event loop
    #
    print "--- Select signal sample"
    theTree = input.Get("TreeS")
    userVar1 = array('f', [0])
    userVar2 = array('f', [0])
    theTree.SetBranchAddress("var1", userVar1)
    theTree.SetBranchAddress("var2", userVar2)
    theTree.SetBranchAddress("var3", var3)
    theTree.SetBranchAddress("var4", var4)

    # Efficiency calculator for cut method
    nSelCuts = 0
    effS = 0.7

    # Process the events
    print "--- Processing: %i events" % theTree.GetEntries()
    sw = TStopwatch()
    sw.Start()
    for ievt in range(theTree.GetEntries()):

        if ievt % 1000 == 0:
            print "--- ... Processing event: %i" % ievt

        # Fill event in memory
        theTree.GetEntry(ievt)

        # Compute MVA input variables
        var1[0] = userVar1[0] + userVar2[0]
        var2[0] = userVar1[0] - userVar2[0]

        # Return the MVAs and fill to histograms
        if "CutsGA" in mlist:
            passed = reader.EvaluateMVA("CutsGA method", effS)
            if passed:
                nSelCuts = nSelCuts + 1

        # Fill histograms with MVA outputs
        for h in histList:
            h.Fill(reader.EvaluateMVA(h.GetName() + " method"))

        # Retrieve probability instead of MVA output
        if "Fisher" in mlist:
            probHistFi.Fill(reader.GetProba("Fisher method"))
            rarityHistFi.Fill(reader.GetRarity("Fisher method"))

    # Get elapsed time
    sw.Stop()
    print "--- End of event loop: %s" % sw.Print()

    # Return computed efficeincies
    if "CutsGA" in mlist:
        eff = float(nSelCuts) / theTree.GetEntries()
        deff = math.sqrt(eff * (1.0 - eff) / theTree.GetEntries())
        print "--- Signal efficiency for Cuts method : %.5g +- %.5g (required was: %.5g)" % (
            eff, deff, effS)

        # Test: retrieve cuts for particular signal efficiency
        mcuts = reader.FindMVA("CutsGA method")
        cutsMin = array('d', [0, 0, 0, 0])
        cutsMax = array('d', [0, 0, 0, 0])
        mcuts.GetCuts(0.7, cutsMin, cutsMax)
        print "--- -------------------------------------------------------------"
        print "--- Retrieve cut values for signal efficiency of 0.7 from Reader"
        for ivar in range(4):
            print "... Cut: %.5g < %s <= %.5g" % (
                cutsMin[ivar], reader.GetVarName(ivar), cutsMax[ivar])

        print "--- -------------------------------------------------------------"

    #
    # write histograms
    #
    target = TFile("TMVApp.root", "RECREATE")
    for h in histList:
        h.Write()

    # Write also probability hists
    if "Fisher" in mlist:
        probHistFi.Write()
        rarityHistFi.Write()

    target.Close()

    print "--- Created root file: \"TMVApp.root\" containing the MVA output histograms"
    print "==> TMVApplication is done!"
예제 #6
0
파일: 2.py 프로젝트: gergler/korol_evm
def inv1(x, b1): return tan(3*x*b1 + atan(a))
def inv2(x, b2): return rt*(-a*exp(x*b2/d) - a - rt*exp(x*b2/d) + rt)/(-a*exp(x*b2/d) + a - rt*exp(x*b2/d) -rt)

print('Inv1: ', inv1(0, b1))
print('Inv2: ', inv2(0, b2))

def fncomposition(a, b, a1, a2, b1, b2):
    while (True):
        nr = gRandom.Uniform(0,1)
        nk = gRandom.Uniform(0,1)
        if nk < a1:
            return inv1(nr, b1)
        else:
            return inv2(nr, b2)
        
c2 = ROOT.TCanvas("myCanvasName2","The Canvas Title", 1200, 500)    
h2 = TH1F("h2", "composition method", 50, -1, 1)
sw = TStopwatch()
sw.Start()
for i in range(0, 10000):
    r = fncomposition(a, b, a1, a2, b1, b2)
    h2.Fill(r)
sw.Stop()
sw.Print()
h2.Draw()
h2.Fit(ff)
c2.Draw()

print('First moment: ', h2.GetMean())
print('Mean square: ', h2.GetStdDev())
예제 #7
0
        if BNTreeUseScript:
            chainName = "OSUAnalysis/" + BNTreeChannel + "/BNTree_" + BNTreeChannel
            command = "root -l -b -q '" + BNTreeScript + "+(\"" + condor_dir + "\",\"" + dataset + "\",\"" + chainName + "\"," + str(
                arguments.condorProcessNum) + ")'"
            print "About to execute command:  " + command
            os.system(command)
        else:
            for hist in input_histograms:
                #chain trees together
                ch = TChain("OSUAnalysis/" + hist['channel'] + "/BNTree_" +
                            hist['channel'])
                ch.Add(condor_dir + "/" + dataset + "/hist_*.root")
                print("Looping over chain with # entries = %f; split time = " %
                      ch.GetEntries()),
                watch1.Stop()
                watch1.Print()
                watch1.Start()

                outputFile = TFile(condor_dir + "/" + dataset + ".root",
                                   "UPDATE")
                if not outputFile or outputFile.IsZombie():
                    print "Could not open file: %s/%s.root" % (condor_dir,
                                                               dataset)
                outputFile.cd("OSUAnalysis/" + hist['channel'])

                deleteString = hist[
                    'histName'] + ";*"  # delete all existing instances of the object
                currentDir = outputFile.GetDirectory("OSUAnalysis/" +
                                                     hist['channel'])
                if not currentDir:
                    print "Could not find directory OSUAnalysis/%s in file %s" % (