Beispiel #1
0
beta_1 = (xp1 * xp1) - (xp2 * xp2)
beta_2 = (xp1 * xp1) - (xp3 * xp3)
gamma_1 = xp1 - xp2
gamma_2 = xp1 - xp3
temp = (beta_1 * (gamma_1 / gamma_2) - beta_2)
a = (gamma_2 * (alpha_1 / gamma_1) - alpha_2) / temp
bb = (alpha_2 - a * beta_2) / gamma_2
c = yp1 - a * xp1 * xp1 - bb * xp1


def parfaze(w):
    return a * w * w + bb * w + c


def phi_trim(w):
    return slope_phi() * (w - w_res) + parfaze(w)


def phi(w):
    return phi_trim(w) + phi_const


def V_out(w):
    return I * Ztotal(w) * np.exp(im_unit * phi(w) * pi / 180)


tg3 = getGraphFromFunc(V_out, x)
tg3.Draw()

gApplication.Run()
Beispiel #2
0
def main():

    try:
        # retrive command line options
        shortopts  = "w:m:i:j:f:g:t:o:a:vgh?"
        longopts   = ["weight_fold=", "methods=", "inputfilesig=", "inputfilebkg=", "friendinputfilesig=", "friendinputfilebkg=", "inputtrees=", "outputfile=", "verbose", "gui", "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)

    infnameSig     = DEFAULT_INFNAMESIG
    infnameBkg     = DEFAULT_INFNAMEBKG
    friendfnameSig = DEFAULT_FRIENDNAMESIG
    friendfnameBkg = DEFAULT_FRIENDNAMEBKG
    treeNameSig    = DEFAULT_TREESIG
    treeNameBkg    = DEFAULT_TREEBKG
    outfname       = DEFAULT_OUTFNAME
    methods        = DEFAULT_METHODS
    weight_fold    = "weights"
    verbose        = False
    gui            = False
    addedcuts      = ""
    for o, a in opts:
        if o in ("-?", "-h", "--help", "--usage"):
            usage()
            sys.exit(0)
        elif o in ("-w", "--weight_fold"):
            weight_fold = a
        elif o in ("-m", "--methods"):
            methods = a
        elif o in ("-i", "--inputfilesig"):
            infnameSig = a
        elif o in ("-j", "--inputfilebkg"):
            infnameBkg = a
        elif o in ("-f", "--friendinputfilesig"):
            friendfnameSig = a
        elif o in ("-g", "--friendinputfilebkg"):
            friendfnameBkg = a
        elif o in ("-o", "--outputfile"):
            outfname = a
        elif o in ("-a", "--addedcuts"):
            addedcuts = 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
        elif o in ("-g", "--gui"):
            gui = True

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

    # Print the file
    print "Using file " + infnameSig + " for signal..."
    print "Using file " + infnameBkg + " for background..."

    # Import ROOT classes
    from ROOT import gSystem, gROOT, gApplication, TFile, TTree, TCut
    
    # check ROOT version, give alarm if 5.18
    print "ROOT version is " + str(gROOT.GetVersionCode())
    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( "./" )
## SO I TAKE DEFAULT FORM ROOT#    gROOT.Macro       ( "./TMVAlogon.C" )    
#!    gROOT.LoadMacro   ( "./TMVAGui.C" )
 
   
    # Import TMVA classes from ROOT
    from ROOT import TMVA

    # Output file
    outputFile = TFile( outfname, 'RECREATE' )
    
    # Create instance of TMVA factory (see TMVA/macros/TMVAClassification.C for more factory options)
    # All TMVA output can be suppressed by removing the "!" (not) in 
    # front of the "Silent" argument in the option string
    factory = TMVA.Factory( "TMVAClassification", outputFile, 
                            "!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification" )

    # Set verbosity
    factory.SetVerbose( verbose )
    
    # If you wish to modify default settings 
    # (please check "src/Config.h" to see all available global options)
    #    gConfig().GetVariablePlotting()).fTimesRMS = 8.0
    (TMVA.gConfig().GetIONames()).fWeightFileDir = weight_fold;

    # Define the input variables that shall be used for the classifier training
    # note that you may also use variable expressions, such as: "3*var1/var2*abs(var3)"
    # [all types of expressions that can also be parsed by TTree::Draw( "expression" )]
    factory.AddVariable( "dR_l1l2", "dR_l1l2", "", 'F' )
    factory.AddVariable( "dR_b1b2", "dR_b1b2", "", 'F' )
    factory.AddVariable( "dR_bl", "dR_bl", "", 'F' )
    factory.AddVariable( "dR_l1l2b1b2", "dR_l1l2b1b2", "", 'F' )
    factory.AddVariable( "MINdR_bl", "MINdR_bl", "", 'F' )
    factory.AddVariable( "dphi_l1l2b1b2", "dphi_l1l2b1b2", "", 'F' )
    factory.AddVariable( "mass_l1l2", "mass_l1l2", "", 'F' )
    factory.AddVariable( "mass_b1b2", "mass_b1b2", "", 'F' )
    factory.AddVariable( "mass_trans", "mass_trans", "", 'F' )
    factory.AddVariable( "MT2", "MT2", "", 'F' )
    factory.AddVariable( "pt_b1b2", "pt_b1b2", "", 'F' )
    #factory.AddVariable( "MMC_h2mass_MaxBin", "MMC_h2mass_MaxBin", "", 'F' )
    #factory.AddVariable( "MMC_h2mass_RMS", "MMC_h2mass_RMS", "", 'F' )
    #factory.AddVariable( "MMC_h2mass_prob", "MMC_h2mass_prob", "", 'F' )

    # You can add so-called "Spectator variables", which are not used in the MVA training, 
    # but will appear in the final "TestTree" produced by TMVA. This TestTree will contain the 
    # input variables, the response values of all trained MVAs, and the spectator variables
    # factory.AddSpectator( "spec1:=var1*2",  "Spectator 1", "units", 'F' )
    # factory.AddSpectator( "spec2:=var1*3",  "Spectator 2", "units", 'F' )

    # Read input data
    if gSystem.AccessPathName( infnameSig ) != 0 or gSystem.AccessPathName( infnameBkg ): gSystem.Exec( "wget http://root.cern.ch/files/" + infname )
        
    inputSig = TFile.Open( infnameSig )
    inputBkg = TFile.Open( infnameBkg )

    # Get the signal and background trees for training
    signal      = inputSig.Get( treeNameSig )
    background  = inputBkg.Get( treeNameBkg )

    ##signal.AddFriend( "eleIDdir/isoT1 = eleIDdir/T1", friendfnameSig )
    ##background.AddFriend( "eleIDdir/isoT1 = eleIDdir/T1", friendfnameBkg )

    # Global event weights (see below for setting event-wise weights)
    signalWeight     = 1.
    backgroundWeight = 1.

#I don't think there's a general answer to this. The safest 'default'
#is to use the envent weight such that you have equal amounts of signal
#and background
#for the training, otherwise for example:  if you look for a rare
#signal and you use the weight to scale the number of events according
#to the expected ratio of signal and background
#according to the luminosity... the classifier sees hardly any signal
#events and "thinks" .. Oh I just classify everything background and do
#a good job!
#
#One can try to 'optimize' the training a bit more in  either 'high
#purity' or 'high efficiency' by choosing different weights, but as I
#said, there's no fixed rule. You'd have
#to 'try' and see if you get better restults by playing with the weights.

    # ====== register trees ====================================================
    #
    # the following method is the prefered one:
    # you can add an arbitrary number of signal or background trees
    factory.AddSignalTree    ( signal,     signalWeight     )
    factory.AddBackgroundTree( background, backgroundWeight )

    # To give different trees for training and testing, do as follows:
    #    factory.AddSignalTree( signalTrainingTree, signalTrainWeight, "Training" )
    #    factory.AddSignalTree( signalTestTree,     signalTestWeight,  "Test" )
    
    # Use the following code instead of the above two or four lines to add signal and background 
    # training and test events "by hand"
    # NOTE that in this case one should not give expressions (such as "var1+var2") in the input 
    #      variable definition, but simply compute the expression before adding the event
    #
    #    # --- begin ----------------------------------------------------------
    #    
    # ... *** please lookup code in TMVA/macros/TMVAClassification.C ***
    #    
    #    # --- end ------------------------------------------------------------
    #
    # ====== end of register trees ==============================================    
            
    # Set individual event weights (the variables must exist in the original TTree)
    #    for signal    : factory.SetSignalWeightExpression    ("weight1*weight2");
    #    for background: factory.SetBackgroundWeightExpression("weight1*weight2");

    # Apply additional cuts on the signal and background sample. 
    # example for cut: mycut = TCut( "abs(var1)<0.5 && abs(var2-0.5)<1" )
    #mycutSig = TCut( "nu1and2_diBaxis_t>-900 && met_diBaxis_t>-900&& hasb1jet && hasb2jet && hasMET && hasGenMET && hasdRljet && hastwomuons" ) 
    mycutSig = TCut( addedcuts ) 
    #mycutBkg = TCut( "event_n%2!=0 && " + addedcuts ) 
    mycutBkg = TCut( addedcuts ) 
    #mycutBkg = TCut( "nu1and2_diBaxis_t>-900 && met_diBaxis_t>-900&& hasb1jet && hasb2jet && hasMET && hasGenMET && hasdRljet && hastwomuons" ) 

    print mycutSig

    # Here, the relevant variables are copied over in new, slim trees that are
    # used for TMVA training and testing
    # "SplitMode=Random" means that the input events are randomly shuffled before
    # splitting them into training and test samples
    factory.PrepareTrainingAndTestTree( mycutSig, mycutBkg,
                                        "nTrain_Signal=0:nTrain_Background=0:SplitMode=Random:NormMode=NumEvents:!V" )

    # --------------------------------------------------------------------------------------------------

    # ---- Book MVA methods
    #
    # please lookup the various method configuration options in the corresponding cxx files, eg:
    # src/MethoCuts.cxx, etc, or here: http://tmva.sourceforge.net/optionRef.html
    # it is possible to preset ranges in the option string in which the cut optimisation should be done:
    # "...:CutRangeMin[2]=-1:CutRangeMax[2]=1"...", where [2] is the third input variable

    # Cut optimisation
    if "Cuts" in mlist:
        factory.BookMethod( TMVA.Types.kCuts, "Cuts",
                            "!H:!V:FitMethod=MC:EffSel:VarProp[0]=FMax:VarProp[1]=FMin" )

    if "CutsD" in mlist:
        factory.BookMethod( TMVA.Types.kCuts, "CutsD",
                            "!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart:VarTransform=Decorrelate" )

    if "CutsPCA" in mlist:
        factory.BookMethod( TMVA.Types.kCuts, "CutsPCA",
                            "!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart:VarTransform=PCA" )

    if "CutsGA" in mlist:
        factory.BookMethod( TMVA.Types.kCuts, "CutsGA",
                            "H:!V:FitMethod=GA:EffSel:Steps=30:Cycles=3:PopSize=400:SC_steps=10:SC_rate=5:SC_factor=0.95:VarProp[0]=FMin:VarProp[1]=FMax" )

    if "CutsSA" in mlist:
        factory.BookMethod( TMVA.Types.kCuts, "CutsSA",
                            "!H:!V:FitMethod=SA:EffSel:MaxCalls=150000:KernelTemp=IncAdaptive:InitialTemp=1e+6:MinTemp=1e-6:Eps=1e-10:UseDefaultScale" )

    # Likelihood ("naive Bayes estimator")
    if "Likelihood" in mlist:
        factory.BookMethod( TMVA.Types.kLikelihood, "Likelihood",
                            "H:!V:!TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmoothBkg[1]=10:NSmooth=1:NAvEvtPerBin=50" )

    # Decorrelated likelihood
    if "LikelihoodD" in mlist:
        factory.BookMethod( TMVA.Types.kLikelihood, "LikelihoodD",
                            "!H:!V:TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmooth=5:NAvEvtPerBin=50:VarTransform=Decorrelate" )

    # PCA-transformed likelihood
    if "LikelihoodPCA" in mlist:
        factory.BookMethod( TMVA.Types.kLikelihood, "LikelihoodPCA",
                            "!H:!V:!TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmooth=5:NAvEvtPerBin=50:VarTransform=PCA" ) 

    # Use a kernel density estimator to approximate the PDFs
    if "LikelihoodKDE" in mlist:
        factory.BookMethod( TMVA.Types.kLikelihood, "LikelihoodKDE",
                            "!H:!V:!TransformOutput:PDFInterpol=KDE:KDEtype=Gauss:KDEiter=Adaptive:KDEFineFactor=0.3:KDEborder=None:NAvEvtPerBin=50" ) 

    # Use a variable-dependent mix of splines and kernel density estimator
    if "LikelihoodMIX" in mlist:
        factory.BookMethod( TMVA.Types.kLikelihood, "LikelihoodMIX",
                            "!H:!V:!TransformOutput:PDFInterpolSig[0]=KDE:PDFInterpolBkg[0]=KDE:PDFInterpolSig[1]=KDE:PDFInterpolBkg[1]=KDE:PDFInterpolSig[2]=Spline2:PDFInterpolBkg[2]=Spline2:PDFInterpolSig[3]=Spline2:PDFInterpolBkg[3]=Spline2:KDEtype=Gauss:KDEiter=Nonadaptive:KDEborder=None:NAvEvtPerBin=50" ) 

    # Test the multi-dimensional probability density estimator
    # here are the options strings for the MinMax and RMS methods, respectively:
    #      "!H:!V:VolumeRangeMode=MinMax:DeltaFrac=0.2:KernelEstimator=Gauss:GaussSigma=0.3" );
    #      "!H:!V:VolumeRangeMode=RMS:DeltaFrac=3:KernelEstimator=Gauss:GaussSigma=0.3" );
    if "PDERS" in mlist:
        factory.BookMethod( TMVA.Types.kPDERS, "PDERS",
                            "!H:!V:NormTree=T:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600" )

    if "PDERSD" in mlist:
        factory.BookMethod( TMVA.Types.kPDERS, "PDERSD",
                            "!H:!V:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600:VarTransform=Decorrelate" )

    if "PDERSPCA" in mlist:
        factory.BookMethod( TMVA.Types.kPDERS, "PDERSPCA",
                             "!H:!V:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600:VarTransform=PCA" )

   # Multi-dimensional likelihood estimator using self-adapting phase-space binning
    if "PDEFoam" in mlist:
        factory.BookMethod( TMVA.Types.kPDEFoam, "PDEFoam",
                            "!H:!V:SigBgSeparate=F:TailCut=0.001:VolFrac=0.0666:nActiveCells=500:nSampl=2000:nBin=5:Nmin=100:Kernel=None:Compress=T" )

    if "PDEFoamBoost" in mlist:
        factory.BookMethod( TMVA.Types.kPDEFoam, "PDEFoamBoost",
                            "!H:!V:Boost_Num=30:Boost_Transform=linear:SigBgSeparate=F:MaxDepth=4:UseYesNoCell=T:DTLogic=MisClassificationError:FillFoamWithOrigWeights=F:TailCut=0:nActiveCells=500:nBin=20:Nmin=400:Kernel=None:Compress=T" )

    # K-Nearest Neighbour classifier (KNN)
    if "KNN" in mlist:
        factory.BookMethod( TMVA.Types.kKNN, "KNN",
                            "H:nkNN=20:ScaleFrac=0.8:SigmaFact=1.0:Kernel=Gaus:UseKernel=F:UseWeight=T:!Trim" )

    # H-Matrix (chi2-squared) method
    if "HMatrix" in mlist:
        factory.BookMethod( TMVA.Types.kHMatrix, "HMatrix", "!H:!V" )

    # Linear discriminant (same as Fisher discriminant)
    if "LD" in mlist:
        factory.BookMethod( TMVA.Types.kLD, "LD", "H:!V:VarTransform=None:CreateMVAPdfs:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=50:NsmoothMVAPdf=10" )

    # Fisher discriminant (same as LD)
    if "Fisher" in mlist:
        factory.BookMethod( TMVA.Types.kFisher, "Fisher", "H:!V:Fisher:CreateMVAPdfs:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=50:NsmoothMVAPdf=10" )

    # Fisher with Gauss-transformed input variables
    if "FisherG" in mlist:
        factory.BookMethod( TMVA.Types.kFisher, "FisherG", "H:!V:VarTransform=Gauss" )

    # Composite classifier: ensemble (tree) of boosted Fisher classifiers
    if "BoostedFisher" in mlist:
        factory.BookMethod( TMVA.Types.kFisher, "BoostedFisher", 
                            "H:!V:Boost_Num=20:Boost_Transform=log:Boost_Type=AdaBoost:Boost_AdaBoostBeta=0.2" )

    # Function discrimination analysis (FDA) -- test of various fitters - the recommended one is Minuit (or GA or SA)
    if "FDA_MC" in mlist:
        factory.BookMethod( TMVA.Types.kFDA, "FDA_MC",
                            "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1)(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=MC:SampleSize=100000:Sigma=0.1" );

    if "FDA_GA" in mlist:
        factory.BookMethod( TMVA.Types.kFDA, "FDA_GA",
                            "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1)(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=GA:PopSize=300:Cycles=3:Steps=20:Trim=True:SaveBestGen=1" );

    if "FDA_SA" in mlist:
        factory.BookMethod( TMVA.Types.kFDA, "FDA_SA",
                            "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1)(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=SA:MaxCalls=15000:KernelTemp=IncAdaptive:InitialTemp=1e+6:MinTemp=1e-6:Eps=1e-10:UseDefaultScale" );

    if "FDA_MT" in mlist:
        factory.BookMethod( TMVA.Types.kFDA, "FDA_MT",
                            "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1)(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=2:UseImprove:UseMinos:SetBatch" );

    if "FDA_GAMT" in mlist:
        factory.BookMethod( TMVA.Types.kFDA, "FDA_GAMT",
                            "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1)(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=GA:Converger=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=0:!UseImprove:!UseMinos:SetBatch:Cycles=1:PopSize=5:Steps=5:Trim" );

    if "FDA_MCMT" in mlist:
        factory.BookMethod( TMVA.Types.kFDA, "FDA_MCMT",
                            "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1)(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=MC:Converger=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=0:!UseImprove:!UseMinos:SetBatch:SampleSize=20" );

    # TMVA ANN: MLP (recommended ANN) -- all ANNs in TMVA are Multilayer Perceptrons
    if "MLP" in mlist:
        factory.BookMethod( TMVA.Types.kMLP, "MLP", "H:!V:NeuronType=tanh:VarTransform=N:NCycles=600:HiddenLayers=N+5:TestRate=5:!UseRegulator" )

    if "MLPBFGS" in mlist:
        factory.BookMethod( TMVA.Types.kMLP, "MLPBFGS", "H:!V:NeuronType=tanh:VarTransform=N:NCycles=600:HiddenLayers=N+5:TestRate=5:TrainingMethod=BFGS:!UseRegulator" )

    if "MLPBNN" in mlist:
        factory.BookMethod( TMVA.Types.kMLP, "MLPBNN", "H:!V:NeuronType=tanh:VarTransform=N:NCycles=600:HiddenLayers=N+5:TestRate=5:TrainingMethod=BFGS:UseRegulator" ) # BFGS training with bayesian regulators

    # CF(Clermont-Ferrand)ANN
    if "CFMlpANN" in mlist:
        factory.BookMethod( TMVA.Types.kCFMlpANN, "CFMlpANN", "!H:!V:NCycles=2000:HiddenLayers=N+1,N"  ) # n_cycles:#nodes:#nodes:...  

    # Tmlp(Root)ANN
    if "TMlpANN" in mlist:
        factory.BookMethod( TMVA.Types.kTMlpANN, "TMlpANN", "!H:!V:NCycles=200:HiddenLayers=N+1,N:LearningMethod=BFGS:ValidationFraction=0.3"  ) #n_cycles:#nodes:#nodes:...

    # Support Vector Machine
    if "SVM" in mlist:
        factory.BookMethod( TMVA.Types.kSVM, "SVM", "Gamma=0.25:Tol=0.001:VarTransform=Norm" )

    # Boosted Decision Trees
    if "BDTG" in mlist:
        factory.BookMethod( TMVA.Types.kBDT, "BDTG",
                            "!H:!V:NTrees=1000:BoostType=Grad:Shrinkage=0.30:UseBaggedGrad:GradBaggingFraction=0.6:SeparationType=GiniIndex:nCuts=20:NNodesMax=5" )

    if "BDT" in mlist:
        factory.BookMethod( TMVA.Types.kBDT, "BDT",
                            "!H:!V:NTrees=850:nEventsMin=150:MaxDepth=3:BoostType=AdaBoost:AdaBoostBeta=0.5:SeparationType=GiniIndex:nCuts=20:PruneMethod=NoPruning" )

    if "BDTB" in mlist:
        factory.BookMethod( TMVA.Types.kBDT, "BDTB",
                            "!H:!V:NTrees=400:BoostType=Bagging:SeparationType=GiniIndex:nCuts=20:PruneMethod=NoPruning" )

    if "BDTD" in mlist:
        factory.BookMethod( TMVA.Types.kBDT, "BDTD",
                            "!H:!V:NTrees=400:nEventsMin=400:MaxDepth=3:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:PruneMethod=NoPruning:VarTransform=Decorrelate" )

    # RuleFit -- TMVA implementation of Friedman's method
    if "RuleFit" in mlist:
        factory.BookMethod( TMVA.Types.kRuleFit, "RuleFit",
                            "H:!V:RuleFitModule=RFTMVA:Model=ModRuleLinear:MinImp=0.001:RuleMinDist=0.001:NTrees=20:fEventsMin=0.01:fEventsMax=0.5:GDTau=-1.0:GDTauPrec=0.01:GDStep=0.01:GDNSteps=10000:GDErrScale=1.02" )

    # --------------------------------------------------------------------------------------------------
            
    # ---- Now you can tell the factory to train, test, and evaluate the MVAs. 

    # Train MVAs
    factory.TrainAllMethods()
    
    # Test MVAs
    factory.TestAllMethods()
    
    # Evaluate MVAs
    factory.EvaluateAllMethods()    
    
    # Save the output.
    outputFile.Close()
    
    print "=== wrote root file %s\n" % outfname
    print "=== TMVAClassification is done!\n"
    
    # open the GUI for the result macros    
    if( gui ):
        gROOT.ProcessLine( "TMVAGui(\"%s\")" % outfname )
        # keep the ROOT thread running
        gApplication.Run() 
Beispiel #3
0
def makePlots(inputHitFileName):
    can = {}
    canIdx = 0

    fitTrackPH = {}
    allHitPH = {}

    ###########################################################################################################
    # Open all the input root files.
    hitTFile = TFile(inputHitFileName)
    list1 = hitTFile.GetListOfKeys()

    print '==> In plotHits, using file name {0:s}'.format(inputHitFileName)

    # Go to directory for the TrackHitAna output
    for i in list1:
        if i.GetClassName() == 'TDirectoryFile':
            if i.GetName() != "mcassociations":
                continue
            hitTFile.cd(i.GetName())
            histogramList = gDirectory.GetListOfKeys()
            can[canIdx] = TCanvas("MC vs Reco", "MC vs Reco", 800, 600)
            can[canIdx].Divide(2, 2)
            nHitsPerPrimary = GetObject("NHitsPerPrimary", histogramList)
            primaryRecoNHits = GetObject("PrimaryRecoNHits", histogramList)
            deltaNHits = GetObject("DeltaNHits", histogramList)
            primaryLength = GetObject("PrimaryLength", histogramList)
            primaryRecLength = GetObject("PrimaryRecLength", histogramList)
            deltaTrackLen = GetObject("DeltaTrackLen", histogramList)
            can[canIdx].cd(1)
            nHitsPerPrimary.SetLineColor(4)
            nHitsPerPrimary.SetStats(0)
            nHitsPerPrimary.Draw()
            primaryRecoNHits.SetLineColor(2)
            primaryRecoNHits.SetStats(0)
            primaryRecoNHits.Draw("SAMES")
            can[canIdx].cd(2)
            deltaNHits.SetLineColor(4)
            deltaNHits.SetStats(0)
            deltaNHits.Draw()
            can[canIdx].cd(3)
            primaryLength.SetLineColor(4)
            primaryLength.SetStats(0)
            primaryLength.Draw()
            primaryRecLength.SetLineColor(2)
            primaryRecLength.SetStats(0)
            primaryRecLength.Draw("SAMES")
            can[canIdx].cd(4)
            deltaTrackLen.SetLineColor(4)
            deltaTrackLen.SetStats(0)
            deltaTrackLen.Draw()
            can[canIdx].Update()

            canIdx += 1

            can[canIdx] = TCanvas("Completeness", "Completeness", 800, 600)
            can[canIdx].Divide(2, 2)
            primCompleteness = GetObject("PrimaryCompleteness", histogramList)
            primCompVsNHits = GetObject("PrimaryCompVsLogHits", histogramList)
            primCompVsLen = GetObject("PrimaryCompVsLen", histogramList)
            primCompVsMom = GetObject("PrimaryCompVsMom", histogramList)
            can[canIdx].cd(1)
            primCompleteness.SetLineColor(4)
            primCompleteness.SetStats(0)
            primCompleteness.Draw()
            can[canIdx].cd(2)
            primCompVsNHits.SetLineColor(4)
            primCompVsNHits.SetStats(0)
            primCompVsNHits.Draw()
            can[canIdx].cd(3)
            primCompVsLen.SetLineColor(4)
            primCompVsLen.SetStats(0)
            primCompVsLen.Draw()
            can[canIdx].cd(4)
            primCompVsMom.SetLineColor(4)
            primCompVsMom.SetStats(0)
            primCompVsMom.Draw()
            can[canIdx].Update()

            canIdx += 1

            can[canIdx] = TCanvas("Efficiency", "Efficiency", 800, 600)
            can[canIdx].Divide(2, 2)
            primEfficiency = GetObject("PrimaryEfficiency", histogramList)
            primEffVsNHits = GetObject("PrimaryEffVsLogHits", histogramList)
            primEffVsLen = GetObject("PrimaryEffVsLen", histogramList)
            primEffVsMom = GetObject("PrimaryEffVsMom", histogramList)
            can[canIdx].cd(1)
            primEfficiency.SetLineColor(4)
            primEfficiency.SetStats(0)
            primEfficiency.Draw()
            can[canIdx].cd(2)
            primEffVsNHits.SetLineColor(4)
            primEffVsNHits.SetStats(0)
            primEffVsNHits.Draw()
            can[canIdx].cd(3)
            primEffVsLen.SetLineColor(4)
            primEffVsLen.SetStats(0)
            primEffVsLen.Draw()
            can[canIdx].cd(4)
            primEffVsMom.SetLineColor(4)
            primEffVsMom.SetStats(0)
            primEffVsMom.Draw()
            can[canIdx].Update()

            canIdx += 1

            can[canIdx] = TCanvas("Purity", "Purity", 800, 600)
            can[canIdx].Divide(2, 2)
            primPurity = GetObject("PrimaryPurity", histogramList)
            primPurVsNHits = GetObject("PrimaryPurityVsLogHits", histogramList)
            primPurVsLen = GetObject("PrimaryPurVsLen", histogramList)
            primPurVsMom = GetObject("PrimaryPurVsMom", histogramList)
            can[canIdx].cd(1)
            primPurity.SetLineColor(4)
            primPurity.SetStats(0)
            primPurity.Draw()
            can[canIdx].cd(2)
            primPurVsNHits.SetLineColor(4)
            primPurVsNHits.SetStats(0)
            primPurVsNHits.Draw()
            can[canIdx].cd(3)
            primPurVsLen.SetLineColor(4)
            primPurVsLen.SetStats(0)
            primPurVsLen.Draw()
            can[canIdx].cd(4)
            primPurVsMom.SetLineColor(4)
            primPurVsMom.SetStats(0)
            primPurVsMom.Draw()
            can[canIdx].Update()

            canIdx += 1

    gApplication.Run()
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 "=== TMVAClassification: 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

    # 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("./")
    gROOT.Macro("./TMVAlogon.C")
    gROOT.LoadMacro("./TMVAGui.C")

    # Import TMVA classes from ROOT
    from ROOT import TMVA

    # Output file
    outputFile = TFile(outfname, 'RECREATE')

    # Create instance of TMVA factory (see TMVA/macros/TMVAClassification.C for more factory options)
    # All TMVA output can be suppressed by removing the "!" (not) in
    # front of the "Silent" argument in the option string
    #    factory = TMVA.Factory( "TMVAClassification", outputFile,
    #                            "!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification" )
    jobname = DEFAULT_OUTFNAME
    factory = TMVA.Factory(
        jobname.replace(".root", ""), outputFile,
        "!V:!Silent:Color:DrawProgressBar:Transformations=I:AnalysisType=Classification"
    )  # pascal

    # Set verbosity
    factory.SetVerbose(verbose)

    # Adjust variables if old sample is used
    if IsOLD:
        SPECTATORS.remove("JisPU")
        SPECTATORS.remove("JisHS")

    # Define the input variables that shall be used for the classifier training
    # note that you may also use variable expressions, such as: "3*var1/var2*abs(var3)"
    theCat1Vars = ""
    theCat2Vars = ""
    theCat3Vars = ""
    for var in VARIABLES:
        factory.AddVariable(var, 'F')
        theCat1Vars += var + ":"
        theCat2Vars += var + ":"
        theCat3Vars += var + ":"

    theCat1Vars = theCat1Vars.rstrip(":")
    theCat2Vars = theCat2Vars.rstrip(":")
    theCat3Vars = theCat3Vars.rstrip(":")

    # You can add so-called "Spectator variables", which are not used in the MVA training,
    for spect in SPECTATORS:
        factory.AddSpectator(spect, spect)

    # Apply additional cuts on the signal and background sample.
    mycutSig = ""
    mycutBkg = TCut(SELECTION + "&&JisPU")
    if doJTruthMatchPt10Cut:
        mycutSig = TCut(SELECTION + "&&JisHS && Jtruthpt>10")
    else:
        mycutSig = TCut(SELECTION + "&&JisHS")

    cat1cuts = TCut("Jpt >20 && Jpt <30")
    cat2cuts = TCut("Jpt >30 && Jpt <40")
    cat3cuts = TCut("Jpt >40 && Jpt <50")

    # open file
    input = TFile.Open(infname)

    # Get the signal and background trees for training
    signal = input.Get(treeNameSig)
    background = input.Get(treeNameBkg)

    # Global event weights (see below for setting event-wise weights)
    signalWeight = 1.0
    backgroundWeight = 1.0

    # ====== register trees ====================================================
    factory.AddSignalTree(signal, signalWeight)
    factory.AddBackgroundTree(background, backgroundWeight)

    # To give different trees for training and testing, do as follows:
    #    factory.AddSignalTree( signalTrainingTree, signalTrainWeight, "Training" )
    #    factory.AddSignalTree( signalTestTree,     signalTestWeight,  "Test" )

    # Set individual event weights (the variables must exist in the original TTree)
    #    for signal    : factory.SetSignalWeightExpression    ("weight1*weight2");
    #    for background: factory.SetBackgroundWeightExpression("weight1*weight2");

    # Here, the relevant variables are copied over in new, slim trees that are
    # used for TMVA training and testing
    # "SplitMode=Random" means that the input events are randomly shuffled before
    # splitting them into training and test samples
    TrainingAndTestTreeStr= "nTrain_Signal="+str(DEFAULT_NEVENTS_TRAIN_S)+\
                            ":nTrain_Background="+str(DEFAULT_NEVENTS_TRAIN_B)+\
                            ":nTest_Signal="+str(DEFAULT_NEVENTS_TEST_S)+\
                            ":nTest_Background="+str(DEFAULT_NEVENTS_TEST_B)+\
                            ":SplitMode=Random:NormMode=EqualNumEvents:!V"
    factory.PrepareTrainingAndTestTree(mycutSig, mycutBkg,
                                       TrainingAndTestTreeStr)

    # --------------------------------------------------------------------------------------------------

    # ---- Book MVA methods
    #

    # multidim likelihood --- kNN
    if "kNN100" in mlist:
        factory.BookMethod(
            TMVA.Types.kKNN, "KNN100",
            "!V:H:nkNN=100:ScaleFrac=0.8:UseKernel=F:UseWeight=F:Trim=False:BalanceDepth=6"
        )

    if "kNN100trim" in mlist:
        factory.BookMethod(
            TMVA.Types.kKNN, "KNN100trim",
            "!V:H:nkNN=100:ScaleFrac=0.8:UseKernel=F:UseWeight=F:Trim=True:BalanceDepth=6"
        )

    if "likelihood" in mlist:
        factory.BookMethod(TMVA.Types.kLikelihood, "Likelihood", "H:!V:")

    if "BDT" in mlist:
        BDToptions = "!H:NTrees=850:nEventsMin=150:MaxDepth=5:BoostType=AdaBoost:AdaBoostBeta=0.5:SeparationType=GiniIndex:nCuts=20:PruneMethod=NoPruning:VerbosityLevel=Error"
        factory.BookMethod(TMVA.Types.kBDT, "BDT", BDToptions)

    # ---- Now you can tell the factory to train, test, and evaluate the MVAs.
    # Train MVAs
    factory.TrainAllMethods()

    # Test MVAs
    factory.TestAllMethods()

    # Evaluate MVAs
    factory.EvaluateAllMethods()

    # Save the output.
    outputFile.Close()

    print "=== wrote root file %s\n" % outfname
    print "=== TMVAClassification is done!\n"

    # open the GUI for the result macros
    gROOT.ProcessLine("TMVAGui(\"%s\")" % outfname)

    # keep the ROOT thread running
    gApplication.Run()
Beispiel #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 "=== TMVAnalysis: 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
    
    # 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" )    
    gROOT.LoadMacro   ( "../macros/TMVAGui.C" )
    
    # Import TMVA classes from ROOT
    from ROOT import TMVA

    # Output file
    outputFile = TFile( outfname, 'RECREATE' )
    
    # Create instance of TMVA factory (see TMVA/macros/TMVAnalysis.C for more factory options)
    # All TMVA output can be suppressed by removing the "!" (not) in 
    # front of the "Silent" argument in the option string
    factory = TMVA.Factory( "TMVAnalysis", outputFile, "!V:!Silent:Color" )

    # Set verbosity
    factory.SetVerbose( verbose )
    
    # Define the input variables that shall be used for the classifier training
    # note that you may also use variable expressions, such as: "3*var1/var2*abs(var3)"
    # [all types of expressions that can also be parsed by TTree::Draw( "expression" )]
    factory.AddVariable( "var1+var2", 'F' )
    factory.AddVariable( "var1-var2", 'F' )
    factory.AddVariable( "var3",      'F' )
    factory.AddVariable( "var4",      'F' )

    # Read input data
    if not gSystem.AccessPathName( infname ):
        input = TFile( infname )
    else:
        print "ERROR: could not access data file %s\n" % infname

    # Get the signal and background trees for training
    signal      = input.Get( treeNameSig )
    background  = input.Get( treeNameBkg )
    
    # Global event weights (see below for setting event-wise weights)
    signalWeight     = 1.0
    backgroundWeight = 1.0

    # ====== register trees ====================================================
    #
    # the following method is the prefered one:
    # you can add an arbitrary number of signal or background trees
    factory.AddSignalTree    ( signal,     signalWeight     )
    factory.AddBackgroundTree( background, backgroundWeight )

    # To give different trees for training and testing, do as follows:
    #    factory.AddSignalTree( signalTrainingTree, signalTrainWeight, "Training" )
    #    factory.AddSignalTree( signalTestTree,     signalTestWeight,  "Test" )
    
    # Use the following code instead of the above two or four lines to add signal and background 
    # training and test events "by hand"
    # NOTE that in this case one should not give expressions (such as "var1+var2") in the input 
    #      variable definition, but simply compute the expression before adding the event
    #
    #    # --- begin ----------------------------------------------------------
    #    
    # ... *** please lookup code in TMVA/macros/TMVAnalysis.C ***
    #    
    #    # --- end ------------------------------------------------------------
    #
    # ====== end of register trees ==============================================    
            
    # This would set individual event weights (the variables defined in the 
    # expression need to exist in the original TTree)
    #    for signal    : factory.SetSignalWeightExpression("weight1*weight2")
    #    for background: factory.SetBackgroundWeightExpression("weight1*weight2")

    # Apply additional cuts on the signal and background sample. 
    # example for cut: mycut = TCut( "abs(var1)<0.5 && abs(var2-0.5)<1" )
    mycutSig = TCut( "" ) 
    mycutBkg = TCut( "" ) 
    
    # Here, the relevant variables are copied over in new, slim trees that are
    # used for TMVA training and testing
    # "SplitMode=Random" means that the input events are randomly shuffled before
    # splitting them into training and test samples
    factory.PrepareTrainingAndTestTree( mycutSig, mycutBkg,
                                        "NSigTrain=3000:NBkgTrain=3000:SplitMode=Random:NormMode=NumEvents:!V" )

    # ... and alternative call to use a different number of signal and background training/test event is:
    # factory.PrepareTrainingAndTestTree( mycut, "NSigTrain=3000:NBkgTrain=3000:NSigTest=3000:NBkgTest=3000:SplitMode=Random:!V" )

    # --------------------------------------------------------------------------------------------------

    # Cut optimisation
    if "Cuts" in mlist:
        factory.BookMethod( TMVA.Types.kCuts, "Cuts", 
                            "!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart" )

    if "CutsD" in mlist:
        factory.BookMethod( TMVA.Types.kCuts, "CutsD", 
                            "!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart:VarTransform=Decorrelate" )

    if "CutsPCA" in mlist:
        factory.BookMethod( TMVA.Types.kCuts, "CutsPCA", 
                            "!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart:VarTransform=PCA" )

    if "CutsGA" in mlist:
        factory.BookMethod( TMVA.Types.kCuts, "CutsGA",
                            "H:!V:FitMethod=GA:EffSel:Steps=30:Cycles=3:PopSize=100:SC_steps=10:SC_rate=5:SC_factor=0.95:VarProp=FSmart" )
   
    if "CutsSA" in mlist:
        factory.BookMethod( TMVA.Types.kCuts, "CutsSA",
                            "H:!V:FitMethod=SA:EffSel:MaxCalls=150000:KernelTemperature=IncreasingAdaptive:InitialTemperature=1e+6:MinTemperature=1e-6:Eps=1e-10:UseDefaultScale" )
   
    # Likelihood
    if "Likelihood" in mlist:
        factory.BookMethod( TMVA.Types.kLikelihood, "Likelihood", 
                            "!H:!V:!TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=10:NSmoothBkg[0]=10:NSmoothBkg[1]=10:NSmooth=10:NAvEvtPerBin=50" )

    # test the decorrelated likelihood
    if "LikelihoodD" in mlist:
        factory.BookMethod( TMVA.Types.kLikelihood, "LikelihoodD", 
                            "!H:!V:!TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=10:NSmoothBkg[0]=10:NSmooth=5:NAvEvtPerBin=50:VarTransform=Decorrelate" )

    if "LikelihoodPCA" in mlist:
        factory.BookMethod( TMVA.Types.kLikelihood, "LikelihoodPCA", 
                            "!H:!V:!TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=10:NSmoothBkg[0]=10:NSmooth=5:NAvEvtPerBin=50:VarTransform=PCA" )
 
    # test the new kernel density estimator
    if "LikelihoodKDE" in mlist:
        factory.BookMethod( TMVA.Types.kLikelihood, "LikelihoodKDE", 
                            "!H:!V:!TransformOutput:PDFInterpol=KDE:KDEtype=Gauss:KDEiter=Nonadaptive:KDEborder=None:NAvEvtPerBin=50" )

    # test the mixed splines and kernel density estimator (depending on which variable)
    if "LikelihoodMIX" in mlist:
        factory.BookMethod( TMVA.Types.kLikelihood, "LikelihoodMIX", 
                            "!H:!V:!TransformOutput:PDFInterpol[0]=KDE:PDFInterpol[1]=KDE:PDFInterpol[2]=Spline2:PDFInterpol[3]=Spline2:KDEtype=Gauss:KDEiter=Nonadaptive:KDEborder=None:NAvEvtPerBin=50" )

    # PDE - RS method
    if "PDERS" in mlist:
        factory.BookMethod( TMVA.Types.kPDERS, "PDERS", 
                            "!H:!V:NormTree=T:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600" )
        # And the options strings for the MinMax and RMS methods, respectively:
        #      "!H:!V:VolumeRangeMode=MinMax:DeltaFrac=0.2:KernelEstimator=Gauss:GaussSigma=0.3" 
        #      "!H:!V:VolumeRangeMode=RMS:DeltaFrac=3:KernelEstimator=Gauss:GaussSigma=0.3" 
        
    if "PDERSkNN" in mlist:
        factory.BookMethod( TMVA.Types.kPDERS, "PDERSkNN", 
                            "!H:!V:VolumeRangeMode=kNN:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600" )

    if "PDERSD" in mlist:
        factory.BookMethod( TMVA.Types.kPDERS, "PDERSD", 
                            "!H:!V:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600:VarTransform=Decorrelate" )

    if "PDERSPCA" in mlist:
        factory.BookMethod( TMVA.Types.kPDERS, "PDERSPCA", 
                            "!H:!V:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600:VarTransform=PCA" )
  
    # K-Nearest Neighbour class ifier (KNN)
    if "KNN" in mlist:
        factory.BookMethod( TMVA.Types.kKNN, "KNN", 
                            "nkNN=400:TreeOptDepth=6:ScaleFrac=0.8:!UseKernel:!Trim" ) 

    # H-Matrix (chi2-squared) method
    if "HMatrix" in mlist:
        factory.BookMethod( TMVA.Types.kHMatrix, "HMatrix", "!H:!V" ) 
        
    # Fisher discriminant
    if "Fisher" in mlist:
        factory.BookMethod( TMVA.Types.kFisher, "Fisher", 
                            "H:!V:!Normalise:CreateMVAPdfs:Fisher:NbinsMVAPdf=50:NsmoothMVAPdf=1" )

    # Function discrimination analysis (FDA) -- test of various fitters - the recommended one is Minuit (or GA or SA)
    if "FDA_MC" in mlist:
        factory.BookMethod( TMVA.Types.kFDA, "FDA_MC",
                            "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=MC:SampleSize=100000:Sigma=0.1" )
   
    if "FDA_GA" in mlist:
        factory.BookMethod( TMVA.Types.kFDA, "FDA_GA",
                            "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=GA:PopSize=100:Cycles=3:Steps=20:Trim=True:SaveBestGen=0" )

    if "FDA_MT" in mlist:
        factory.BookMethod( TMVA.Types.kFDA, "FDA_MT",
                            "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=2:UseImprove:UseMinos:SetBatch" )

    if "FDA_GAMT" in mlist:
        factory.BookMethod( TMVA.Types.kFDA, "FDA_GAMT",
                            "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=GA:Converger=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=0:!UseImprove:!UseMinos:SetBatch:Cycles=1:PopSize=5:Steps=5:Trim" )

    if "FDA_MCMT" in mlist:
        factory.BookMethod( TMVA.Types.kFDA, "FDA_MCMT",
                            "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=MC:Converger=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=0:!UseImprove:!UseMinos:SetBatch:SampleSize=20" )

    # TMVA ANN: MLP (recommended ANN) -- all ANNs in TMVA are Multilayer Perceptrons
    if "MLP" in mlist:
        factory.BookMethod( TMVA.Types.kMLP, "MLP", "H:!V:!Normalise:NeuronType=tanh:NCycles=200:HiddenLayers=N+1,N:TestRate=5" )

    # CF(Clermont-Ferrand)ANN
    if "CFMlpANN" in mlist:
        factory.BookMethod( TMVA.Types.kCFMlpANN, "CFMlpANN", "!H:!V:NCycles=500:HiddenLayers=N+1,N"  ) # n_cycles:#nodes:#nodes:...  
        
    # Tmlp(Root)ANN
    if "TMlpANN" in mlist:
        factory.BookMethod( TMVA.Types.kTMlpANN, "TMlpANN", "!H:!V:NCycles=200:HiddenLayers=N+1,N:LearningMethod=BFGS:ValidationFraction=0.3"  ) # n_cycles:#nodes:#nodes:..
  
    # Support Vector Machines using three d ifferent Kernel types (Gauss, polynomial and linear)
    if "SVM_Gauss" in mlist:
        factory.BookMethod( TMVA.Types.kSVM, "SVM_Gauss", "Sigma=2:C=1:Tol=0.001:Kernel=Gauss" )
      
    if "SVM_Poly" in mlist:
        factory.BookMethod( TMVA.Types.kSVM, "SVM_Poly", "Order=4:Theta=1:C=0.1:Tol=0.001:Kernel=Polynomial" )
      
    if "SVM_Lin" in mlist:
        factory.BookMethod( TMVA.Types.kSVM, "SVM_Lin", "!H:!V:Kernel=Linear:C=1:Tol=0.001" ) 
        
    # Boosted Decision Trees (second one with decorrelation)
    if "BDT" in mlist:
        factory.BookMethod( TMVA.Types.kBDT, "BDT", 
                            "!H:!V:NTrees=400:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:PruneMethod=CostComplexity:PruneStrength=1.5" )
    if "BDTD" in mlist:
        factory.BookMethod( TMVA.Types.kBDT, "BDTD", 
                            "!H:!V:NTrees=400:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:PruneMethod=CostComplexity:PruneStrength=2.5:VarTransform=Decorrelate" )

    # RuleFit -- TMVA implementation of Friedman's method
    if "RuleFit" in mlist:
        factory.BookMethod( TMVA.Types.kRuleFit, "RuleFit",
                            "H:!V:RuleFitModule=RFTMVA:Model=ModRuleLinear:MinImp=0.001:RuleMinDist=0.001:NTrees=20:fEventsMin=0.01:fEventsMax=0.5:GDTau=-1.0:GDTauPrec=0.01:GDStep=0.01:GDNSteps=10000:GDErrScale=1.02" )

    # Friedman's RuleFit method, implementation by J. Friedman
    if "RuleFitJF" in mlist:
        factory.BookMethod( TMVA.Types.kRuleFit, "RuleFitJF",
                            "!V:RuleFitModule=RFFriedman:Model=ModRuleLinear:GDStep=0.01:GDNSteps=10000:GDErrScale=1.1:RFNendnodes=4" )
 
    # --------------------------------------------------------------------------------------------------
            
    # ---- Now you can tell the factory to train, test, and evaluate the MVAs. 

    # Train MVAs
    factory.TrainAllMethods()
    
    # Test MVAs
    factory.TestAllMethods()
    
    # Evaluate MVAs
    factory.EvaluateAllMethods()    
    
    # Save the output.
    outputFile.Close()
    
    print "=== wrote root file %s\n" % outfname
    print "=== TMVAnalysis is done!\n"
    
    # open the GUI for the result macros    
    gROOT.ProcessLine( "TMVAGui(\"%s\")" % outfname )
    
    # keep the ROOT thread running
    gApplication.Run() 
def main():

    try:
        # retrive command line options
        shortopts  = "m:o:l:s:vh?"
        longopts   = ["methods=", "outputfile=", "lepton=", "signal=", "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)

    lepton = DEFAULT_LEPTON
    outfname    = DEFAULT_OUTFNAME
    methods     = DEFAULT_METHODS
    verbose     = False
    signal      = DEFAULT_SIGNAL
    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 ("-o", "--outputfile"):
            outfname = a
        elif o in ("-s", "--signal"):
            signal = a
        elif o in ("-v", "--verbose"):
            verbose = True
        elif o in ("-l", "--lepton"):
            if a == "electron":
                lepton = ELECTRON
            elif a == "muon":
                lepton = MUON
            else:
                print "*** Lepton must be 'electron' or 'muon ****"
                sys.exit(1)


    # Print methods
    mlist = methods.replace(' ',',').split(',')
    print "=== TMVAClassification: 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
    
    # 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( "./" )
    gROOT.Macro       ( "./TMVAlogon.C" )    
    gROOT.LoadMacro   ( "./TMVAGui.C" )
    
    # Import TMVA classes from ROOT
    from ROOT import TMVA

    # Output file
    outputFile = TFile( outfname, 'RECREATE' )
    
    # Create instance of TMVA factory (see TMVA/macros/TMVAClassification.C for more factory options)
    # All TMVA output can be suppressed by removing the "!" (not) in 
    # front of the "Silent" argument in the option string
    factory = TMVA.Factory( "TMVAClassification", outputFile, 
                            "!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification" )

    # Set verbosity
    factory.SetVerbose( verbose )
    
    # let's open the input files
    if lepton == ELECTRON:

        print "Lepton is ELECTRON."
        path = "/data3/jmitrevs/lepphoton/elphoton_ntuple2/mergedFiles/"

        wino_600_200FileName = path + "wino_600_200_el.root"
        wino_600_500FileName = path + "wino_600_500_el.root"
        wino_1000_200FileName = path + "wino_1000_200_el.root"
        wino_1500_300FileName = path + "wino_1500_300_el.root"
        
        WlepnuFileName_Np0 = path + "Wenu_Np0.root"
        WlepnuFileName_Np1 = path + "Wenu_Np1.root"
        WlepnuFileName_Np2 = path + "Wenu_Np2.root"
        WlepnuFileName_Np3 = path + "Wenu_Np3.root"
        WlepnuFileName_Np4 = path + "Wenu_Np4.root"
        WlepnuFileName_Np5 = path + "Wenu_Np5.root"

        ZleplepFileName_Np0 = path + "Zee_Np0.root"
        ZleplepFileName_Np1 = path + "Zee_Np1.root"
        ZleplepFileName_Np2 = path + "Zee_Np2.root"
        ZleplepFileName_Np3 = path + "Zee_Np3.root"
        ZleplepFileName_Np4 = path + "Zee_Np4.root"
        ZleplepFileName_Np5 = path + "Zee_Np5.root"

        st_tchan_lepnuFileName   = path + "st_tchan_enu.root"
        st_schan_lepnuFileName   = path + "st_schan_enu.root"
        ZleplepgammaFileName = path + "Zeegamma.root"

    elif lepton == MUON:

        print "Lepton is MUON."
        path = "/data3/jmitrevs/lepphoton/muphoton2/mergedFiles/"

        wino_600_200FileName = path + "wino_600_200_mu.root"
        wino_600_500FileName = path + "wino_600_500_mu.root"
        wino_1000_200FileName = path + "wino_1000_200_mu.root"
        wino_1500_300FileName = path + "wino_1500_300_mu.root"

        WlepnuFileName_Np0 = path + "Wmunu_Np0.root"
        WlepnuFileName_Np1 = path + "Wmunu_Np1.root"
        WlepnuFileName_Np2 = path + "Wmunu_Np2.root"
        WlepnuFileName_Np3 = path + "Wmunu_Np3.root"
        WlepnuFileName_Np4 = path + "Wmunu_Np4.root"
        WlepnuFileName_Np5 = path + "Wmunu_Np5.root"

        ZleplepFileName_Np0 = path + "Zmumu_Np0.root"
        ZleplepFileName_Np1 = path + "Zmumu_Np1.root"
        ZleplepFileName_Np2 = path + "Zmumu_Np2.root"
        ZleplepFileName_Np3 = path + "Zmumu_Np3.root"
        ZleplepFileName_Np4 = path + "Zmumu_Np4.root"
        ZleplepFileName_Np5 = path + "Zmumu_Np5.root"

        st_tchan_lepnuFileName   = path + "st_tchan_munu.root"
        st_schan_lepnuFileName   = path + "st_schan_munu.root"
        ZleplepgammaFileName = path + "Zmumugamma.root"

    else:
        raise ValueError("Lepton has to be ELECTRON or MUON.")

    
    WtaunuFileName_Np0 = path + "Wtaunu_Np0.root"
    WtaunuFileName_Np1 = path + "Wtaunu_Np1.root"
    WtaunuFileName_Np2 = path + "Wtaunu_Np2.root"
    WtaunuFileName_Np3 = path + "Wtaunu_Np3.root"
    WtaunuFileName_Np4 = path + "Wtaunu_Np4.root"
    WtaunuFileName_Np5 = path + "Wtaunu_Np5.root"

    ZtautauFileName_Np0 = path + "Ztautau_Np0.root"
    ZtautauFileName_Np1 = path + "Ztautau_Np1.root"
    ZtautauFileName_Np2 = path + "Ztautau_Np2.root"
    ZtautauFileName_Np3 = path + "Ztautau_Np3.root"
    ZtautauFileName_Np4 = path + "Ztautau_Np4.root"
    ZtautauFileName_Np5 = path + "Ztautau_Np5.root"

    st_tchan_taunuFileName = path + "st_tchan_taunu.root"    
    st_schan_taunuFileName = path + "st_schan_taunu.root"
    st_WtFileName   = path + "st_Wt.root"    
    
    WgammaFileName_Np0 = path + "Wgamma_Np0.root"
    WgammaFileName_Np1 = path + "Wgamma_Np1.root"
    WgammaFileName_Np2 = path + "Wgamma_Np2.root"
    WgammaFileName_Np3 = path + "Wgamma_Np3.root"
    WgammaFileName_Np4 = path + "Wgamma_Np4.root"
    WgammaFileName_Np5 = path + "Wgamma_Np5.root"
    
    ttbarFileName = path + "ttbar.root"

    WWFileName = path + "WW.root"
    WZFileName = path + "WZ.root"
    ZZFileName = path + "ZZ.root"

    ZtautaugammaFileName = path + "Ztautaugamma.root"

    
    ###########################################

    
    wino_600_200File = TFile(wino_600_200FileName)
    wino_600_500File = TFile(wino_600_500FileName)
    wino_1000_200File = TFile(wino_1000_200FileName)
    wino_1500_300File = TFile(wino_1500_300FileName)

    WlepnuFile_Np0 = TFile(WlepnuFileName_Np0)
    WlepnuFile_Np1 = TFile(WlepnuFileName_Np1)
    WlepnuFile_Np2 = TFile(WlepnuFileName_Np2)
    WlepnuFile_Np3 = TFile(WlepnuFileName_Np3)
    WlepnuFile_Np4 = TFile(WlepnuFileName_Np4)
    WlepnuFile_Np5 = TFile(WlepnuFileName_Np5)
    
    WtaunuFile_Np0 = TFile(WtaunuFileName_Np0)
    WtaunuFile_Np1 = TFile(WtaunuFileName_Np1)
    WtaunuFile_Np2 = TFile(WtaunuFileName_Np2)
    WtaunuFile_Np3 = TFile(WtaunuFileName_Np3)
    WtaunuFile_Np4 = TFile(WtaunuFileName_Np4)
    WtaunuFile_Np5 = TFile(WtaunuFileName_Np5)

    ZleplepFile_Np0 = TFile(ZleplepFileName_Np0)
    ZleplepFile_Np1 = TFile(ZleplepFileName_Np1)
    ZleplepFile_Np2 = TFile(ZleplepFileName_Np2)
    ZleplepFile_Np3 = TFile(ZleplepFileName_Np3)
    ZleplepFile_Np4 = TFile(ZleplepFileName_Np4)
    ZleplepFile_Np5 = TFile(ZleplepFileName_Np5)
    
    ZtautauFile_Np0 = TFile(ZtautauFileName_Np0)
    ZtautauFile_Np1 = TFile(ZtautauFileName_Np1)
    ZtautauFile_Np2 = TFile(ZtautauFileName_Np2)
    ZtautauFile_Np3 = TFile(ZtautauFileName_Np3)
    ZtautauFile_Np4 = TFile(ZtautauFileName_Np4)
    ZtautauFile_Np5 = TFile(ZtautauFileName_Np5)
    
    WgammaFile_Np0 = TFile(WgammaFileName_Np0)
    WgammaFile_Np1 = TFile(WgammaFileName_Np1)
    WgammaFile_Np2 = TFile(WgammaFileName_Np2)
    WgammaFile_Np3 = TFile(WgammaFileName_Np3)
    WgammaFile_Np4 = TFile(WgammaFileName_Np4)
    WgammaFile_Np5 = TFile(WgammaFileName_Np5)
    
    ttbarFile = TFile(ttbarFileName)
    
    st_tchan_lepnuFile   = TFile(st_tchan_lepnuFileName)
    st_tchan_taunuFile = TFile(st_tchan_taunuFileName)
    
    st_schan_lepnuFile   = TFile(st_schan_lepnuFileName)
    st_schan_taunuFile = TFile(st_schan_taunuFileName)
    
    st_WtFile   = TFile(st_WtFileName)

    WWFile = TFile(WWFileName)
    WZFile = TFile(WZFileName)
    ZZFile = TFile(ZZFileName)
    
    ZleplepgammaFile = TFile(ZleplepgammaFileName)
    ZtautaugammaFile = TFile(ZtautaugammaFileName)

    ###########################################

    
    wino_600_200Tree = wino_600_200File.Get("GammaLepton")
    wino_600_500Tree = wino_600_500File.Get("GammaLepton")
    wino_1000_200Tree = wino_1000_200File.Get("GammaLepton")
    wino_1500_300Tree = wino_1500_300File.Get("GammaLepton")

    WlepnuTree_Np0 = WlepnuFile_Np0.Get("GammaLepton")
    WlepnuTree_Np1 = WlepnuFile_Np1.Get("GammaLepton")
    WlepnuTree_Np2 = WlepnuFile_Np2.Get("GammaLepton")
    WlepnuTree_Np3 = WlepnuFile_Np3.Get("GammaLepton")
    WlepnuTree_Np4 = WlepnuFile_Np4.Get("GammaLepton")
    WlepnuTree_Np5 = WlepnuFile_Np5.Get("GammaLepton")
    
    WtaunuTree_Np0 = WtaunuFile_Np0.Get("GammaLepton")
    WtaunuTree_Np1 = WtaunuFile_Np1.Get("GammaLepton")
    WtaunuTree_Np2 = WtaunuFile_Np2.Get("GammaLepton")
    WtaunuTree_Np3 = WtaunuFile_Np3.Get("GammaLepton")
    WtaunuTree_Np4 = WtaunuFile_Np4.Get("GammaLepton")
    WtaunuTree_Np5 = WtaunuFile_Np5.Get("GammaLepton")

    ZleplepTree_Np0 = ZleplepFile_Np0.Get("GammaLepton")
    ZleplepTree_Np1 = ZleplepFile_Np1.Get("GammaLepton")
    ZleplepTree_Np2 = ZleplepFile_Np2.Get("GammaLepton")
    ZleplepTree_Np3 = ZleplepFile_Np3.Get("GammaLepton")
    ZleplepTree_Np4 = ZleplepFile_Np4.Get("GammaLepton")
    ZleplepTree_Np5 = ZleplepFile_Np5.Get("GammaLepton")
    
    ZtautauTree_Np0 = ZtautauFile_Np0.Get("GammaLepton")
    ZtautauTree_Np1 = ZtautauFile_Np1.Get("GammaLepton")
    ZtautauTree_Np2 = ZtautauFile_Np2.Get("GammaLepton")
    ZtautauTree_Np3 = ZtautauFile_Np3.Get("GammaLepton")
    ZtautauTree_Np4 = ZtautauFile_Np4.Get("GammaLepton")
    ZtautauTree_Np5 = ZtautauFile_Np5.Get("GammaLepton")
    
    WgammaTree_Np0 = WgammaFile_Np0.Get("GammaLepton")
    WgammaTree_Np1 = WgammaFile_Np1.Get("GammaLepton")
    WgammaTree_Np2 = WgammaFile_Np2.Get("GammaLepton")
    WgammaTree_Np3 = WgammaFile_Np3.Get("GammaLepton")
    WgammaTree_Np4 = WgammaFile_Np4.Get("GammaLepton")
    WgammaTree_Np5 = WgammaFile_Np5.Get("GammaLepton")
    
    ttbarTree = ttbarFile.Get("GammaLepton")
    
    st_tchan_lepnuTree   = st_tchan_lepnuFile.Get("GammaLepton")
    st_tchan_taunuTree = st_tchan_taunuFile.Get("GammaLepton")
    
    st_schan_lepnuTree   = st_schan_lepnuFile.Get("GammaLepton")
    st_schan_taunuTree = st_schan_taunuFile.Get("GammaLepton")
    
    st_WtTree   = st_WtFile.Get("GammaLepton")

    WWTree = WWFile.Get("GammaLepton")
    WZTree = WZFile.Get("GammaLepton")
    ZZTree = ZZFile.Get("GammaLepton")
    
    ZleplepgammaTree = ZleplepgammaFile.Get("GammaLepton")
    ZtautaugammaTree = ZtautaugammaFile.Get("GammaLepton")
    
    ##############################
    # and now the weights

    # wino_600_200_scale = 7.005
    # wino_600_500_scale = 3.03021
    # wino_1000_200_scale = 4.1325
    # wino_1500_300_scale = 0.16
    # Wlepnu_Np0_scale = 12.0052623622
    # Wlepnu_Np1_scale = 3.13076456857
    # Wlepnu_Np2_scale = 0.60296853897
    # Wlepnu_Np3_scale = 0.603183318846
    # Wlepnu_Np4_scale = 0.62088
    # Wlepnu_Np5_scale = 0.600008571551
    # Wtaunu_Np0_scale = 12.1457006649
    # Wtaunu_Np1_scale = 3.12868868923
    # Wtaunu_Np2_scale = 0.602359552172
    # Wtaunu_Np3_scale = 0.602586672951
    # Wtaunu_Np4_scale = 0.62088496708
    # Wtaunu_Np5_scale = 0.638769230769
    # Zleplep_Np0_scale = 0.631361988532
    # Zleplep_Np1_scale = 0.629541167757
    # Zleplep_Np2_scale = 0.625618828688
    # Zleplep_Np3_scale = 0.634090909091
    # Zleplep_Np4_scale = 0.6
    # Zleplep_Np5_scale = 0.51875
    # Ztautau_Np0_scale = 0.631228327261
    # Ztautau_Np1_scale = 0.631347664299
    # Ztautau_Np2_scale = 0.622916409433
    # Ztautau_Np3_scale = 0.640077378243
    # Ztautau_Np4_scale = 0.581269375646
    # Ztautau_Np5_scale = 0.48125
    # Wgamma_Np0_scale = 0.0129441737417
    # Wgamma_Np1_scale = 0.0635170304401
    # Wgamma_Np2_scale = 0.140920227273
    # Wgamma_Np3_scale = 0.140622611111
    # Wgamma_Np4_scale = 0.134589
    # Wgamma_Np5_scale = 0.123308
    # ttbar_scale = 0.0384505023442
    # st_tchan_lepnu_scale = 0.200916540624
    # st_tchan_taunu_scale = 0.201132004918
    # st_schan_lepnu_scale = 0.0092735093327
    # st_schan_taunu_scale = 0.00926981472204
    # st_Wt_scale = 0.0916407781992
    # WW_scale = 0.0342151663714
    # WZ_scale = 0.110873818259
    # ZZ_scale = 0.0252773011092
    # Zleplepgamma_scale = 0.963
    # Ztautaugamma_scale = 0.941960800016

    #################ntuple_pt25
    # wino_600_200_scale = 1.401
    # wino_600_500_scale = 3.03021
    # wino_1000_200_scale = 4.1325
    # wino_1500_300_scale = 0.16
    # Wlepnu_Np0_scale = 12.0052623622
    # Wlepnu_Np1_scale = 3.13076456857
    # Wlepnu_Np2_scale = 0.60296853897
    # Wlepnu_Np3_scale = 0.603183318846
    # Wlepnu_Np4_scale = 0.62088
    # Wlepnu_Np5_scale = 0.600008571551
    # Wtaunu_Np0_scale = 12.1457006649
    # Wtaunu_Np1_scale = 3.12868868923
    # Wtaunu_Np2_scale = 0.602359552172
    # Wtaunu_Np3_scale = 0.602586672951
    # Wtaunu_Np4_scale = 0.62088496708
    # Wtaunu_Np5_scale = 0.638769230769
    # Zleplep_Np0_scale = 0.631361988532
    # Zleplep_Np1_scale = 0.629541167757
    # Zleplep_Np2_scale = 0.625618828688
    # Zleplep_Np3_scale = 0.634090909091
    # Zleplep_Np4_scale = 0.6
    # Zleplep_Np5_scale = 0.51875
    # Ztautau_Np0_scale = 0.631228327261
    # Ztautau_Np1_scale = 0.631347664299
    # Ztautau_Np2_scale = 0.622916409433
    # Ztautau_Np3_scale = 0.640077378243
    # Ztautau_Np4_scale = 0.581269375646
    # Ztautau_Np5_scale = 0.48125
    # Wgamma_Np0_scale = 1.08706263428
    # Wgamma_Np1_scale = 0.734676952566
    # Wgamma_Np2_scale = 0.733754057143
    # Wgamma_Np3_scale = 0.149752323594
    # Wgamma_Np4_scale = 0.157524392683
    # Wgamma_Np5_scale = 0.1281354
    # ttbar_scale = 0.0384505023442
    # st_tchan_lepnu_scale = 0.200916540624
    # st_tchan_taunu_scale = 0.201132004918
    # st_Wt_scale = 0.0916407781992
    # WW_scale = 0.0342151663714
    # WZ_scale = 0.110873818259
    # ZZ_scale = 0.0252773011092
    # Zleplepgamma_scale = 0.963
    # Ztautaugamma_scale = 0.941960800016
    # gamma_Np1_scale = 4.06453310851
    # gamma_Np2_scale = 3.3709968686
    # gamma_Np3_scale = 1.38728943513
    # gamma_Np4_scale = 1.41464077802
    # gamma_Np5_scale = 1.23661096137


    if lepton == ELECTRON:
        wino_600_200_scale = 0.291875
        wino_600_500_scale = 2.69352
        wino_1000_200_scale = 4.1325
        wino_1500_300_scale = 0.0093269
        wino_1000_100_scale = 69.5
        wino_800_700_scale = 0.2328
        Wlepnu_Np0_scale = 12.0052623622
        Wlepnu_Np1_scale = 3.13076456857
        Wlepnu_Np2_scale = 0.60296853897
        Wlepnu_Np3_scale = 0.603183318846
        Wlepnu_Np4_scale = 0.62088
        Wlepnu_Np5_scale = 0.600008571551
        Wtaunu_Np0_scale = 12.1457006649
        Wtaunu_Np1_scale = 3.12868868923
        Wtaunu_Np2_scale = 0.602359552172
        Wtaunu_Np3_scale = 0.602586672951
        Wtaunu_Np4_scale = 0.62088496708
        Wtaunu_Np5_scale = 0.638769230769
        Zleplep_Np0_scale = 0.631361988532
        Zleplep_Np1_scale = 0.629541167757
        Zleplep_Np2_scale = 0.625618828688
        Zleplep_Np3_scale = 0.634090909091
        Zleplep_Np4_scale = 0.6
        Zleplep_Np5_scale = 0.51875
        Ztautau_Np0_scale = 0.631228327261
        Ztautau_Np1_scale = 0.631347664299
        Ztautau_Np2_scale = 0.622916409433
        Ztautau_Np3_scale = 0.640077378243
        Ztautau_Np4_scale = 0.581269375646
        Ztautau_Np5_scale = 0.48125
        Wgamma_Np0_scale = 0.0132834003639
        Wgamma_Np1_scale = 0.0651816146862
        Wgamma_Np2_scale = 0.144613309091
        Wgamma_Np3_scale = 0.144307893333
        Wgamma_Np4_scale = 0.13811616
        Wgamma_Np5_scale = 0.12653952
        ttbar_scale = 0.0384505023442
        st_tchan_lepnu_scale = 0.200916540624
        st_tchan_taunu_scale = 0.201132004918
        st_Wt_scale = 0.0916407781992
        WW_scale = 0.0342151663714
        WZ_scale = 0.110873818259
        ZZ_scale = 0.0252773011092
        Zleplepgamma_scale = 0.963
        Ztautaugamma_scale = 0.941960800016
        gamma_Np1_scale = 4.17064063358
        gamma_Np2_scale = 3.35244054801
        gamma_Np3_scale = 1.36994217452
        gamma_Np4_scale = 1.41464077802
        gamma_Np5_scale = 1.23661096137
    elif lepton == MUON:
        wino_600_200_scale = 0.291875
        Wlepnu_Np0_scale = 11.9925371604
        Wlepnu_Np1_scale = 3.13058966
        Wlepnu_Np2_scale = 0.601616497017
        Wlepnu_Np3_scale = 0.605913424797
        Wlepnu_Np4_scale = 0.606001176701
        Wlepnu_Np5_scale = 0.593142857143
        Wtaunu_Np0_scale = 12.1457006649
        Wtaunu_Np1_scale = 3.12868868923
        Wtaunu_Np2_scale = 0.602359552172
        Wtaunu_Np3_scale = 0.602586672951
        Wtaunu_Np4_scale = 0.62088496708
        Wtaunu_Np5_scale = 0.638769230769
        Zleplep_Np0_scale = 0.631664271554
        Zleplep_Np1_scale = 0.628327597475
        Zleplep_Np2_scale = 0.62551337696
        Zleplep_Np3_scale = 0.635795454545
        Zleplep_Np4_scale = 0.572916666667
        Zleplep_Np5_scale = 0.48125
        Ztautau_Np0_scale = 0.631228327261
        Ztautau_Np1_scale = 0.631347664299
        Ztautau_Np2_scale = 0.622916409433
        Ztautau_Np3_scale = 0.640077378243
        Ztautau_Np4_scale = 0.581269375646
        Ztautau_Np5_scale = 0.48125
        Wgamma_Np0_scale = 0.0132834003639
        Wgamma_Np1_scale = 0.0651816146862
        Wgamma_Np2_scale = 0.144613309091
        Wgamma_Np3_scale = 0.144307893333
        Wgamma_Np4_scale = 0.13811616
        Wgamma_Np5_scale = 0.12653952
        ttbar_scale = 0.0384505023442
        st_tchan_lepnu_scale = 0.201919368378
        st_tchan_taunu_scale = 0.201132004918
        st_Wt_scale = 0.0916407781992
        WW_scale = 0.0342151663714
        WZ_scale = 0.110873818259
        ZZ_scale = 0.0252773011092
        Zleplepgamma_scale = 0.963963963964
        Ztautaugamma_scale = 0.941960800016
        gamma_Np1_scale = 4.08704733658
        gamma_Np2_scale = 3.35244054801
        gamma_Np3_scale = 1.36994217452
        gamma_Np4_scale = 1.41464077802
        gamma_Np5_scale = 1.23661096137
        

    if signal == "600_200":
        factory.AddSignalTree(wino_600_200Tree, wino_600_200_scale)
    elif signal == "600_500":
        factory.AddSignalTree(wino_600_500Tree, wino_600_500_scale)
    elif signal == "1000_200":
        factory.AddSignalTree(wino_1000_200Tree, wino_1000_200_scale)
    elif signal == "1500_300":
        factory.AddSignalTree(wino_1500_300Tree, wino_1500_300_scale)
    else:
        print "*** signal designation not supported: %s ****" % signal
        sys.exit(1)

    factory.AddBackgroundTree(WlepnuTree_Np0, Wlepnu_Np0_scale)
    factory.AddBackgroundTree(WlepnuTree_Np1, Wlepnu_Np1_scale)
    factory.AddBackgroundTree(WlepnuTree_Np2, Wlepnu_Np2_scale)
    factory.AddBackgroundTree(WlepnuTree_Np3, Wlepnu_Np3_scale)
    factory.AddBackgroundTree(WlepnuTree_Np4, Wlepnu_Np4_scale)
    factory.AddBackgroundTree(WlepnuTree_Np5, Wlepnu_Np5_scale)
    
    #factory.AddBackgroundTree(WtaunuTree_Np0, Wtaunu_Np0_scale)
    factory.AddBackgroundTree(WtaunuTree_Np1, Wtaunu_Np1_scale)
    factory.AddBackgroundTree(WtaunuTree_Np2, Wtaunu_Np2_scale)
    factory.AddBackgroundTree(WtaunuTree_Np3, Wtaunu_Np3_scale)
    factory.AddBackgroundTree(WtaunuTree_Np4, Wtaunu_Np4_scale)
    factory.AddBackgroundTree(WtaunuTree_Np5, Wtaunu_Np5_scale)

    # factory.AddBackgroundTree(ZleplepTree_Np0, Zleplep_Np0_scale)
    # factory.AddBackgroundTree(ZleplepTree_Np1, Zleplep_Np1_scale)
    # factory.AddBackgroundTree(ZleplepTree_Np2, Zleplep_Np2_scale)
    # factory.AddBackgroundTree(ZleplepTree_Np3, Zleplep_Np3_scale)
    # factory.AddBackgroundTree(ZleplepTree_Np4, Zleplep_Np4_scale)
    # factory.AddBackgroundTree(ZleplepTree_Np5, Zleplep_Np5_scale)
    
    # factory.AddBackgroundTree(ZtautauTree_Np0, Ztautau_Np0_scale)
    # factory.AddBackgroundTree(ZtautauTree_Np1, Ztautau_Np1_scale)
    # factory.AddBackgroundTree(ZtautauTree_Np2, Ztautau_Np2_scale)
    # factory.AddBackgroundTree(ZtautauTree_Np3, Ztautau_Np3_scale)
    # factory.AddBackgroundTree(ZtautauTree_Np4, Ztautau_Np4_scale)
    # factory.AddBackgroundTree(ZtautauTree_Np5, Ztautau_Np5_scale)
    
    factory.AddBackgroundTree(WgammaTree_Np0, Wgamma_Np0_scale)
    factory.AddBackgroundTree(WgammaTree_Np1, Wgamma_Np1_scale)
    factory.AddBackgroundTree(WgammaTree_Np2, Wgamma_Np2_scale)
    factory.AddBackgroundTree(WgammaTree_Np3, Wgamma_Np3_scale)
    factory.AddBackgroundTree(WgammaTree_Np4, Wgamma_Np4_scale)
    factory.AddBackgroundTree(WgammaTree_Np5, Wgamma_Np5_scale)
    
    factory.AddBackgroundTree(ttbarTree, ttbar_scale)
    
    factory.AddBackgroundTree(st_tchan_lepnuTree, st_tchan_lepnu_scale)
    factory.AddBackgroundTree(st_tchan_taunuTree, st_tchan_taunu_scale)
    
    # factory.AddBackgroundTree(st_schan_lepnuTree, st_schan_lepnu_scale)
    # factory.AddBackgroundTree(st_schan_taunuTree, st_schan_taunu_scale)
    
    factory.AddBackgroundTree(st_WtTree, st_Wt_scale)

    factory.AddBackgroundTree(WWTree, WW_scale)
    factory.AddBackgroundTree(WZTree, WZ_scale)
    factory.AddBackgroundTree(ZZTree, ZZ_scale)
    
    factory.AddBackgroundTree(ZleplepgammaTree, Zleplepgamma_scale)
    factory.AddBackgroundTree(ZtautaugammaTree, Ztautaugamma_scale)
    


    # note that you may also use variable expressions, such as: "3*var1/var2*abs(var3)"
    # [all types of expressions that can also be parsed by TTree::Draw( "expression" )]
    factory.AddVariable( "MET := sqrt(Metx*Metx+Mety*Mety)", 'F' )
    # factory.AddVariable( "HT", 'F' )
    factory.AddVariable( "PhotonPt[0]", 'F' )
    #factory.AddVariable( "ElectronPt[0]", 'F' )
    if lepton == ELECTRON:
        factory.AddVariable( "mTel", 'F' )
    else:
        factory.AddVariable( "mTmu", 'F' )
    #factory.AddVariable( "abs(PhotonEta[0])", 'F' )
    #factory.AddVariable( "abs(ElectronEta[0])", 'F' )

    # Apply additional cuts on the signal and background sample. 
    # example for cut: mycut = TCut( "abs(var1)<0.5 && abs(var2-0.5)<1" )
    #mycutSig = TCut( "abs(PhotonEta[0]) < 2.01 && abs(ElectronEta[0]) < 2.01" ) 

    if lepton == ELECTRON:
        mycutSig = TCut( "sqrt((PhotonEta[0]-ElectronEta[0])*(PhotonEta[0]-ElectronEta[0]) + (PhotonPhi[0]-ElectronPhi[0])*(PhotonPhi[0]-ElectronPhi[0])) > 0.7")
    else:
        mycutSig = TCut( "sqrt((PhotonEta[0]-MuonEta[0])*(PhotonEta[0]-MuonEta[0]) + (PhotonPhi[0]-MuonPhi[0])*(PhotonPhi[0]-MuonPhi[0])) > 0.7")
    #mycutSig = TCut( "PhotonPt[0] > 85000" ) 
    mycutBkg = mycutSig 
    
    # Here, the relevant variables are copied over in new, slim trees that are
    # used for TMVA training and testing
    # "SplitMode=Random" means that the input events are randomly shuffled before
    # splitting them into training and test samples
    factory.PrepareTrainingAndTestTree( mycutSig, mycutBkg,
                                        "nTrain_Signal=0:nTrain_Background=0:SplitMode=Random:NormMode=NumEvents:!V" )

    # --------------------------------------------------------------------------------------------------

    # ---- Book MVA methods
    #
    # please lookup the various method configuration options in the corresponding cxx files, eg:
    # src/MethoCuts.cxx, etc, or here: http://tmva.sourceforge.net/optionRef.html
    # it is possible to preset ranges in the option string in which the cut optimisation should be done:
    # "...:CutRangeMin[2]=-1:CutRangeMax[2]=1"...", where [2] is the third input variable

    # Cut optimisation
    if "Cuts" in mlist:
        factory.BookMethod( TMVA.Types.kCuts, "Cuts",
                            "!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart" )

    if "CutsD" in mlist:
        factory.BookMethod( TMVA.Types.kCuts, "CutsD",
                            "!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart:VarTransform=Decorrelate" )

    if "CutsPCA" in mlist:
        factory.BookMethod( TMVA.Types.kCuts, "CutsPCA",
                            "!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart:VarTransform=PCA" )

    # if "CutsGA" in mlist:
    #     factory.BookMethod( TMVA.Types.kCuts, "CutsGA",
    #                         "H:!V:FitMethod=GA:CutRangeMin[0]=-10:CutRangeMax[0]=10:VarProp[1]=FMax:EffSel:Steps=30:Cycles=3:PopSize=400:SC_steps=10:SC_rate=5:SC_factor=0.95" )

    # if "CutsSA" in mlist:
    #     factory.BookMethod( TMVA.Types.kCuts, "CutsSA",
    #                         "!H:!V:FitMethod=SA:EffSel:MaxCalls=150000:KernelTemp=IncAdaptive:InitialTemp=1e+6:MinTemp=1e-6:Eps=1e-10:UseDefaultScale" )


    # --------------------------------------------------------------------------------------------------
            
    # ---- Now you can tell the factory to train, test, and evaluate the MVAs. 

    # Train MVAs
    factory.TrainAllMethods()
    
    # Test MVAs
    factory.TestAllMethods()
    
    # Evaluate MVAs
    factory.EvaluateAllMethods()    
    
    # Save the output.
    outputFile.Close()
    
    print "=== wrote root file %s\n" % outfname
    print "=== TMVAClassification is done!\n"
    
    # open the GUI for the result macros    
    gROOT.ProcessLine( "TMVAGui(\"%s\")" % outfname )
    
    # keep the ROOT thread running
    gApplication.Run()