// Silly macro to run the classes that optimize supercuts 
// using ON and OFF data.

// The user only needs to fill/change the variables that control 
// the optimization procedure.


gROOT -> Reset();

void SuperCutsONOFFMacro()
{
  gLog.SetNoColors();

    // File containing the data (ON/OFF DATA and path for files (root/ps))

    // From magicserv01
    TString  ONDataFilename("/.magic/data16a/mazin/data/Mrk421/2004_04_22/4slices/Hillas_20040422_4sl_time_clean/Mrk421_*_HillasON.root");
                                       
    TString  OFFDataFilename("/.magic/data16a/mazin/data/Mrk421/2004_04_22/4slices/Hillas_20040422_4sl_time_clean/Mrk421_*_HillasOFF.root");

    
    TString PathForFiles ("/mnt/magicserv01/scratch/David/SillyTestForCommiting_July20_2004/");

    
    // **********************************************
    // Boolean variables defining the job of the 
    // macro
    // **********************************************

    

    // Boolean variable that decides wether data is read from files specified above
    // (ON/OFF) or read from already existing Matrices (which are obviously stored
    // in a root file). The names of the files storing those matrices are produced 
    // automatically using information provided by some of the next variables whose 
    // values must be specified by user.

    // kTRUE reads alredy existing matrices, and kFALSE read data and produce matrices.

    Bool_t ReadMatrixFromRootFiles = kTRUE; 
  

    // Boolean variable that controls wether to use the 
    // TRAIN sample or not.
    

    Bool_t TrainParams   = kTRUE;  



    // Variable that allows the user to skip the optimization on the 
    // train sample. If optimization is skipped (value kTRUE), the
    // previously optimized supercuts (stored in root file
    // which is called OptSCParametersONOFFThetaRangeXXXXXmRad.root, and located 
    // in the directory specified by variable PathForFiles) are used 
    // on the train and/or the test sample.

    // If value kFALSE, the cuts are optimized.
    // The optimized cuts will be  written in root file
    // located in directory specified before. Name of 
    // the root files is created automatically.
    
    Bool_t SkipOptimization = kTRUE;
  




    // Boolean variable that allows the user to write the initial parameters 
    // into the root file that will be used to store the optimum cuts.
    // If ApplyInitialParams = kTRUE , the initial 
    // parameters are written into this root file, and they 
    // will be applied to the data (TRAIN/TEST ) 
    // IF NO OPTIMIZATION PROCEDURE IS PERFORMED.
    
    // If cuts are optimized (ie, variable SkipOptimization = kFALSE), 
    // the cuts applied to the data are the optimized cuts.
  
    // NOTE: be aware that, if ApplyInitialSCParams = kTRUE and 
    // there was a root file with the optimized cuts 
    // (previously computed), it will be overwritten with the initial 
    // SC parameters. 

    Bool_t ApplyInitialSCParams = kTRUE;
    


    // Boolean variable that controls wether to use the 
    // TEST sample or not.
    

    Bool_t TestParams = kFALSE;  


    // Boolean variable that controls wether to combine, OR not, the 
    // alpha distributions computed (after cuts) for the several theta bins
    // in which the TRAIN sample was divided.

    Bool_t CombineCosThetaBinsForTrainSample = kFALSE; 
    
    // Boolean variable that controls wether to combine, OR not, the 
    // alpha distribution computed (after cuts) for the several theta bins
    // in which the TEST sample was divided.

    Bool_t CombineCosThetaBinsForTestSample = kFALSE; 
    

    // Fraction of ON events used for the training/testing
    Double_t whichfractiontrain = 0.999;
    Double_t whichfractiontest = 0.001;

    // Fraction of OFF events used for the training/testing 
    Double_t whichfractiontrainOFF = 0.999;
    Double_t whichfractiontestOFF = 0.001;


    // Efficiency for gammas when using this set of dynamical cuts
    // (i.e., fraction of initial gammas that remain after cuts)

    // Current value is the first estimation of the efficiency of cuts
    // on Mkn421 at a SIZE > 2000 photons

    Double_t gammaeff = 0.6;  
                         

    // Alpha value (degrees) below which signal is expected
    
    Double_t alphasig = 12; 

    // Definition of alpha bkg region (where no signal is expected)

    Double_t alphabkgmin = 30;
    Double_t alphabkgmax = 90;
    
    // Definition of the Size range

    Double_t SizeLow = 800;
    Double_t SizeUp = 1200;
//    Double_t SizeUp = 1000000;
    

     // Definition of binning of alpha plots
    Int_t NAlphaBins = 35;
    Double_t AlphaBinLow = -9;
    Double_t AlphaBinUp = 96;

 
    // Boolean variable used to determine wether the normalization factor is 
    // computed from method 1) or 2)
    // 1) Using total number of ON and OFF events before cuts, and tuning the factor 
    //    correcting for "contamination" of gamma events in ON sample 
    // 2) Using number of ON and OFF events after cuts in the background 
    //    region determined by variables fAlphaBkgMin-fAlphaBkgMax
    
    Bool_t NormFactorFromAlphaBkg = kTRUE; // if kTRUE, method 2) is used


    // Boolean variable used to disable the usage ("serious" usage) of the 
    // quantities computed from fits. This will be useful in those cases 
    // where there is too few events to perform a decent fit to the 
    // alpha histograms.
    
    Bool_t UseFittedQuantities = kTRUE;


    // Boolean variable used to control wether to use theta information 
    // in the computation of teh dynamical cuts that take place within
    // class MCT1SupercutsCalc
    Bool_t NotUseTheta = kTRUE; // kTRUE renoves theta from the parameterization of cuts

    // Boolean variable used to decide wether to use dynamical cuts or static cuts
    // kTRUE means that static cuts are used.
    Bool_t UseStaticCuts = kFALSE;





    // Name of the Postscript document where all plots
    // will be saved.
    // STORAGE OF PSFILE IS NOT WORKING PROPERLY
    // For the time being, several ps files are produced 
    // and saved in the directory specified by PathForFiles

    /*
    TString PsFileName = ("PsTest23.ps");
    TString CompletePsFileName = (PathForFiles);
    CompletePsFileName += PsFileName;
    TPostScript* PsFile = new TPostScript(CompletePsFileName, 111);
    */

    // Boolean variable used to decide wether initial parameters are 
    // read from ascii file or not. If kTRUE, parameters are retrieved 
    // from ascii file. Otherwise, default parameters from MSupercuts 
    // class are used.

    Bool_t ReadInitParamsFromAsciiFile = kTRUE;

    // Number of SC parameters. The aim of this variable is to cross check 
    // that the number of parameters read from an ascii file 
    // is teh one the user wants. 

    Int_t NInitSCPar = 104;

    // Name of  the ascii file containing the 2 columns, the first one 
    // for initial parameters and the second one for the steps
    // Name must contain also the path.
 
    const char* InitSCParamAsciiFile = 
      // {"../InitialSCParametersSteps/InitSCParamsAndStepsDanielModified1.txt"};
      // {"../InitialSCParametersSteps/FixedStaticCutsInLengthWidthDist.txt"};
      // {"../InitialSCParametersSteps/FixedStaticCutsInLengthWidthDist11.txt"};
      // {"../InitialSCParametersSteps/InitSCParamsAndStepsDanielModified1.txt"};
      // {"../InitialSCParametersSteps/StartingValuesForOptimizationMkn421.txt"};
      // {"../InitialSCParametersSteps/StartingValuesForOptimizationMkn421DynStaticCutsFixedPol2SizeCut3000.txt"};
      // {"../InitialSCParametersSteps/StartingValuesForOptimizationMkn421DynWithDistParametersFixed.txt"};
      // {"../InitialSCParametersSteps/StartingValuesForOptimizationMkn421DynStaticCutsVariablePol2.txt"};
      // {"../InitialSCParametersSteps/StartingValuesForOptimizationMkn421DynStaticCutsVariablePol2WidthCutLowFixed.txt"};
      // {"../InitialSCParametersSteps/StartingValuesForOptimizationMkn421DynCutsOnSize.txt"};
      // {"../InitialSCParametersSteps/StartingValuesForOptimizationMkn421DynCutsOnSizeAndDist.txt"};
      {"mtemp/mmpi/asciifiles/OptimizedMkn421DynCutsGridWithSelected22pointsMay19.txt"};


    // Name of the root file where alpha distributions, TTree objects
    // with info about the events and cuts applied and  info support histograms 
    // will be stored. 
    // Write only the name of the file. The Path 
    // is the one defined previously

    TString RootFilename = ("RootFileDynCuts.root");

    

    
    

    // Vector containing the theta bins in which data (ON/OFF train/test)
    // will be divided. Actually this vector contains the cosinus of 
    // these theta bins. The dimension of the vector is N+1, where 
    // N is the number of theta bins intended. The first component of the 
    // vector is the low bin edge of the first bin, and the last 
    // vector component the upper bin edge of the last bin.


    TArrayD CosThetaRangeVector(2);
    CosThetaRangeVector[0] = 0.0;
    //CosThetaRangeVector[1] = 0.825;
    //CosThetaRangeVector[2] = 0.921; 
    //CosThetaRangeVector[3] = 0.961; 
    CosThetaRangeVector[1] = 1.0;


    /*
    TArrayD CosThetaRangeVector(2);
    CosThetaRangeVector[0] = 0.622;
    // CosThetaRangeVector[1] = 0.825;
    //CosThetaRangeVector[2] = 0.921; 
    //CosThetaRangeVector[0] = 0.961; 
    CosThetaRangeVector[1] = 0.984;
    
    */
    // Object of MCT1FindSupercutsONOFFThetaLoop created, data that was specified 
    // above is introduced and ... and the party starts.
     
    MFindSupercutsONOFFThetaLoop FindSupercuts("MFindSupercutsONOFFThetaLoop", 
					       "Optimizer for the supercuts");

    
    FindSupercuts.SetPathForFiles(PathForFiles);

    FindSupercuts.SetDataONOFFRootFilenames(ONDataFilename, OFFDataFilename);

    FindSupercuts.SetFractionTrainTestOnOffEvents(whichfractiontrain, 
						  whichfractiontest, 
						  whichfractiontrainOFF, 
						  whichfractiontestOFF);


    FindSupercuts.SetGammaEfficiency(gammaeff);


    FindSupercuts.SetAlphaSig(alphasig);

    // Bkg alpha region is set 
    FindSupercuts.SetAlphaBkgMin(alphabkgmin);
    FindSupercuts.SetAlphaBkgMax(alphabkgmax);

    // alpha bkg and signal region set in object FindSupercuts
    // are re-checked in order to be sure that make sense
	
    FindSupercuts.CheckAlphaSigBkg();


    // binning for alpha plots is defined

    FindSupercuts.SetAlphaPlotBinining(NAlphaBins, AlphaBinLow, 
				       AlphaBinUp);




    // Size range is defined

    FindSupercuts.SetSizeRange(SizeLow, SizeUp);



    FindSupercuts.SetNormFactorFromAlphaBkg(NormFactorFromAlphaBkg);

    FindSupercuts.SetUseFittedQuantities(UseFittedQuantities);

    FindSupercuts.SetVariableUseStaticCuts(UseStaticCuts);

    FindSupercuts.SetVariableNotUseTheta(NotUseTheta);

    FindSupercuts.SetReadMatricesFromFile(ReadMatrixFromRootFiles);

    FindSupercuts.SetTrainParameters(TrainParams);
    FindSupercuts.SetSkipOptimization(SkipOptimization);
    FindSupercuts.SetUseInitialSCParams(ApplyInitialSCParams);

    FindSupercuts.SetTestParameters(TestParams);

   
    
    FindSupercuts.SetHadronnessName("MHadSC");
    FindSupercuts.SetHadronnessNameOFF("MHadOFFSC");
    
    FindSupercuts.SetAlphaDistributionsRootFilename (RootFilename);
    
    // FindSupercuts.SetPostScriptFile (PsFile);

    FindSupercuts.SetCosThetaRangeVector (CosThetaRangeVector);
    

    // Names for all root files (matrices, alpha distributions...)
    // are created 
    FindSupercuts.SetALLNames();

    if(ReadInitParamsFromAsciiFile)
    {
	// Initial SC Parameters and steps are retrieved from 
	// Ascii file
	if(!FindSupercuts.ReadSCParamsFromAsciiFile(InitSCParamAsciiFile,
						    NInitSCPar))
	{
	    cout << "Initial SC Parameters could not be read from Ascii file "
		 << InitSCParamAsciiFile << endl
		 << "Aborting execution of macro... " << endl;
	    return;

	}
    }
 
   


    // Finally loop over all theta bins defined is executed
    
    if (!FindSupercuts.LoopOverThetaRanges())
      {
	cout << "Function MFindSupercutsONOFFThetaLoop::LoopOverThetaRanges()" << endl
	     << "could not be performed" << endl;

      }

    

    // Nex and Significance are computed vs alphasig
    
    if (!FindSupercuts.ComputeNexSignificanceVSAlphaSig())
      {
	cout << "Function MFindSupercutsONOFFThetaLoop::ComputeNexSignificanceVSAlphaSig()" << endl
	     << "could not be performed" << endl;
	

      }
    



    // Option to store ps files in a single ps document is still not working
    /*
    PsFile -> Close();
    PsFile = NULL;
    */

    // Several theta bins are combined to produced a single alpha plot (for train and test)
    // with single Nex and significances

    if (CombineCosThetaBinsForTrainSample || CombineCosThetaBinsForTestSample)
    {
	if(!FindSupercuts.ComputeOverallSignificance(CombineCosThetaBinsForTrainSample, 
						     CombineCosThetaBinsForTestSample))
	  {
	    cout << "Function MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance" << endl
		 << "could not be performed" << endl;
	  }
       

    }


   
}





















