Ejemplo n.º 1
0
void SetParameter(const unsigned int i, const unsigned int num_params, TMinuit& minuit){
  if(i==num_params-3){
    minuit.DefineParameter(i, "chi_b", 10.0, 1.0, 0.0, 0.0);
  }else if(i==num_params-2){
    minuit.DefineParameter(i, "chi_c", 10.0, 1.0, 0.0, 0.0);
  }else if(i==num_params-1){
    minuit.DefineParameter(i, "sig str", 0.5, 0.05, 0.0, 0.0);
  }else if(i<num_params-3){
    char name[128];
    switch(i%5){
    case 0:
      sprintf(name, "mu (%d)", i/5);
      break;
    case 1:
      sprintf(name, "As (%d)", i/5);
      break;
    case 2:
      sprintf(name, "Bs (%d)", i/5);
      break;
    case 3:
      sprintf(name, "Cs (%d)", i/5);
      break;
    case 4:
      sprintf(name, "Ds (%d)", i/5);
      break;
    }
    minuit.DefineParameter(i, name, 10.0, 1.0, 0.0, 0.0);
  }
}
Ejemplo n.º 2
0
std::vector<double> run_fit(double parSRS){
    TMinuit minuit;
    double arglist[10];
    int iflag;
    arglist[0] = -1;
    minuit.mnexcm("SET PRINT",arglist,1,iflag);
    minuit.mnexcm("SET NOW",arglist,0,iflag);
    minuit.SetFCN(fcn);
    minuit.mnexcm("SET STR",arglist,1,iflag);
    minuit.mnparm(0,"parSRS",parSRS,0.1,-100,100,iflag);

    arglist[0] = 10000;
    arglist[1] = 0.01;
    minuit.mnexcm("MIGRAD",arglist,2,iflag);
    minuit.mnexcm("HESSE",arglist,0,iflag);

    double fmin, fedm,errdef;
    int npari, nparx, istat;
    minuit.mnstat(fmin,fedm,errdef,npari,nparx,istat);

    double val,err;
    std::vector<double> ret_ary;
    for(int p = 0; p < 1; p++) {
        minuit.GetParameter(p, val, err);
        ret_ary.push_back(val);
    }
    ret_ary.push_back(fmin);

    return ret_ary;
}
Ejemplo n.º 3
0
float getR(TMinuit& m) {
  //get results
  Double_t amin,edm,errdef;
  Int_t nvpar,nparx,icstat;
  m.mnstat(amin,edm,errdef,nvpar,nparx,icstat);
  return amin;
}
//______________________________________________________________________________
vector< vector<double> > cSpline(int nPoints, int npar, vector <double> xData, vector <double> yData, vector <double> yErrorData, double stepSpline, double start, double step)
{
	//Populate the global variables//-> DONE IN THE MAIN
	xData_GLOB = xData;//-> DONE IN THE MAIN
	yData_GLOB = yData;//-> DONE IN THE MAIN
	yErrorData_GLOB = yErrorData;//-> DONE IN THE MAIN

	//Initialize Minuit
	vector<double> vstart, vstep;
	for(int i=0; i<npar; i++) 	//set starting values and step sizes for parameters
	{
		vstart.push_back(start);
		vstep.push_back(step);
	}

	TMinuit *myMinuit = new TMinuit(npar);  //initialize TMinuit with a maximum of npar (5) -> PASSED AS ARGUMENT
	myMinuit->SetFCN(fcn);//-> DONE IN THE MAIN
	myMinuit->SetPrintLevel(-1);//No output: -1, output:1//-> DONE IN THE MAIN

	double arglist[10];//-> DONE IN THE MAIN
	int ierflg = 0;//-> DONE IN THE MAIN
	arglist[0] = 1;//-> DONE IN THE MAIN
	myMinuit->mnexcm("SET ERR", arglist, 1, ierflg);//-> DONE IN THE MAIN

	for (int i = 0; i < npar; i++) {//-> DONE IN THE MAIN
		stringstream ss;//-> DONE IN THE MAIN
		ss<<"a"<<i;//-> DONE IN THE MAIN
		myMinuit->mnparm(i, ss.str().c_str(), vstart.at(i), vstep.at(i), 0, 0, ierflg);//-> DONE IN THE MAIN
	}//-> DONE IN THE MAIN

	//Perform the Minuit fit
	arglist[0] = 500;//-> DONE IN THE MAIN
	arglist[1] = 1.;//-> DONE IN THE MAIN
	myMinuit->mnexcm("MIGRAD", arglist, 2, ierflg); //minimization

	//Retrieve best-fit parameters
	vector< double > bestFitParams, e_bestFitParams;
	for(int i=0; i<npar; i++)
	{
		double par, epar;
		myMinuit->GetParameter(i, par, epar); //retrieve best fit parameters
		bestFitParams.push_back(par);
		e_bestFitParams.push_back(epar);
	}

	//Store the best-fit spline in a TGraph
	gsl_spline_init (spline_GLOB, &xData[0], &bestFitParams[0], xData.size()); //initialize the spline

	int nPointsSpline = int ((xData[nPoints-1]-xData[0])/stepSpline); //calculate the number of points of the spline

	vector< vector<double> > cSplineValues;
	cSplineValues.push_back( vector< double > ());//x
	cSplineValues.push_back( vector< double > ());//y
	for (int i= 0; i < nPointsSpline; i++){
		cSplineValues[0].push_back(xData[0]+i*stepSpline);
		cSplineValues[1].push_back(gsl_spline_eval (spline_GLOB, cSplineValues[0].back(), acc_GLOB));
	}

	return cSplineValues;
}
Ejemplo n.º 5
0
//______________________________________________________________________________
void Ifit()
{
// The z values
	z[0]=1;
	z[1]=0.96;
	z[2]=0.89;
	z[3]=0.85;
	z[4]=0.78;
// The errors on z values
        Float_t error = 0.01;
	errorz[0]=error;
	errorz[1]=error;
	errorz[2]=error;
	errorz[3]=error;
	errorz[4]=error;
// the x values
	x[0]=1.5751;
	x[1]=1.5825;
	x[2]=1.6069;
	x[3]=1.6339;
	x[4]=1.6706;
// the y values
	y[0]=1.0642;
	y[1]=0.97685;
	y[2]=1.13168;
	y[3]=1.128654;
	y[4]=1.44016;

   TMinuit *gMinuit = new TMinuit(5);  //initialize TMinuit with a maximum of 5 params
   gMinuit->SetFCN(fcn);

   Double_t arglist[10];
   Int_t ierflg = 0;

   arglist[0] = 1;
   gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);

// Set starting values and step sizes for parameters
   static Double_t vstart[4] = {3, 1 , 0.1 , 0.01};
   static Double_t step[4] = {0.1 , 0.1 , 0.01 , 0.001};
   gMinuit->mnparm(0, "a1", vstart[0], step[0], 0,0,ierflg);
   gMinuit->mnparm(1, "a2", vstart[1], step[1], 0,0,ierflg);
   gMinuit->mnparm(2, "a3", vstart[2], step[2], 0,0,ierflg);
   gMinuit->mnparm(3, "a4", vstart[3], step[3], 0,0,ierflg);

// Now ready for minimization step
   arglist[0] = 500;
   arglist[1] = 1.;
   gMinuit->mnexcm("MIGRAD", arglist ,2,ierflg);

// Print results
   Double_t amin,edm,errdef;
   Int_t nvpar,nparx,icstat;
   gMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
   //gMinuit->mnprin(3,amin);

}
Ejemplo n.º 6
0
// --------------------------------- //
void make_lin_fit(double & slope, double & d_slope, double & offset, double & d_offset){
    TMinuit min;
    min.SetPrintLevel(-1);
    //min.SetPrintLevel(0);
    int err = min.DefineParameter(0, "slope", slope, d_slope, 0.05, 1.0);
    assert(err==0);
    err = min.DefineParameter(1, "offset", offset, d_offset, 0.001, 0.2);
    assert(err==0);
    min.SetFCN(chi2_linear);
    min.mnmigr();
    min.GetParameter(0, slope, d_slope);
    min.GetParameter(1, offset, d_offset);
}
Ejemplo n.º 7
0
vector<double> fit()
{
  vector<double> out(2*nbeta+1);
  
  TMinuit minu;
  //minu.SetPrintLevel(-1);
  minu.SetFCN(ch2);
  //set tolerance
  double tol=1e-16;
  int iflag;
  //minu.SetMaxIterations(10000000);
  //minu.mnexcm("SET ERR",&tol,1,iflag);
  
  for(int ib=0;ib<nbeta;ib++)
    {
      minu.DefineParameter(2*ib+0,"infi",1,0.001,0,0);
      minu.DefineParameter(2*ib+1,"coef",1,0.001,0,0);
    }
  minu.DefineParameter(2*nbeta,"M",0,0.001,0,0);
  
  minu.Migrad();
  
  double dum;
  for(int ib=0;ib<=2*nbeta;ib++) minu.GetParameter(ib,out[ib],dum);
  
  return out;
}
Ejemplo n.º 8
0
void unbinFitosc_pts()
{
  TMinuit *gMinuit = new TMinuit(4);
  gMinuit -> SetFCN(mll_fit_pts);
  
  Double_t arglist[10];
  Double_t vstart[10];
  Double_t step[10];

  Double_t p0=0,p1=1,p2=2,p3=3;
  Int_t ierflg=0;
 
  Double_t par0;
  Double_t err0;

  // Set to 0.5 for likelihood, 1 for chisquare

  arglist[0] = 0.5;
  gMinuit->mnexcm("SET ERR", arglist, 1, ierflg);

  // Set initial values of parameters

  vstart[0] = oscpar0_init;

  step[0] = oscerr0_step;

  gMinuit->mnparm(0, "mistag", vstart[0], step[0], 0., 0., ierflg);


  // Do minimization
  arglist[0] = 3000.;
  arglist[1] = 0.1;
  gMinuit->mnexcm("CALL FCN", &p1, 1, ierflg);
  gMinuit->mnexcm("MIGRAD", arglist, 2, ierflg);
  gMinuit->mnexcm("CALL FCN", &p3, 1, ierflg);

  // Get parameters 
  gMinuit->GetParameter(0,par0,err0);


  // Export the fitted parameters so we can graph them.

  fitpar=par0;

  fiterr=err0;


  RooComplex ct = RooMath::ComplexErrFunc(2.,1.);
  Double_t ctre=ct.re();
  Double_t ctim=ct.im();
  printf("ct  %10.5f  %10.5f  \n",ctre,ctim);

  delete gMinuit;

}
Ejemplo n.º 9
0
Double_t Fitter::MinuitFit() {
  TMinuit *gMinuit = new TMinuit(1);
  gMinuit->SetFCN(ChiSquare);
  
  //settings 
  Double_t arglist[6];
  Int_t ierflg = 0;
  
  // Set starting values and step sizes for parameters
  gMinuit->mnparm(0, "Sig", _W1, _step, _W1min, _W1max,ierflg);
  //gMinuit->mnparm(0, "Sig", _W1, _step,0,0,ierflg);
  
  // Now ready for minimization step
  gMinuit->mnexcm("MIGRAD", arglist ,0,ierflg);
  
  // Print results
  Double_t amin,edm,errdef;
  Int_t nvpar,nparx,icstat;
  gMinuit->mnstat(amin, edm, errdef, nvpar, nparx, icstat);
  gMinuit->mnprin(3, amin);
  
  //gMinuit->mnexcm("MINOS", arglist ,0,ierflg);
  for(int i=0; i<1; i++)
    {
      gMinuit -> GetParameter(i, _W1, _W1err);
      cout<<"Parameter fit  "<<i<<" value "<<_W1<<" err "<<_W1err<<endl;
    }
  
  delete gMinuit;
  
  //calculate bkg error:
  double entries_mc = _hsig->Integral(_hdata->GetXaxis()->FindBin(_xmin), _hdata->GetXaxis()->FindBin(_xmax));
  double entries_bkg = _hbkg->Integral(_hdata->GetXaxis()->FindBin(_xmin), _hdata->GetXaxis()->FindBin(_xmax));
  _W2err = _W1err*entries_mc/entries_bkg;

  return amin;
}
Ejemplo n.º 10
0
void fit(boot &A,boot &B,boot &C,boot &D,bvec &X,bvec &Y)
{
  //copy X
  X_fit=new double[nens];
  for(int iens=0;iens<nens;iens++) X_fit[iens]=X[iens].med();
  Y_fit=new double[nens];
  err_Y_fit=new double[nens];
  
  TMinuit minu;
  minu.SetPrintLevel(-1);
  
  int npars=4;
  minu.DefineParameter(0,"A",0.0,0.0001,0,0);
  minu.DefineParameter(1,"B",0.0,0.0001,0,0);
  minu.DefineParameter(2,"C",0.0,0.0001,0,0);
  minu.DefineParameter(3,"D",0.0,0.0001,0,0);
  if(!include_a4)
    {
      minu.FixParameter(3);
      npars--;
    }
  if(!include_ml_term)
    {
      minu.FixParameter(1);
      npars--;
    }
  minu.SetFCN(chi2_wr);
  
  double C2;
  for(int iboot=0;iboot<nboot+1;iboot++)
    {
      if(iboot>0)
        minu.SetPrintLevel(-1);
      
      minu.DefineParameter(4,"a380",lat[0][iboot],0.0001,0,0);
      minu.DefineParameter(5,"a390",lat[1][iboot],0.0001,0,0);
      minu.DefineParameter(6,"a405",lat[2][iboot],0.0001,0,0);
      minu.DefineParameter(7,"a420",lat[3][iboot],0.0001,0,0);
      minu.FixParameter(4);
      minu.FixParameter(5);
      minu.FixParameter(6);
      minu.FixParameter(7);
      
      for(int iens=0;iens<nens;iens++)
        {
          Y_fit[iens]=Y.data[iens].data[iboot];
          err_Y_fit[iens]=Y.data[iens].err();
        }
      
      //minimize
      minu.Migrad();
      
      //get back parameters
      double dum;
      minu.GetParameter(0,A.data[iboot],dum);
      minu.GetParameter(1,B.data[iboot],dum);
      minu.GetParameter(2,C.data[iboot],dum);
      minu.GetParameter(3,D.data[iboot],dum);
      
      double lat_med[4]={lat[0].med(),lat[1].med(),lat[2].med(),lat[3].med()};
      if(iboot==0) C2=chi2(A.data[iboot],B[iboot],C[iboot],D[iboot],lat_med);
    }
  
  int ninc_ens=0;
  for(int iens=0;iens<nens;iens++)
    if(ibeta[iens]!=0 || include_380) ninc_ens++;
  
  //calculate the chi2
  cout<<"A=("<<A<<"), B=("<<B<<"), C=("<<C<<"), D=("<<D<<")"<<endl;
  cout<<"Chi2 = "<<C2<<" / "<<ninc_ens-npars<<" = "<<C2/(ninc_ens-npars)<<endl;
  
  delete[] X_fit;
  delete[] Y_fit;
  delete[] err_Y_fit;
}
void runAngleOpt() {

  gSystem->AddIncludePath("-I${ANITA_UTIL_INSTALL_DIR}/include");

  double startVal=0;               
  double stepSize=0.1;       
  double minVal=-2;           
  double maxVal=2;            
  Double_t p0 = 0;

  //Load libraries. Need to have ANITA_UTIL_INSTALL_DIR/lib and ROOTSYS/lib in the LD_LIBRARY_PATH               
  gSystem->Load("libfftw3.so");
  gSystem->Load("libMathMore.so");
  gSystem->Load("libPhysics.so");  
  gSystem->Load("libGeom.so");  
  gSystem->Load("libMinuit.so");  
  gSystem->Load("libRootFftwWrapper.so");         
  gSystem->Load("libAnitaEvent.so");      
  gSystem->Load("libAnitaCorrelator.so");

  AnitaGeomTool *fGeomTool = AnitaGeomTool::Instance();
  gSystem->CompileMacro("anglePlotterOpt.C","k");
  
  Double_t relDeltaOut=0;

  TMinuit *myMin = new TMinuit(1);
  myMin->SetObjectFit(anglePlotterOpt);
  myMin->SetFCN(iHateRoot);
  //setArray();

  for(int u = 0; u < 1; u++){

    int middle = 16;

      for(int y = 16; y <32; y++){

	int leftOpt, rightOpt;
	fGeomTool->getThetaPartners(middle,leftOpt,rightOpt); 


	myMin->DefineParameter(0, "antNum", middle, stepSize, minVal, maxVal);
	myMin->FixParameter(0);  
    
	myMin->DefineParameter(1, "deltaT", startVal, stepSize, minVal, maxVal);

  
	Double_t deltaT,deltaTErr;
  
	//*********MINUIT METHOD*******************
	myMin->SetPrintLevel(-1);
	myMin->Migrad();   
	myMin->GetParameter(1,deltaT,deltaTErr);

  

	setValue(rightOpt,deltaT);

	//	printArray();

	//	cout << middle << "  " << rightOpt << "  " << deltaT << endl;
  
	cout << "deltaTArrayMod[" << rightOpt << "] = " << deltaT << ";" << endl;

	middle = rightOpt;

      }

  }

  
  //   myMin->DeleteArrays();

  //   myMin->DeleteArrays();

  
}
Ejemplo n.º 12
0
//_________________________________________________________________________________
void integratedSplinesV5(double seed = 231)
{
    //Load the data
    int nEvents = 1000; //number of times the data will be randomized
    int nPoints = 9;
    double lowerBound = 10; //bounds for random vector function
    double upperBound = 20;
    double lowerErrorBound = 1;
    double upperErrorBound = 2;

    vector< vector<double> > xEvents, yEvents, yErrorEvents; //each of these is a vector of vectors (of randomized data points)
    for(int i = 0; i < nEvents; i++)
    {
        vector <double> xData, yData, yErrorData; //temporary vectors that are only used to get random values from FillRand function
        FillRandVectors(nPoints, xData, yData, yErrorData, seed*(i+1), lowerBound, upperBound, lowerErrorBound, upperErrorBound); //populates random vectors for y values and y error vector
        xEvents.push_back(xData);
        yEvents.push_back(yData);
        yErrorEvents.push_back(yErrorData);
        //Populate the global variables
        xData_GLOB = xData;
        yData_GLOB = yData;
        yErrorData_GLOB = yErrorData;
    }

    //Intialization of the variables
    const int npar = nPoints;
    const int orderSpline = 4;
    const int nbreak = npar+2-orderSpline;
    double stepSpline = 0.01;
    double xminBSplineWorkspace = 0;
    double xmaxBSplineWorkspace = 9;
    double startCSplineWorkspace = 15.;
    double stepCSplineWorkspace = 1.5;

    acc_GLOB = gsl_interp_accel_alloc ();
    spline_GLOB = gsl_spline_alloc (gsl_interp_cspline, nPoints);
    gsl_bspline_workspace *bw = gsl_bspline_alloc(orderSpline, nbreak);

//Setup for the C-spline_________________________________________________________________________

    //Setting up TMinuit for C-spline minimization
    TMinuit *myMinuit = new TMinuit(npar);  //initialize TMinuit with a maximum of npar
    myMinuit->SetFCN(fcn);
    myMinuit->SetPrintLevel(-1); //No output: -1, output:1

    double arglist[10];
    int ierflg = 0;
    arglist[0] = 1;
    myMinuit->mnexcm("SET ERR", arglist, 1, ierflg);

    vector<double> vstart, vstep;
    for(int i=0; i < npar; i++) 	//set starting values and step sizes for parameters
    {
        vstart.push_back(startCSplineWorkspace);
        vstep.push_back(stepCSplineWorkspace);
    }

    for (int i = 0; i < npar; i++)
    {
        stringstream ss;
        ss<<"a"<<i;
        myMinuit->mnparm(i, ss.str().c_str(), vstart.at(i), vstep.at(i), 0, 0, ierflg);
    }

    //Perform the Minuit fit
    arglist[0] = 500;
    arglist[1] = 1.;

//Setup for the B-spline_________________________________________________________________________
    //Declare and allocate memory to compose data set of control points
    gsl_vector *xControl = gsl_vector_alloc(nPoints);
    gsl_vector *yControl = gsl_vector_alloc(nPoints);
    gsl_vector *w = gsl_vector_alloc(nPoints);
    gsl_vector *B = gsl_vector_alloc(npar);
    gsl_matrix *X = gsl_matrix_alloc(nPoints, npar);

    //Create a b spline workspace and allocate its memory
    gsl_bspline_knots_uniform(xminBSplineWorkspace, xmaxBSplineWorkspace, bw);
    //Set up the variables for the fit matrix
    for (int i = 0; i < nPoints; ++i)
    {
        gsl_bspline_eval(gsl_vector_get(xControl, i), B, bw); //Compute B_j(xi) for all j
        for (int j = 0; j < npar; ++j)	gsl_matrix_set(X, i, j, gsl_vector_get(B, j)); //Fill in row i of X
    }

    gsl_vector *c = gsl_vector_alloc(npar);
    gsl_multifit_linear_workspace *mw = gsl_multifit_linear_alloc(nPoints, npar);
    gsl_matrix *cov = gsl_matrix_alloc(npar, npar);

//B and C spline loops__________________________________________________________________________
    clock_t tbstart, tbstop, tcstart, tcstop;
    vector <double> timeb, timec;

    vector< vector<double> > xBSplineValues, yBSplineValues;
    vector< vector<double> > xCSplineValues, yCSplineValues;

    for(int i = 0; i < (int)xEvents.size(); i++)
    {
        //Populate gsl vectors with the appropriate data
        for (int j = 0; j < nPoints; j++)
        {
            double xi = xEvents[i][j];
            double yi = yEvents[i][j];
            double sigma = yErrorEvents[i][j];
            gsl_vector_set(xControl, j, xi);
            gsl_vector_set(yControl, j, yi);
            gsl_vector_set(w, j, 1.0/(sigma*sigma));
        }

        tbstart = clock();
        vector< vector<double> > bSplineValues = bSpline(xEvents.at(i),stepSpline, bw, yControl, B, X, c, mw, cov);
        tbstop = clock();
        timeb.push_back(((float)tbstop-(float)tbstart)/ (CLOCKS_PER_SEC/1000.) );

        xBSplineValues.push_back(bSplineValues.at(0));
        yBSplineValues.push_back(bSplineValues.at(1));

        tcstart = clock();
        vector< vector<double> > cSplineValues = cSpline(nPoints, npar, xEvents.at(i), stepSpline, myMinuit, arglist, ierflg);
        tcstop = clock();
        timec.push_back(((float)tcstop-(float)tcstart)/ (CLOCKS_PER_SEC/1000.) );

        xCSplineValues.push_back(cSplineValues.at(0));
        yCSplineValues.push_back(cSplineValues.at(1));
    }

    //Histograms______________________________________________________________________________________

    //Time
    int nbins = 100;
    double xlow = 0;
    double xup = 1.;

    TH1D *hTimeB = new TH1D("Time","Timing; time [ms]; Number of Events", nbins, xlow, xup);
    hTimeB->SetStats(0);
    TH1D *hTimeC = new TH1D("TimeC","Timing; time [ms]; Number of Events", nbins, xlow, xup);
    hTimeC->SetLineColor(kRed);
    hTimeC->SetStats(0);

    for(int i=0; i<(int)timec.size(); i++)
    {
        hTimeB->Fill(timeb.at(i));
        hTimeC->Fill(timec.at(i));
    }

    //Interpolation distance
    vector <double> interpB, interpC;
    for(int i = 0; i < (int)yEvents.size(); i++)
    {
        for(int j = 0; j < (int)yEvents[i].size(); j++)
        {
            double key = xEvents[i][j];
            int indexForB = binarySearch(xBSplineValues[i], key);
            int indexForC = binarySearch(xCSplineValues[i], key);
            if(indexForB != -1)
                interpB.push_back( (yEvents[i][j]-yBSplineValues[i][indexForB])/yErrorEvents[i][indexForB] );
            if(indexForC != -1)
                interpC.push_back( (yEvents[i][j]-yCSplineValues[i][indexForC])/yErrorEvents[i][indexForC] );
        }
    }

    int nbinsI = 40;
    int xlowI = -4;
    int xupI = 4;
    TH1D *hInterpB = new TH1D("Interp B","Interpolation; Distance between spline and data normalized by error; Number of Events", nbinsI, xlowI, xupI);
    for(int i=0; i<(int)interpB.size(); i++) hInterpB->Fill(interpB.at(i));
    hInterpB->SetStats(0);


    TH1D *hInterpC = new TH1D("Interp C","Interpolation; Distance between spline and data normalized by error; Number of Events", nbinsI, xlowI, xupI);
    for (int i=0; i<(int)interpC.size(); i++) hInterpC->Fill(interpC.at(i));
    hInterpC->SetLineColor(kRed);
    hInterpC->SetStats(0);

    //Draws______________________________________________________________________________________

    //Interpolation
    TLegend *legInterp = new TLegend(0.9,0.70,0.75,0.85);
    legInterp->SetLineColor(kWhite);
    legInterp->SetFillColor(kWhite);
    legInterp->SetMargin(0.3);
    legInterp->AddEntry(hInterpB,"b-spline","l");
    legInterp->AddEntry(hInterpC,"c-spline","l");
    legInterp->SetTextSize(0.05);

    TCanvas *c1 = new TCanvas("c1", "Interpolation distance");
    c1->cd();
    hInterpB->Draw("");
    hInterpC->Draw("same");
    legInterp->Draw();

    //Time
    TLegend *legTime = new TLegend(0.9,0.70,0.75,0.85);
    legTime->SetLineColor(kWhite);
    legTime->SetFillColor(kWhite);
    legTime->SetMargin(0.3);
    legTime->AddEntry(hTimeB,"b-spline","l");
    legTime->AddEntry(hTimeC,"c-spline","l");
    legTime->SetTextSize(0.05);

    TCanvas *c2 = new TCanvas("c2", "Computation time");
    c2->cd();
    hTimeB->Draw("");
    hTimeC->Draw("same");
    legTime-> Draw();

    //Free the memory____________________________________________________________________________
    gsl_spline_free (spline_GLOB);
    gsl_interp_accel_free (acc_GLOB);
    gsl_bspline_free(bw);
    gsl_vector_free(xControl);
    gsl_vector_free(yControl);
    gsl_vector_free(B);
    gsl_matrix_free(X);
    gsl_vector_free(c);
    gsl_multifit_linear_free(mw);
    gsl_matrix_free(cov);
}
Ejemplo n.º 13
0
//_________________________________________________________________________________
void integratedSplinesV4a(double seed = 231)
{
    //Load the data
    int nEvents = 1000; //number of times the data will be randomized
    int nPoints = 9;

    vector< vector<double> > xEvents, yEvents, yErrorEvents; //each of these is a vector of vectors (of randomized data points)
    for(int i = 0; i < nEvents; i++)
    {
        vector <double> xData, yData, yErrorData; //temporary vectors that are only used to get random values from FillRand function
        FillRandVectors(nPoints, xData, yData, yErrorData, seed*(i+1)); //populates random vectors for y values and y error vector
        xEvents.push_back(xData);
        yEvents.push_back(yData);
        yErrorEvents.push_back(yErrorData);
        //Populate the global variables
        xData_GLOB = xData;
        yData_GLOB = yData;
        yErrorData_GLOB = yErrorData;
    }

    //Intialization of the variables
    const int npar = nPoints;
    const int orderSpline = 4;
    const int nbreak = npar+2-orderSpline;
    double stepSpline = 0.01;
    double xminBSplineWorkspace = 0;
    double xmaxBSplineWorkspace = 9;
    double startCSplineWorkspace = 15.;
    double stepCSplineWorkspace = 1.5;

    acc_GLOB = gsl_interp_accel_alloc ();
    spline_GLOB = gsl_spline_alloc (gsl_interp_cspline, nPoints);
    gsl_bspline_workspace *bw = gsl_bspline_alloc(orderSpline, nbreak);

    //Setting up TMinuit for C-spline minimization
    TMinuit *myMinuit = new TMinuit(npar);  //initialize TMinuit with a maximum of npar (5)
    myMinuit->SetFCN(fcn);
    myMinuit->SetPrintLevel(-1);//No output: -1, output:1

    double arglist[10];
    int ierflg = 0;
    arglist[0] = 1;
    myMinuit->mnexcm("SET ERR", arglist, 1, ierflg);

    vector<double> vstart, vstep;
    for(int i=0; i < npar; i++) 	//set starting values and step sizes for parameters
    {
        vstart.push_back(startCSplineWorkspace);
        vstep.push_back(stepCSplineWorkspace);
    }

    for (int i = 0; i < npar; i++)
    {
        stringstream ss;
        ss<<"a"<<i;
        myMinuit->mnparm(i, ss.str().c_str(), vstart.at(i), vstep.at(i), 0, 0, ierflg);
    }

    //Perform the Minuit fit
    arglist[0] = 500;
    arglist[1] = 1.;

    //B and C spline loops__________________________________________________________________________
    clock_t tbstart, tbstop, tcstart, tcstop;
    vector <double> timeb, timec;

    vector< vector<double> > xBSplineValues, yBSplineValues;
    vector< vector<double> > xCSplineValues, yCSplineValues;
    for(int i = 0; i < (int)xEvents.size(); i++)
    {
        tbstart = clock();
        vector< vector<double> > bSplineValues = bSpline(nPoints, npar, xEvents.at(i), yEvents.at(i), yErrorEvents.at(i), stepSpline, xminBSplineWorkspace, xmaxBSplineWorkspace, bw);
        tbstop = clock();
        timeb.push_back(((float)tbstop-(float)tbstart)/ (CLOCKS_PER_SEC/1000.) );

        xBSplineValues.push_back(bSplineValues.at(0));
        yBSplineValues.push_back(bSplineValues.at(1));

        tcstart = clock();
        vector< vector<double> > cSplineValues = cSpline(nPoints, npar, xEvents.at(i), stepSpline, myMinuit, arglist, ierflg);
        tcstop = clock();
        timec.push_back(((float)tcstop-(float)tcstart)/ (CLOCKS_PER_SEC/1000.) );

        xCSplineValues.push_back(cSplineValues.at(0));
        yCSplineValues.push_back(cSplineValues.at(1));
    }

    //Histograms______________________________________________________________________________________

    //Time
    int nbins = 100;
    double xlow = 0;
    double xup = 5.;

    TH1D *hTimeB = new TH1D("Time","; time [ms]; number of runs", nbins, xlow, xup);
    hTimeB->SetStats(0);
    TH1D *hTimeC = new TH1D("TimeC","; time [ms]; number of runs", nbins, xlow, xup);
    hTimeC->SetLineColor(kRed);
    hTimeC->SetStats(0);

    for(int i=0; i<(int)timec.size(); i++)
    {
        hTimeB->Fill(timeb.at(i));
        hTimeC->Fill(timec.at(i));
    }

    //Interpolation distance -> Should FIND THE RIGHT J FOR SPLINE
    vector <double> interpB, interpC;
    for(int i = 0; i < (int)yEvents.size(); i++)
    {
        for(int j = 0; j < (int)yEvents[i].size(); j++)
        {
            double key = xEvents[i][j];
            int indexForB = binarySearch(xBSplineValues[i], key);
            int indexForC = binarySearch(xCSplineValues[i], key);
//			std::cout << "B: " << indexForB << " C: " << indexForC << endl;
            if(indexForB != -1)
                interpB.push_back( (yEvents[i][j]-yBSplineValues[i][indexForB])/yErrorEvents[i][indexForB] );
            if(indexForC != -1)
                interpC.push_back( (yEvents[i][j]-yCSplineValues[i][indexForC])/yErrorEvents[i][indexForC] );
        }
    }

    int nbinsI = 40;
    int xlowI = -4;
    int xupI = 4;
    TH1D *hInterpB = new TH1D("Interp B","; xAxis; yAxis", nbinsI, xlowI, xupI);
    for(int i=0; i<(int)interpB.size(); i++) hInterpB->Fill(interpB.at(i));
    hInterpB->SetStats(0);

    TH1D *hInterpC = new TH1D("Interp C","; xAxis; yAxis", nbinsI, xlowI, xupI);
    for (int i=0; i<(int)interpC.size(); i++) hInterpC->Fill(interpC.at(i));
    hInterpC->SetLineColor(kRed);
    hInterpC->SetStats(0);

    //Draws______________________________________________________________________________________

    //Interpolation distance
    TLegend *legInterp = new TLegend(0.75,0.70,0.4,0.85);
    legInterp->SetLineColor(kWhite);
    legInterp->SetFillColor(kWhite);
    legInterp->SetMargin(0.3);
    legInterp->AddEntry(hInterpB,"b-spline","l");
    legInterp->AddEntry(hInterpC,"c-spline","l");

    TCanvas *c1 = new TCanvas("c1", "Interpolation distance");
    c1->cd();
    hInterpB->Draw("");
    hInterpC->Draw("same");
    legInterp->Draw();

    //Time
    TLegend *legTime = new TLegend(0.75,0.70,0.4,0.85);
    legTime->SetLineColor(kWhite);
    legTime->SetFillColor(kWhite);
    legTime->SetMargin(0.3);
    legTime->AddEntry(hTimeB,"b-spline","l");
    legTime->AddEntry(hTimeC,"c-spline","l");

    TCanvas *c2 = new TCanvas("c2", "Computation time");
    c2->cd();
    hTimeB->Draw("");
    hTimeC->Draw("same");
    legTime-> Draw();

    //Free the memory for the spline
    gsl_spline_free (spline_GLOB); //frees the memory used by the spline
    gsl_interp_accel_free (acc_GLOB);
    gsl_bspline_free(bw);
}
void runQuickOptAllAntFixedZ() {
  
  gSystem->AddIncludePath("-I${ANITA_UTIL_INSTALL_DIR}/include");
  
  double startVal=0;               
  double stepSize=0.05;       
  double minVal=-0.5;           
  double maxVal=0.5;            
  Double_t p0 = 0;

  //Load libraries. Need to have ANITA_UTIL_INSTALL_DIR/lib and ROOTSYS/lib in the LD_LIBRARY_PATH               
  gSystem->Load("libfftw3.so");
  gSystem->Load("libMathMore.so");
  gSystem->Load("libPhysics.so");  
  gSystem->Load("libGeom.so");  
  gSystem->Load("libMinuit.so");  
  gSystem->Load("libRootFftwWrapper.so");         
  gSystem->Load("libAnitaEvent.so");      
  gSystem->Load("libAnitaCorrelator.so");

  AnitaGeomTool *fGeomTool = AnitaGeomTool::Instance();
  gSystem->CompileMacro("quickOptAllAntFixedZ.C","k");

  fillArrays(eventNumberIndex, thetaWaveIndex, phiWaveIndex, antIndex1, antIndex2, maxCorrTimeIndex, adjacent);
  
  Double_t relDeltaOut=0;

  TMinuit *myMin = new TMinuit(192);
  myMin->SetObjectFit(quickOptAllAntFixedZ);
  myMin->SetFCN(iHateRoot);
//   myMin->SetMaxIterations(2);
  //myMin->SetErrorDef(1000);

//   int ierflg;
//   double eps[1] = {2.};
//   myMin->mnexcm("SET EPS", eps, 1, ierflg);
  //setArray();

  double startValR[MAX_ANTENNAS] ={0};
  double startValZ[MAX_ANTENNAS] ={0};
  double startValPhi[MAX_ANTENNAS] ={0};
  double startValCableDelays[MAX_ANTENNAS] ={0};
  
  
  for(int y = 0; y <MAX_ANTENNAS; y++){
    
    char name[30];
    sprintf(name,"r%d",y);
    myMin->DefineParameter(y, name, startValR[y], stepSize, -0.1, 0.1);
    sprintf(name,"z%d",y);
    myMin->DefineParameter(y+MAX_ANTENNAS, name, startValZ[y], stepSize, -0.1, 0.1);
    myMin->FixParameter(y+MAX_ANTENNAS);
    sprintf(name,"phi%d",y);
    myMin->DefineParameter(y+MAX_ANTENNAS*2, name, startValPhi[y], stepSize, -0.1, 0.1);
    sprintf(name,"cable%d",y);
    myMin->DefineParameter(y+MAX_ANTENNAS*3, name, startValCableDelays[y], stepSize, -0.5, 0.5);
  }
  
  
  
  Double_t deltaR[MAX_ANTENNAS],deltaRErr[MAX_ANTENNAS];
  Double_t deltaZ[MAX_ANTENNAS],deltaZErr[MAX_ANTENNAS];
  Double_t deltaPhi[MAX_ANTENNAS],deltaPhiErr[MAX_ANTENNAS];
  Double_t deltaCableDelays[MAX_ANTENNAS],deltaCableDelaysErr[MAX_ANTENNAS];
  
  //*********MINUIT METHOD*******************
//   myMin->SetPrintLevel(-1);
  myMin->Migrad();
  //  int error_flag;
  //  myMin->mnexcm("MINOS",0,0,error_flag);  

  ofstream newfile("newLindaNumbersCableDelays_ALLANTENNAS_RMS_GRAD_FixedZ.txt");
  for(int u = 0; u <MAX_ANTENNAS; u++){
    myMin->GetParameter(u,deltaR[u],deltaRErr[u]);
    cout << "deltaR[" << u << "] = " << deltaR[u] << " +/- " << deltaRErr[u] << endl;
	
    
    myMin->GetParameter(u+MAX_ANTENNAS,deltaZ[u],deltaZErr[u]);
    cout << " deltaZ[" << u << "] = " << deltaZ[u] << " +/- " << deltaZErr[u] << endl;
    
    myMin->GetParameter(u+MAX_ANTENNAS*2,deltaPhi[u],deltaPhiErr[u]);
    cout << " deltaPhi[" << u << "] = " << deltaPhi[u] << " +/- " << deltaPhiErr[u] << endl;

    myMin->GetParameter(u+MAX_ANTENNAS*3,deltaCableDelays[u],deltaCableDelaysErr[u]);
    cout << " deltaCableDelays[" << u << "] = " << deltaCableDelays[u]  << " +/- " << deltaCableDelaysErr[u] << endl;
    
    newfile << u << "  " << deltaR[u]<< "  " << deltaZ[u]<< "  " << deltaPhi[u]<< "  " << deltaCableDelays[u] << endl;


  }
  
  
  cout << "Easy table" << endl;
  for(int u = 0; u <MAX_ANTENNAS; u++)  cout << u << " & " << deltaR[u]<< " & " << deltaZ[u]<< " & " << deltaPhi[u]<< " & " << deltaCableDelays[u] << endl;

  
}
void runTopRingOpt() {

  gSystem->AddIncludePath("-I${ANITA_UTIL_INSTALL_DIR}/include");

  double startVal=0;               
  double stepSize=0.1;       
  double minVal=-0.5;           
  double maxVal=0.5;            
  Double_t p0 = 0;

  //Load libraries. Need to have ANITA_UTIL_INSTALL_DIR/lib and ROOTSYS/lib in the LD_LIBRARY_PATH               
  gSystem->Load("libfftw3.so");
  gSystem->Load("libMathMore.so");
  gSystem->Load("libPhysics.so");  
  gSystem->Load("libGeom.so");  
  gSystem->Load("libMinuit.so");  
  gSystem->Load("libRootFftwWrapper.so");         
  gSystem->Load("libAnitaEvent.so");      
  gSystem->Load("libAnitaCorrelator.so");

  AnitaGeomTool *fGeomTool = AnitaGeomTool::Instance();
  gSystem->CompileMacro("topRingOpt.C","k");
  
  Double_t relDeltaOut=0;

  TMinuit *myMin = new TMinuit(150);
  myMin->SetObjectFit(topRingOpt);
  myMin->SetFCN(iHateRoot);
  //setArray();

  double startValDeltaT[16] ={0};
  double startValR[16] ={0};
  double startValPhi[16] ={0};

 //    startValDeltaT[0] =  -0.0519515;     startValR[0] =   -0.0101463;         startValPhi[0] =      -0.00473836 ;   
//     startValDeltaT[1] =     -0.0597062;   startValR[1] =      -0.02577;       startValPhi[1] =   0.00864501 ; 
//     startValDeltaT[2] =     -0.081435;     startValR[2] =     -0.000224044;    startValPhi[2] =   -0.000630649;
//     startValDeltaT[3] =     0.0118873;     startValR[3] =      0.019945;       startValPhi[3] =    0.014016;   
//     startValDeltaT[4] =      0.017917;      startValR[4] =     -0.00297559;    startValPhi[4] =    0.0224936 ;
//     startValDeltaT[5] =      0.0377119;     startValR[5] =     -0.014872;       startValPhi[5] =   0.0163349; 
//     startValDeltaT[6] =     -0.0426158;     startValR[6] =    -0.0562555;      startValPhi[6] =    0.0220065 ; 
//     startValDeltaT[7] =     -0.0221673;     startValR[7] =    -0.034104 ;      startValPhi[7] =    0.0158545 ; 
//     startValDeltaT[8] =      0.0263739;     startValR[8] =     0.00248804;      startValPhi[8] =    0.013246 ; 
//     startValDeltaT[9] =      -0.0938419;    startValR[9] =     -0.00344703;     startValPhi[9] =    -0.00718616; 
//     startValDeltaT[10] =      0.145264;      startValR[10] =     -0.0121874 ;     startValPhi[10] =     0.0156988 ;  
//     startValDeltaT[11] =      0.118105;      startValR[11] =     -0.0337033 ;      startValPhi[11] =   -0.00324182 ;
//     startValDeltaT[12] =      0.321805;      startValR[12] =     0.0134362  ;      startValPhi[12] =   -0.00190277 ;
//     startValDeltaT[13] =      0.0197693;     startValR[13] =     -0.000656063;      startValPhi[13] =   -0.0162318  ;
//     startValDeltaT[14] =      -0.115263;     startValR[14] =     0.0495637   ;      startValPhi[14] =   -0.0198119 ; 
//     startValDeltaT[15] =      -0.255707;   startValR[15] =     0.00189892  ;     startValPhi[15] =     0.0383932  ;
    


 for(int y = 0; y <16; y++){

   ofstream newfile("newSimonNumbers.txt");

   char name[30];
   sprintf(name,"r%d",y);
	myMin->DefineParameter(y, name, startValR[y], stepSize, minVal, maxVal);
   sprintf(name,"z%d",y);
	myMin->DefineParameter(y+16, name, startValDeltaT[y], stepSize, minVal, maxVal);
	   sprintf(name,"phi%d",y);
	myMin->DefineParameter(y+32, name, startValPhi[y], stepSize, minVal, maxVal);
 }


  
	Double_t deltaR[32],deltaRErr[32];
	Double_t deltaZ[32],deltaZErr[32];
	Double_t deltaPhi[32],deltaPhiErr[32];
  
	//*********MINUIT METHOD*******************
	myMin->SetPrintLevel(-1);
	myMin->Migrad();   

	for(int u = 0; u <16; u++){
	  myMin->GetParameter(u,deltaR[u],deltaRErr[u]);
	  //cout << "deltaR[" << u << "] = " << deltaR[u] ;
	
	
	  myMin->GetParameter(u+16,deltaZ[u],deltaZErr[u]);
	  //cout << " deltaZ[" << u << "] = " << deltaZ[u] ;
	
	  myMin->GetParameter(u+32,deltaPhi[u],deltaPhiErr[u]);
	  //cout << " deltaPhi[" << u << "] = " << deltaPhi[u] << ";" << endl;

	  newfile << u << "  " << deltaZ[u]<< "  " << deltaR[u]<< "  " << deltaPhi[u]<< "  " << 0 << endl;


	}


  
}
Ejemplo n.º 16
0
void AverageMW()
{
   // include NuTeV?
   if( inclNuTeV ) nVals = 5;
   else            nVals = 4;

   // number of parameters
   const int npar = 1;
   
   // create minuit pointer
   TMinuit *minuit = new TMinuit( npar );
   
   // set FCN function
   minuit->SetFCN( &fcn );
 
   // -1=quiet, 0=normal, 1=verbose
   minuit->SetPrintLevel( 0 );

   // start values
   Double_t startVal = 80;
   Double_t fitStep  = 0.1;
   Double_t limitMin = 70;
   Double_t limitMax = 90;
   minuit->DefineParameter( 0, "MW", startVal, fitStep, limitMin, limitMax);

   // minimize with MIGRAD
   Int_t ierr = 0;
   Double_t args[2];
   args[0] = 0; // maximum function calls (0=default)
   args[1] = 0; // tolerance at minimum (0=default)
   minuit->mnexcm( "MIGrad", args, 2, ierr );
   if ( ierr != 0 )
      cout << "Warning: Maybe fit didn't converge!" << endl;

   // fit results
   Double_t fitval_MW[1], fiterr_MW[1]; 
   minuit->GetParameter( 0, fitval_MW[0], fiterr_MW[0] );

   cout << "\n\n*************************************************" << endl;
   cout << "          chi2Min = " << chi2Min  << endl;
   cout << "          n_dof   = " << nVals-1  << endl;
   cout << "          p-value = " << TMath::Prob(chi2Min, nVals-1)  << endl;
   cout << "          MW      = " << fitval_MW[0] << " +- " << fiterr_MW[0] << endl;
   cout << "*************************************************" << endl;

   // make plot
   gStyle->SetOptTitle(0);
   gStyle->SetOptStat(0);
   gStyle->SetOptFit(0);
   TCanvas* c = new TCanvas( "c", "Mean of W boson mass", 0, 0, 850, 500 );
   c->SetGridy();
   TH2F *frame = new TH2F("frame", "Mean of W boson mass", 1, 80, 80.6, 5, 0, 5. );
   frame->SetLineColor(0);
   frame->SetTickLength(0,"Y");
   frame->SetXTitle("M_{W} [GeV]");  
   frame->GetYaxis()->CenterLabels( 1 );
   frame->GetYaxis()->SetNdivisions( frame->GetNbinsY()+10, 1 );
   frame->GetYaxis()->SetBinLabel( 1, "" ); // no labels
   frame->Draw();
   
   // make labels
   MakeLabels(frame);
   
   // draw fit value
   DrawFitValue( frame, fitval_MW[0], fiterr_MW[0] );
      
   // draw measurements
   for( Int_t i=0; i<5; i++ ){
      DrawMeasurement( frame, 4-i, val_MW[i], err_MW[i] ); 
   }

   // Redraw axis
   frame->Draw("sameaxis");
   
}
Ejemplo n.º 17
0
int main(int argc, char *argv[])
{
  setenv("TZ","UTC",1);
  tzset();
  gROOT->SetStyle("Plain");

  static struct RecEvent RecEvent30;
  static struct RecEvent RecEvent17;
  static struct channel_profiles channel_profiles30;
  static struct channel_profiles channel_profiles17;
  static struct h3 h330;
  static struct h3 h317;

  //get pointer to data
  TChain *TRecEvent30 = new TChain ("TRecEvent");
  CreateTRecEventChain30(TRecEvent30);
  cout << "TRecEvent entries = " << TRecEvent30->GetEntries() << endl;
  CreateTRecEvent(TRecEvent30, &RecEvent30);
  CreateTGrande(TRecEvent30, &h330, false);
  
  TChain *TRecEvent17 = new TChain ("TRecEvent");
  CreateTRecEventChain17(TRecEvent17);
  cout << "TRecEvent entries = " << TRecEvent17->GetEntries() << endl;
  CreateTRecEvent(TRecEvent17, &RecEvent17);
  CreateTGrande(TRecEvent17, &h317, false);

  char cut[2048];
  sprintf(cut, "Eg>0");
  sprintf(cut, "Eg>8.5 && abs(Zenith1Third)+2*Zenith1Third_err>Zeg && abs(Zenith1Third)-2*Zenith1Third_err<Zeg && LDFSlope<0");
//  sprintf(cut, "Eg>6 && abs(Zenith1Third)+2*Zenith1Third_err>Zeg && abs(Zenith1Third)-2*Zenith1Third_err<Zeg && event_id!=2768428"); //slope!!
  cout << "cut = " << cut << endl;
  
  
  TRecEvent30->Draw(">>ListRecEvent30",cut);
  TEventList *EventList30 = (TEventList*) gDirectory->Get("ListRecEvent30");
  if(EventList30==NULL) cerr << "error - EventList30 has null entries" << endl;
  TRecEvent30->SetEventList(EventList30);
  cout << "30: events to analyse = " <<  EventList30->GetN() << endl;
  
  TRecEvent17->Draw(">>ListRecEvent17",cut);
  TEventList *EventList17 = (TEventList*) gDirectory->Get("ListRecEvent17");
  if(EventList17==NULL) cerr << "error - EventList17 has null entries" << endl;
  TRecEvent17->SetEventList(EventList17);
  cout << "17: events to analyse = " <<  EventList17->GetN() << endl;
  
  TChain *Tchannel_profile30 = new TChain("Tchannel_profile");
  int NoChannels30;
  Tchannel_profile30->AddFile("~/analysis/AnaFlag/AF_D30_run21-49_v28.root");
  CreateTchannel_profiles(Tchannel_profile30, &channel_profiles30);
  NoChannels30 = Tchannel_profile30->GetEntries();
  cout << "Tchannel_profile30 entries = " << NoChannels30 << endl;

  TChain *Tchannel_profile17 = new TChain("Tchannel_profile");
  int NoChannels17;
  Tchannel_profile17->AddFile("~/analysis/AnaFlag/AF_D17_run12-60_v28.root");
  CreateTchannel_profiles(Tchannel_profile17, &channel_profiles17);
  NoChannels17 = Tchannel_profile17->GetEntries();
  cout << "Tchannel_profile17 entries = " << NoChannels17 << endl;
  
  
  gEntries = 0;
  float errScale = 1;
  float errScale2 = 0.14; //0.0737; //0.048*1;
  
  bool bNS = false, bEW = false;
  //fill data pointers
  for(int i=0; i<EventList30->GetN(); i++){
    TRecEvent30->GetEntry(EventList30->GetEntry(i));
    bNS = false;
    bEW = false;
    for(int k=0; k<RecEvent30.DetCh; k++){
      for(int j=0; j<NoChannels30; j++){
        Tchannel_profile30->GetEntry(j);
	if((int)channel_profiles30.ch_id == RecEvent30.channel_id[k]){
	  if( strncmp(channel_profiles30.polarisation,"East",4) == 0 ){
	    bEW = true;
	    gFieldStrengthEW[gEntries]    = RecEvent30.FieldStrengthChannel[k];
	    gFieldStrengthEWErr[gEntries] = RecEvent30.ChannelErrBackground[k]*errScale + RecEvent30.FieldStrengthChannel[k]*errScale2;
	    gFieldStrengthAnt[gEntries]   = RecEvent30.FieldStrengthAntenna[k];
	    gDistanceShowerAxis[gEntries] = RecEvent30.DistanceShowerAxis[k];
	  }
	  else{
	    bNS = true;
	    gFieldStrengthNS[gEntries]    = RecEvent30.FieldStrengthChannel[k];
	    gFieldStrengthNSErr[gEntries] = RecEvent30.ChannelErrBackground[k]*errScale + RecEvent30.FieldStrengthChannel[k]*errScale2;
	    gFieldStrengthAnt[gEntries]   = RecEvent30.FieldStrengthAntenna[k];
	    gDistanceShowerAxis[gEntries] = RecEvent30.DistanceShowerAxis[k];
	  }
	  if(bNS && bEW){
	    gAzimuth[gEntries] = h330.Azg;
            while(gAzimuth[gEntries]>360) gAzimuth[gEntries] -= 360;
	    gBAngle[gEntries] = RecEvent30.BAngle;
            while(gBAngle[gEntries]>360) gBAngle[gEntries] -= 360;
	    gZenith[gEntries] = h330.Zeg;	    
	    gEg[gEntries] = h330.Eg;
	    
	   if(0){
              cout << gAzimuth[gEntries] << " -- " << gBAngle[gEntries] << endl;
              cout << channel_profiles30.polarisation << endl;
              cout << gFieldStrengthNS[gEntries] << " -- " << gFieldStrengthEW[gEntries] <<  " ----- " << gFieldStrengthNS[gEntries]/gFieldStrengthEW[gEntries] << endl;
	      cout << gFieldStrengthAnt[gEntries] << endl;
              cout << h330.Zeg << " -- " << RecEvent30.Zenith1Third << " -- " << RecEvent30.Zenith1Third_err << endl;
	      cout << RecEvent30.event_id << endl;
              cout << endl;
            }

	    gEntries++;
	    bNS = false;
	    bEW = false;
	  }
	  break;
	}
      }
    }
   }

  if(true)
  for(int i=0; i<EventList17->GetN(); i++){
    TRecEvent17->GetEntry(EventList17->GetEntry(i));
    bNS = false;
    bEW = false;
    for(int k=0; k<RecEvent17.DetCh; k++){
      for(int j=0; j<NoChannels17; j++){
        Tchannel_profile17->GetEntry(j);
	if((int)channel_profiles17.ch_id == RecEvent17.channel_id[k]){
	  if( strncmp(channel_profiles17.polarisation,"East",4) == 0 ){
	    bEW = true;
	    gFieldStrengthEW[gEntries]    = RecEvent17.FieldStrengthChannel[k];
	    gFieldStrengthEWErr[gEntries] = RecEvent17.ChannelErrBackground[k]*errScale + RecEvent17.FieldStrengthChannel[k]*errScale2;
	    gFieldStrengthAnt[gEntries]   = RecEvent17.FieldStrengthAntenna[k];
	    gDistanceShowerAxis[gEntries] = RecEvent17.DistanceShowerAxis[k];
	  }
	  else{
	    bNS = true;
	    gFieldStrengthNS[gEntries]    = RecEvent17.FieldStrengthChannel[k];
	    gFieldStrengthNSErr[gEntries] = RecEvent17.ChannelErrBackground[k]*errScale + RecEvent17.FieldStrengthChannel[k]*errScale2;
	    gFieldStrengthAnt[gEntries]   = RecEvent17.FieldStrengthAntenna[k];
	    gDistanceShowerAxis[gEntries] = RecEvent17.DistanceShowerAxis[k];
	  }
	  if(bNS && bEW){
	    gAzimuth[gEntries] = h317.Azg;
            while(gAzimuth[gEntries]>360) gAzimuth[gEntries] -= 360;
	    gBAngle[gEntries] = RecEvent17.BAngle;
            while(gBAngle[gEntries]>360) gBAngle[gEntries] -= 360;
    	    gZenith[gEntries] = h317.Zeg;
	    gEg[gEntries] = h317.Eg;

	    
	    
	   if(0){
	      cout << "index = " << i << endl;
              cout << gAzimuth[gEntries] << " -- " << gBAngle[gEntries] << endl;
              cout << channel_profiles17.polarisation << endl;
              cout << gFieldStrengthNS[gEntries] << " -- " << gFieldStrengthEW[gEntries] <<  " ----- " << gFieldStrengthNS[gEntries]/gFieldStrengthEW[gEntries] << endl;
	      cout << gFieldStrengthAnt[gEntries] << endl;
              cout << h317.Zeg << " -- " << RecEvent17.Zenith1Third << " -- " << RecEvent17.Zenith1Third_err << endl;
              cout << endl;
            }

	    gEntries++;
	    bNS = false;
	    bEW = false;
	  }
	  break;
	}
      }
    }
   }

   cout << gEntries << endl;
   if(NoChannels30+NoChannels17 > gMaxCh || gEntries > gMaxEvents) {
     cout << "constants limit reached" << endl;
     exit(1);
   }
 
   TMinuit *gMinuit = new TMinuit(10);
   gMinuit->SetPrintLevel(-1);
   Double_t arglist[10];
   Int_t ierflg = 0;
   int NoPar = 6;
   
   bool AntFit = false;
   
   if(AntFit){
   // Antenna Fit Settings
   //++++++++++++++++++++++
   cout << "Antenna Fit" << endl;
   cout << "+++++++++++" << endl;
   
   gMinuit->SetFCN(FcnParFS);
   
// no effect
  arglist[0] = 1;
  gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);

  arglist[0] = 1;
  gMinuit->mnexcm("SET STRATEGY", arglist, 1, ierflg);
  

   gMinuit->mnparm(0, "scale",  1., 0.01, 0, 0, ierflg);
   gMinuit->mnparm(1, "r0",    400., 1, 0, 0, ierflg);
   gMinuit->mnparm(2, "Epower",  1., 0.01, 0.8, 1.2, ierflg);
//   gMinuit->mnparm(2, "Epower",  1., 0.1, 0, 0, ierflg);
   gMinuit->mnparm(3, "Zphase",  0., 0.1, -TMath::Pi()*2, TMath::Pi()*2, ierflg);
   gMinuit->mnparm(4, "Bphase",  0., 0.1, -TMath::Pi()*2, TMath::Pi()*2, ierflg);
   gMinuit->mnparm(5, "offset",  2., 0.1, 0, 0, ierflg);
//   gMinuit->FixParameter(0);
//   gMinuit->FixParameter(2);

   gMinuit->FixParameter(3);
   gMinuit->FixParameter(4);
   gMinuit->FixParameter(5);
   }
   else{
   // Channel Fit Settings
   //+++++++++++++++++++++
   cout << "Channel Fit" << endl;
   cout << "+++++++++++" << endl;

   gMinuit->SetFCN(FcnParFSChannel);
   
// no effect
  arglist[0] = 1;
  gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);

  arglist[0] = 1;
  gMinuit->mnexcm("SET STRATEGY", arglist, 1, ierflg);
  
   gMinuit->mnparm(0, "scale",  1., 0.01, 0.1, 100, ierflg);
   gMinuit->mnparm(1, "r0",    400., 1, 100, 1000, ierflg);
   gMinuit->mnparm(2, "Epower",  1., 0.01, 0.8, 1.2, ierflg);
//   gMinuit->mnparm(2, "Epower",  1., 0.01, 0, 0, ierflg);
   gMinuit->mnparm(3, "Zphase",  0., 0.1, -TMath::Pi()*2, TMath::Pi()*2, ierflg);
   gMinuit->mnparm(4, "Bphase",  0., 0.1, -TMath::Pi()*2, TMath::Pi()*2, ierflg);
   gMinuit->mnparm(5, "offset",  2., 0.1, 0, 0, ierflg);
//   gMinuit->FixParameter(0);
//   gMinuit->FixParameter(2);

   gMinuit->FixParameter(3);
   gMinuit->FixParameter(4);
   gMinuit->FixParameter(5);
   }

   
   //scan par space
   for(int i=0; i<1; i++){
     gMinuit->mnexcm("SCA", arglist, 0, ierflg);
   }
   
// Now ready for minimization step
   arglist[0] = 50000; // steps of iteration
   arglist[1] = 1.; // tolerance
   gMinuit->mnexcm("MIGRAD", arglist ,2,ierflg); //MIGRAD
   cout << " MINIMIZE flag is " << ierflg << endl;
   if(ierflg!=0){
     cout << "+++++++++++++++++++++" << endl;
     cout << "+ ups.. check again +" << endl;
     cout << "+++++++++++++++++++++" << endl;
   }

   // MIGRAD: error optimiser
   if(ierflg==0 && 0){
     arglist[0] = 500000;
     gMinuit->mnexcm("MIGRAD", arglist ,1,ierflg);
     cout << " MIGRAD flag is " << ierflg << endl;
     if(ierflg!=0){
       cout << "+++++++++++++++++++++" << endl;
       cout << "+ ups.. check again +" << endl;
       cout << "+++++++++++++++++++++" << endl;
     }
   }

   // Minos: error optimiser
   if(ierflg==0 && 0){
     arglist[0] = 500000;
     gMinuit->mnexcm("MINOS", arglist ,1,ierflg);
     cout << " MINOS flag is " << ierflg << endl;
     if(ierflg!=0){
       cout << "+++++++++++++++++++++" << endl;
       cout << "+ ups.. check again +" << endl;
       cout << "+++++++++++++++++++++" << endl;
     }
   }

// Print results
   Double_t amin,edm,errdef;
   Int_t nvpar,nparx,icstat;
   gMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
   gMinuit->mnprin(3,amin);
 
   cout << "prob = " << TMath::Prob(amin,gEntriesUsed-gMinuit->GetNumFreePars())*100 << " %" << endl;
   cout << "ndf = " << gEntriesUsed-gMinuit->GetNumFreePars() << endl;

   
   cout << "output" << endl;
//   gMinuit->mnexcm("SHO COV", arglist ,0,ierflg);
//   gMinuit->mnexcm("SHO COR", arglist ,0,ierflg);
//   gMinuit->mnexcm("SHO EIG", arglist ,0,ierflg);
   
   //get fit parameters
   double par[15], epar;
   for(int i=0; i<NoPar; i++){
     gMinuit->GetParameter(i,par[i],epar);
   }

   
   TFile *output = new TFile("FitParFieldStrength_out.root","RECREATE");

   int tcount = 0;
   float tmpBAngle, tmpZenith;
   float r0x[gMaxEvents], r0y[gMaxEvents];
   float bx[gMaxEvents], by[gMaxEvents];
   
   for(int i=0; i<gEntries; i++){
     if(gFieldStrengthAnt[i]>0 && gFieldStrengthNS[i]>0 && gFieldStrengthEW[i]>0){
       tmpBAngle = gBAngle[i] * TMath::Pi() / 180.;
       tmpZenith = gZenith[i] * TMath::Pi() / 180.;
       
       r0x[tcount] = -gDistanceShowerAxis[i];
       r0y[tcount] = (log( (gFieldStrengthAnt[i]/gEffBand) / ( par[0]*cos(tmpZenith+par[3])*(par[5]+sin(tmpBAngle+par[4]))*powf(10,par[2]*(gEg[i]-8))))  );
       //if(r0y[tcount] < -4 && r0x[tcount] > 50) cout << "E = " << gEg[i] << " --  i = " << i << endl;
       
       bx[tcount] = tmpBAngle;
       by[tcount] = gFieldStrengthAnt[i]/gEffBand / (par[0]*cos(tmpZenith+par[3])*exp(-gDistanceShowerAxis[i]/par[1])*powf(10,par[2]*(gEg[i]-8))) - par[5];
//       if(by[tcount]>1.5) cout << " E = " << gEg[i] << " -- i = " << i << endl;

       tcount++;
     }
   }
   TCanvas *can1 = new TCanvas("can1");
   can1->Divide(2,2);

   TGraph *gr0 = new TGraph(tcount,r0x, r0y);
   gr0->SetName("gr0");
   gr0->SetMarkerStyle(20);
   gr0->SetTitle("lateral distribution");

   TGraph *gb = new TGraph(tcount,bx, by);
   gb->SetName("gb");
   gb->SetMarkerStyle(20);
   gb->SetTitle("geomagnetic angle");
 
   can1->cd(1);
   gr0->Draw("ap");
   
   can1->cd(2);
   gb->Draw("ap");
 
 
   gr0->Write();
   gb->Write();
   can1->Write();
   output->Close();
   
   
   

}
Ejemplo n.º 18
0
void hrstrans3(){

//    LeRose SNAKE scaled by 1.4
    THRSTrans *trans = new THRSTrans( 0.1746, -0.1385, -0.1281, 0.050178, 0.037056, THRSTrans::kStd);
//
//
//    // Fit to data optics
//    THRSTrans *trans = new THRSTrans(  0.178259, -0.137781, -0.128674, 0.050178, 0.037056, THRSTrans::kStd);

    /*

//    trans->GetElement(5)->Print();
   trans->ShowOutput();
   trans->ShowAcc();
   trans->ShowFocalLengths();
   return;

   */

    // LeRose Translated Numbers
    //THRSTrans *trans = new THRSTrans( 0.1861, -0.1415, -0.1375, 0.5, 0.5, THRSTrans::kStd);
//   trans->ShowOutput();
  // return;
    // LeRose Numbers Fit to Transport matrix elements, PREX
//    THRSTrans *trans = new THRSTrans( 1.34761e-01, -1.38523e-01, -2.13742e-01, 0.02075 };
//
//

//     THRSTrans *trans = new THRSTrans(  1.344e-01, -1.431e-01, -1.855e-01, 0.005763, 0.000014, THRSTrans::kPREX);
//     trans->SetSeptumPsi(  1.22603, 0.929424);


    // HRS Database fit forcing 
//    THRSTrans *trans = new THRSTrans(     1.38796e-01, -1.39940e-01, -1.73034e-01, 0.02075, THRSTrans::kPREX);

//     trans->ShowOutput(4);

//     trans->ShowOutput();
//     trans->ShowFocalLengths();
//     trans->ShowAcc();
//   return;


    TMinuit *gMinuit = new TMinuit(5);
    gMinuit->SetFCN(fcn);
    Double_t arglist[10];
    Int_t ierflg = 0;

    arglist[0] = 1;
    gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);
    Double_t vstart[5] = {
    // Standard tune from data
    0.178615, -0.137474, -0.128384, 0.043667, 0.036814};

    //PREX Tune
       

    Double_t step[5] = {0.001 , 0.001 , 0.001, 0.001, 0.001};

    gMinuit->mnparm(0, "q1", vstart[0], step[0], 0,0,ierflg);
    gMinuit->mnparm(1, "q2", vstart[1], step[1], 0,0,ierflg);
    gMinuit->mnparm(2, "q3", vstart[2], step[2], 0, 0,ierflg);
    gMinuit->mnparm(3, "K1", vstart[3], step[3], 0.0,1.5,ierflg);
    gMinuit->mnparm(4, "K2", vstart[4], step[4], 0.0,1.5,ierflg);


    arglist[0] = 5000;
    arglist[1] = 1.;
    gMinuit->mnexcm("SIMPLEX", arglist ,2,ierflg);
    Double_t amin,edm,errdef;
    Int_t nvpar,nparx,icstat;
    gMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
    gMinuit->mnimpr();
    gMinuit->mnimpr();
    double q1, q2, q3, psi1, psi2, e1;

    gMinuit->GetParameter(0, q1, e1);
    gMinuit->GetParameter(1, q2, e1);
    gMinuit->GetParameter(2, q3, e1);
    gMinuit->GetParameter(3, psi1, e1);
    gMinuit->GetParameter(4, psi2, e1);


    THRSTrans *result = new THRSTrans( q1, q2, q3, psi1, psi2);

    result->ShowOutput();
    result->GetOptics()->Print();
    result->ShowAcc();
    result->ShowFocalLengths();

    return;
}
Ejemplo n.º 19
0
void minuitFit()
{

  TH1F::SetDefaultSumw2(); 
  TH1D::SetDefaultSumw2(); 

  cout << "Must Use Same Binning as previous Analysis!" << endl;

  gStyle->SetOptFit(1111);
  gStyle->SetOptStat(0);
  haveName = kFALSE;
  char fname[100];
  TFile* file;
  Bool_t makePDF = checkMakePDF();
  Bool_t makeROOT = checkMakeRoot();
  if(makeROOT){
    sprintf(fname,"/Users/zach/Research/pythia/200GeVTemplate/FFOutput/%s_FIT.root",FileNameR);
    file = new TFile(fname,"RECREATE");
    if (file->IsOpen()==kFALSE)
    {
      std::cout << "!!! Outfile Not Opened !!!" << std::endl;
      makeROOT = kFALSE;
    }
  }


  char name[1000];
  sprintf(name,"/Users/zach/Research/pythia/200GeVTemplate/currentTemplate.root");
  TFile *fT = new TFile(name,"READ");
  sprintf(name,"/Users/zach/Research/rootFiles/run12NPEhPhi/currentData.root");
  TFile *fD = new TFile(name,"READ");
  if (fT->IsOpen()==kFALSE || fD->IsOpen()==kFALSE)
  { std::cout << "!!!!!! Either B,C, or Data File not found !!!!!!" << std::endl
    << "Looking for currentB.root, currentC.root, and currentData.root" << std::endl;
    exit(1); }

  // Set constants and projection bins (from header file anaConst, analysis constants)

  Float_t lowpt[numPtBins],highpt[numPtBins];
  for(Int_t c=0; c< numPtBins; c++){
    lowpt[c] = anaConst::lpt[c];
    highpt[c] = anaConst::hpt[c];
  }
  Float_t hptCut=anaConst::hptCut;

  // Make Canvases
  TCanvas* deltaPhi  = new TCanvas("deltaPhi","Pythia Delta Phi",150,0,1150,1000);
  TCanvas* deltaPhi2  = new TCanvas("deltaPhi2","Pythia Delta Phi",150,0,1150,1000);
  TCanvas* fitResult0 = new TCanvas("fitResult0","RB Extraction HT0",150,0,1150,1000);
  TCanvas* fitResult2 = new TCanvas("fitResult2","RB Extraction HT2",150,0,1150,1000);
  TCanvas* fitResultC = new TCanvas("fitResultC","RB Extraction Combined Trigs",150,0,1150,1000);
  TCanvas* fitResultP = new TCanvas("fitResultP","RB Previous Analysis",150,0,1150,1000);
  TCanvas* scaleCheck = new TCanvas("scaleCheck","Check scale diff",150,0,1150,1000);
  TCanvas* prettyPlot = new TCanvas("prettyPlot","PrettyPlot",150,0,1150,1000);
  deltaPhi  ->Divide(3,3);
  deltaPhi2 ->Divide(3,3);
  fitResult0->Divide(3,4);
  fitResult2->Divide(3,4);
  fitResultC->Divide(3,4);
  fitResultP->Divide(2,2);
  scaleCheck->Divide(1,2);

  // Get and Draw histos
  TPaveText* lbl[numPtBins];
  TPaveText* stat[4][numPtBins];
  char statLabel[100];
  char textLabel[100];
  Int_t plotbin;
  Double_t norm0,norm2,normB,normC;

  // Get ptbin independent hists
  histoNorms = (TH2F*)fD->Get("histoNorms");
   // Get Previous Analysis
  TFile *file3 = new TFile("/Users/zach/Research/previousNPEhFigures/Chi2_25_35.root");
  Hdphi[0]  = (TH1D*)file3->Get("fit_25_35");
  HpphiD[0] = (TH1D*)file3->Get("De_25_35");
  HpphiB[0] = (TH1D*)file3->Get("Be_25_35");
  TFile *file4 = new TFile("/Users/zach/Research/previousNPEhFigures/Chi2_55_65.root");
  Hdphi[1]  = (TH1D*)file4->Get("fit_55_65");
  HpphiD[1] = (TH1D*)file4->Get("De_55_65");
  HpphiB[1] = (TH1D*)file4->Get("Be_55_65");

  for(Int_t ptbin=0; ptbin<numPtBins; ptbin++)
  {
    bPtNorms[ptbin]   = (TH1F*)fT->Get(Form("beEventTally_%i",ptbin));
    cPtNorms[ptbin]   = (TH1F*)fT->Get(Form("ceEventTally_%i",ptbin));

    norm0 = histoNorms->GetBinContent(histoNorms->GetBin(1,ptbin+1));
    norm2 = histoNorms->GetBinContent(histoNorms->GetBin(3,ptbin+1));
    normB = bPtNorms[ptbin]->GetBinContent(1);
    normC = cPtNorms[ptbin]->GetBinContent(1);

    cout << ptbin << "; 0: " << norm0 << " 2: " << norm2 << endl;

    if( norm0 == 0)
    {
      cout << ptbin << " For this bin, some norm0 = 0" << endl;
      continue;
    }
    if( norm2 == 0 )
    {
      cout << ptbin << " For this bin, some norm2 = 0" << endl;
      continue;
    }
    if( normB == 0 )
    {
      cout << ptbin << " For this bin, some normB = 0" << endl;
      continue;
    }
    if( normC == 0)
    {
      cout << ptbin << " For this bin, some normC = 0" << endl;
      continue;
    }
    plotbin = ptbin;
    // Init necessary plotting tools
    lbl[ptbin] = new TPaveText(.15,.15,.35,.23,Form("NB NDC%i",ptbin));
    sprintf(textLabel,"%.1f < P_{T,e} < %.1f",lowpt[ptbin],highpt[ptbin]);
    lbl[ptbin]->AddText(textLabel);
    lbl[ptbin]->SetFillColor(kWhite);

    projB[ptbin] = (TH1D*)fT->Get(Form("hdPhiRawbe_%i",ptbin));
    projC[ptbin] = (TH1D*)fT->Get(Form("hdPhiRawce_%i",ptbin));
    projData0[ptbin]= (TH1D*)fD->Get(Form("NPEhDelPhi_0_%i",ptbin));
    projData2[ptbin]= (TH1D*)fD->Get(Form("NPEhDelPhi_2_%i",ptbin));
 
    pileupCorrect[ptbin][0] = (TH1D*)fD->Get(Form("pileupCorrection_%i_0",ptbin));
    pileupCorrect[ptbin][1] = (TH1D*)fD->Get(Form("pileupCorrection_%i_2",ptbin));
    pileupCorrect[ptbin][0]->Sumw2();
    pileupCorrect[ptbin][1]->Sumw2();

    // Do any rebinning
    Int_t RB = 1;
    projB[ptbin]->Rebin(RB);
    projC[ptbin]->Rebin(RB);
    projData0[ptbin]->Rebin(RB);
    projData2[ptbin]->Rebin(RB);

    // Clone to make plots without effecting fits
    plotD0[ptbin] = (TH1D*) projData0[ptbin]->Clone();
    plotD2[ptbin] = (TH1D*) projData2[ptbin]->Clone();
    plotB[ptbin]  = (TH1D*) projB[ptbin]->Clone();
    plotC[ptbin]  = (TH1D*) projC[ptbin]->Clone();

    // Set features that are the same in plots
    projData0[ptbin]->SetLineColor(kBlue);
    projData2[ptbin]->SetLineColor(kGreen+3);
    projB[ptbin]->SetLineColor(kRed);
    projC[ptbin]->SetLineColor(kBlack);
    projC[ptbin]->GetXaxis()->SetRangeUser(-3.5,3.5);
    plotD0[ptbin]->SetLineColor(kBlue);
    plotD2[ptbin]->SetLineColor(kGreen+3);
    plotD0[ptbin]->SetMarkerStyle(20);
    plotD0[ptbin]->SetMarkerColor(kBlue);
    plotD0[ptbin]->SetMarkerSize(0.4);
    plotB[ptbin]->SetLineColor(kRed);
    plotC[ptbin]->SetLineColor(kBlack);
    plotC[ptbin]->GetXaxis()->SetRangeUser(-3.5,3.5);

    combData[ptbin] = (TH1D*) projData0[ptbin]->Clone();
    combData[ptbin] -> Add(projData2[ptbin]);
    combData[ptbin]->SetLineColor(kBlue);
    combData[ptbin]->SetMarkerStyle(20);
    combData[ptbin]->SetMarkerColor(kBlue);
    combData[ptbin]->SetMarkerSize(0.4);
    combData[ptbin]->SetTitle("");

    // Normalize
    projB[ptbin]     -> Scale(1./normB);
    projC[ptbin]     -> Scale(1./normC);
    projData0[ptbin] -> Scale(1./norm0);
    projData2[ptbin] -> Scale(1./norm2);
    plotD0[ptbin]    -> Scale(1./norm0);
    plotD2[ptbin]    -> Scale(1./norm2);
    plotB[ptbin]     -> Scale(1./normB);
    plotC[ptbin]     -> Scale(1./normC);
    combData[ptbin]  -> Scale(1./(norm0+norm2));

    // Subtract Pileup correction (data only)
    projData0[ptbin]->Sumw2();projData2[ptbin]->Sumw2();
    //projData0[ptbin]->Add(pileupCorrect[ptbin][0],-1);
    //projData2[ptbin]->Add(pileupCorrect[ptbin][1],-1);

    // Draw Templates on own plots
    if(ptbin+1 <= 9) deltaPhi->cd(plotbin+1);
    if(ptbin+1 > 9) deltaPhi2->cd(ptbin-8);
    plotC[ptbin]->GetYaxis()->SetRangeUser(-.1,0.8);
    plotC[ptbin]  -> Draw("hist");
    plotB[ptbin]  -> Draw("same hist");
    plotD0[ptbin] -> Draw("same");
    plotD2[ptbin] -> Draw("same");
    lbl[ptbin]    -> Draw("same");

    TLegend* leg = new TLegend(0.65,0.6,0.85,0.85);
    leg->AddEntry(projB[ptbin],"b#bar{b}->NPE","lpe");
    leg->AddEntry(projC[ptbin],"c#bar{c}->NPE","lpe");
    leg->AddEntry(projData0[ptbin],"HT0","lpe");
    leg->AddEntry(projData2[ptbin],"HT2","lpe");
    leg->Draw();

    deltaPhi->cd(1);
    Hdphi[0]->Draw("same");
    deltaPhi->cd(4);
    Hdphi[1]->Draw("same");

      if(ptbin == 1)
      {
        prettyPlot->cd();
        plotC[ptbin]->GetYaxis()->SetRangeUser(0,0.35);
        plotC[ptbin]->SetMarkerStyle(20);
        plotC[ptbin]->SetMarkerSize(0.6);
        plotB[ptbin]->SetMarkerStyle(21);
        plotB[ptbin]->SetMarkerSize(0.6);
        plotB[ptbin]->SetMarkerColor(kRed);
        plotD0[ptbin]->SetMarkerStyle(22);
        plotD0[ptbin]->SetMarkerSize(0.9);
        plotC[ptbin]->GetXaxis()->SetTitle("#Delta#phi_{NPE-h} (rad)");
        plotC[ptbin]->GetYaxis()->SetTitle("#frac{1}{N_{NPE}} #frac{dN}{d(#Delta#phi)}");
        plotC[ptbin]->DrawClone("P");
        plotB[ptbin]->DrawClone("same P");
        plotD0[ptbin]->DrawClone("same P");
        TLegend* legPret = new TLegend(0.65,0.6,0.85,0.85);
        legPret->AddEntry(plotB[ptbin],"B #rightarrow NPE-h, Monte Carlo","LPE");
        legPret->AddEntry(plotC[ptbin],"D #rightarrow NPE-h, Monte Carlo","LPE");
        legPret->AddEntry(plotD0[ptbin],"NPE-h 2012 STAR Data","LPE");
        lbl[ptbin]->Draw("same");
        legPret->Draw("same");
      }

    /*// Draw Scale Check
      scaleCheck->cd(1);
      TH1F* HT0 = (TH1F*) plotD0[0]->Clone();
      HT0->Divide(HT0,Hdphi[0],1,1);
      HT0->Draw();
      scaleCheck->cd(2);
      TH1F* HT2 = (TH1F*) plotD2[3]->Clone();
      HT2->Divide(HT2,Hdphi[1],1,1);
      HT0->GetXaxis()->SetRangeUser(-3.5,3.5);
      HT2->GetXaxis()->SetRangeUser(-3.5,3.5);
      HT2->Draw();
      lbl[ptbin]->Draw("same");
      TLegend* legSC = new TLegend(0.65,0.6,0.85,0.85);
      legSC->AddEntry(HT0,"HT0/prevdata","lpe");
      legSC->AddEntry(HT2,"HT2/prevdata","lpe");
      legSC->Draw();*/

    /////////////////////
    // Do the actual fits
    /////////////////////

    currentPtBin = ptbin;
    cout << "!!!!!!! HT0 ptbin: " << highpt[ptbin] << "-" << lowpt[ptbin] <<" !!!!!!!"<< endl;
    TMinuit* gMinuit = new TMinuit(1);
    gMinuit->SetFCN(chi2_0);
    currentPtBin = ptbin;
    doFit(gMinuit,p01[ptbin],p00[ptbin],e01[ptbin],e00[ptbin]);

    // assign to plotting variables
    if(highpt[ptbin] < 6)
    {
      pT[ptbin] = (lowpt[ptbin]+highpt[ptbin])/2.;
      dx[plotCount0] = 0.;
      ptOFF1[plotCount0] = pT[ptbin];
      Rb0[plotCount0] = p01[ptbin];///(p01[ptbin]+p00[ptbin]);
      eb0[plotCount0] = e01[ptbin];
      plotCount0++;
    }

    // Plot results
    fitResult0->cd(ptbin+1);
    TH1D* dClone = (TH1D*) projData0[ptbin]->Clone();
    TH1D* cClone = (TH1D*) projC[ptbin]->Clone();
    TH1D* bClone = (TH1D*) projB[ptbin]->Clone();
    stat[0][ptbin] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%i",ptbin));
    sprintf(statLabel,"Chi2/NDF: %.2f/%.0f",curChi2,curNDF);
    stat[0][ptbin]->InsertText(statLabel);
    stat[0][ptbin]->SetFillColor(kWhite);
    cClone->Scale((1.-p01[ptbin])*p00[ptbin]); bClone->Scale(p00[ptbin]*p01[ptbin]); // scale by contribution param
    cClone->Add(bClone);
    //cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
    dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
    dClone->GetYaxis()->SetRangeUser(-0.1,0.6);
    dClone->Draw();
    cClone->Draw("same");
    stat[0][ptbin]->Draw("same");
    lbl[ptbin]->Draw("same");


    cout << "!!!!!!! HT2 ptbin: " <<  highpt[ptbin] << "-" << lowpt[ptbin] <<" !!!!!!!"<< endl;
    gMinuit->SetFCN(chi2_2);
    doFit(gMinuit,p21[ptbin],p20[ptbin],e21[ptbin],e20[ptbin]);

    // assign to plotting variables
    if(highpt[ptbin] > 3.6)
    {
      pT[ptbin] = (lowpt[ptbin]+highpt[ptbin])/2.;
      ptOFF2[plotCount2] = pT[ptbin];
      Rb2[plotCount2] = p21[ptbin];///(p21[ptbin]+p20[ptbin]);
      eb2[plotCount2] = e21[ptbin];
      plotCount2++;
    }

    // Plot results
    fitResult2->cd(ptbin+1);
    dClone = (TH1D*) projData2[ptbin]->Clone();
    cClone = (TH1D*) projC[ptbin]->Clone();
    bClone = (TH1D*) projB[ptbin]->Clone();
    stat[2][ptbin] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%i",ptbin));
    sprintf(statLabel,"Chi2/NDF: %.2f/%.2f",curChi2,curNDF);
    stat[2][ptbin]->InsertText(statLabel);
    stat[2][ptbin]->SetFillColor(kWhite);
    cClone->Scale((1.-p21[ptbin])*p20[ptbin]); bClone->Scale(p20[ptbin]*p21[ptbin]); // scale by contribution param
    cClone->Add(bClone);
    // cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
    dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
    dClone->GetYaxis()->SetRangeUser(-0.1,0.6);
    dClone->Draw();
    cClone->Draw("same");
    stat[2][ptbin]->Draw("same");
    lbl[ptbin]->Draw("same");

    cout << "!!!!!!! HTC ptbin: " <<  highpt[ptbin] << "-" << lowpt[ptbin] <<" !!!!!!!"<< endl;
    gMinuit->SetFCN(chi2_C);
    doFit(gMinuit,pC1[ptbin],pC0[ptbin],eC1[ptbin],eC0[ptbin]);
    // assign to plotting variables
    pT[ptbin] = (lowpt[ptbin]+highpt[ptbin])/2.;
    RbC[plotCount] = pC1[ptbin];///(p21[ptbin]+p20[ptbin]);
    ebC[plotCount] = eC1[ptbin];
    plotCount++;
  }

  cout << "!!!!!!! Previous Data: 0"<<" !!!!!!!"<< endl;

  //////////
  // 2.5-3.5 GeV Bin
  //////////

  gMinuit->SetFCN(chi2_P0);
  doFit(gMinuit,RbP[0],SF[0],EbP[0],eSF[0]);

  // assign plotting variables
  pTP[0] = 3.;

  // Plot results
  fitResultP->cd(1);
  /*TH1D* dClone = (TH1D*) Hdphi[0]->Clone();
    TH1D* cClone = (TH1D*) projC[0]->Clone();
    TH1D* bClone = (TH1D*) projB[0]->Clone();*/
  TH1D* dClone = (TH1D*) projData0[0]->Clone();
  TH1D* cClone = (TH1D*) HpphiD[0]->Clone();
  TH1D* bClone = (TH1D*) HpphiB[0]->Clone();
  stat[3][0] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%iP",0));
  sprintf(statLabel,"Chi2/NDF: %.2f/%.2f",curChi2,curNDF);
  stat[3][0]->InsertText(statLabel);
  stat[3][0]->SetFillColor(kWhite);
  cClone->Scale((1.-RbP[0])*SF[0]); bClone->Scale(RbP[0]*SF[0]); // scale by contribution param
  cClone->Add(bClone);
  // cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
  dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
  dClone->GetYaxis()->SetRangeUser(-0.1,0.6);
  cClone->SetLineColor(kRed);
  dClone->Draw();
  cClone->Draw("same");
  stat[3][0]->Draw("same");

  ////////
  // 5.5-6.5 GeV Bin
  ////////

  gMinuit->SetFCN(chi2_P1);
  doFit(gMinuit,RbP[1],SF[1],EbP[1],eSF[1]);

  // assign plotting variables
  pTP[1] = 6.;

  // Plot results
  fitResultP->cd(2);
  /*dClone = (TH1D*) Hdphi[1]->Clone();
    cClone = (TH1D*) projC[3]->Clone();
    bClone = (TH1D*) projB[3]->Clone();*/
  dClone = (TH1D*) projData2[3]->Clone();
  cClone = (TH1D*) HpphiD[1]->Clone();
  bClone = (TH1D*) HpphiB[1]->Clone();
  stat[3][1] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%iP",0));
  sprintf(statLabel,"Chi2/NDF: %.2f/%.2f",curChi2,curNDF);
  stat[3][1]->InsertText(statLabel);
  stat[3][1]->SetFillColor(kWhite);
  cClone->Scale((1.-RbP[1])*SF[1]); bClone->Scale(RbP[1]*SF[1]); // scale by contribution param
  cClone->Add(bClone);
  // cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
  dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
  dClone->GetYaxis()->SetRangeUser(-0.1,0.6);
  cClone->SetLineColor(kRed);
  dClone->Draw();
  cClone->Draw("same");
  stat[3][1]->Draw("same");

  ////////
  // Old Data, Old Template
  ///////
  gMinuit->SetFCN(chi2_PP);
  doFit(gMinuit,RbPP[0],SFPP[0],EbPP[0],eSFPP[0]);

  // assign plotting variables
  pTPP[0] = 3.;

  // Plot results
  fitResultP->cd(3);
  dClone = (TH1D*) Hdphi[0]->Clone();
  cClone = (TH1D*) HpphiD[0]->Clone();
  bClone = (TH1D*) HpphiB[0]->Clone();
  stat[3][2] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%iP",0));
  sprintf(statLabel,"Chi2/NDF: %.2f/%.2f",curChi2,curNDF);
  stat[3][2]->InsertText(statLabel);
  stat[3][2]->SetFillColor(kWhite);
  cClone->Scale((1.-RbPP[0])*SFPP[0]); bClone->Scale(RbPP[0]*SFPP[0]); // scale by contribution param
  cClone->Add(bClone);
  // cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
  dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
  dClone->GetYaxis()->SetRangeUser(-0.1,0.6);
  cClone->SetLineColor(kRed);
  dClone->Draw();
  cClone->Draw("same");
  stat[3][2]->Draw("same");

  // Bin at 6 GeV
  gMinuit->SetFCN(chi2_PP1);
  doFit(gMinuit,RbPP[1],SFPP[1],EbPP[1],eSFPP[1]);

  // assign plotting variables
  pTPP[1] = 6.;

  // Plot results
  fitResultP->cd(4);
  dClone = (TH1D*) Hdphi[1]->Clone();
  cClone = (TH1D*) HpphiD[1]->Clone();
  bClone = (TH1D*) HpphiB[1]->Clone();
  stat[3][3] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%iP",0));
  sprintf(statLabel,"Chi2/NDF: %.2f/%.2f",curChi2,curNDF);
  stat[3][3]->InsertText(statLabel);
  stat[3][3]->SetFillColor(kWhite);
  cClone->Scale((1.-RbPP[1])*SFPP[1]); bClone->Scale(RbPP[1]*SFPP[1]); // scale by contribution param
  cClone->Add(bClone);
  // cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
  dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
  dClone->GetYaxis()->SetRangeUser(-0.1,0.6);
  cClone->SetLineColor(kRed);
  dClone->Draw();
  cClone->Draw("same");
  stat[3][3]->Draw("same");


  // Get FONLL Calc
  Int_t l=0;
  char line[1000];
  Float_t xF[100],yF[100],minF[100],maxF[100];
  ifstream fp("/Users/zach/Research/pythia/200GeVTemplate/FONLL.txt",ios::in);
  while (!fp.eof()){
    fp.getline(line,1000);
    sscanf(line,"%f %f %f %f",&xF[l],&yF[l],&minF[l],&maxF[l]);
    //  printf("L: %f %f\n",xF[l],yF[l]);
    l++;
  }
  fp.close();

  // Get Previous Analysis 
  Int_t p=0;
  Float_t xP[100],yP[100],dyP[100];
  ifstream fp1("/Users/zach/Research/pythia/200GeVTemplate/run5_6.txt",ios::in);
  while (!fp1.eof()){
    fp1.getline(line,1000);
    sscanf(line,"%f %f %f",&xP[p],&yP[p],&dyP[p]);
    // printf("L: %f %f\n",xF[l],yF[l]);
    p++;
  }
  fp1.close();

  //cout << "at bottom contrib plot" << endl;
  TCanvas* c1 = new TCanvas("c1","Bottom Contribution",150,0,1150,1000);
  TGraphErrors *gr0     = new TGraphErrors(plotCount0-1,ptOFF1,Rb0,dx,eb0);
  TGraphErrors *gr2     = new TGraphErrors(plotCount2-1,ptOFF2,Rb2,dx,eb2);
  TGraphErrors *grC     = new TGraphErrors(plotCount-1,pT,RbC,dx,ebC);
  TGraphErrors *grF     = new TGraphErrors(l-1,xF,yF);
  TGraphErrors *grFmax  = new TGraphErrors(l-1,xF,maxF);
  TGraphErrors *grFmin  = new TGraphErrors(l-1,xF,minF);
  TGraphErrors *grP     = new TGraphErrors(p-1,xP,yP,0,dyP);
  TGraphErrors *grPr    = new TGraphErrors(2,pTP,RbP,0,EbP);
  TGraphErrors *grPPr   = new TGraphErrors(2,pTPP,RbPP,0,EbPP);


  c1->cd(1);

  grP->SetTitle("");
  grP->GetXaxis()->SetTitle("NPE p_{T} (GeV/c)");
  grP->GetYaxis()->SetTitle("r_{B}");
  gr0->SetMarkerStyle(20);
  gr0->SetMarkerSize(1);
  gr0->SetLineColor(kBlue);
  gr0->SetMarkerColor(kBlue);
  gr2->SetMarkerStyle(22);
  gr2->SetMarkerSize(1);
  gr2->SetLineColor(kRed);
  gr2->SetMarkerColor(kRed);
  grC->SetMarkerStyle(21);
  grC->SetMarkerSize(1);
  grC->SetLineColor(kRed);
  grC->SetMarkerColor(kRed);
  grP->GetXaxis()->SetLimits(0,10);
  grP->GetYaxis()->SetRangeUser(0,1);
  grF->SetLineStyle(1);
  grFmax->SetLineStyle(2);
  grFmin->SetLineStyle(2);
  grP->SetMarkerStyle(33);
  grP->SetMarkerColor(kBlack);
  grPr->SetMarkerStyle(29);
  grPr->SetMarkerColor(9);
  grPr->SetLineColor(9);
  grPPr->SetMarkerStyle(29);
  grPPr->SetMarkerColor(49);
  grPPr->SetLineColor(49);


  grP->Draw("AP");
  //grC->Draw("same P");
  gr2->Draw("same P");
  grF->Draw("same");
  grFmax->Draw("same");
  grFmin->Draw("same");
  gr0->Draw("same P");
 // grPr->Draw("same P");
  //grPPr->Draw("same P");

  TLegend* leg2 = new TLegend(0.15,0.68,0.48,0.85);
  leg2->AddEntry(gr0,"STAR Run 12 - Low p_{T} Analysis","pe");
  leg2->AddEntry(gr2,"STAR Run 12 - High p_{T} Analysis","pe");
  //leg2->AddEntry(grC,"Combined Trigs","pe");
  leg2->AddEntry(grP,"STAR Run 6 Analysis (Stat. Uncertainty)","pe");
//  leg2->AddEntry(grPr,"Run 12 Data, Run 5/6 Templates)","pe");
  //leg2->AddEntry(grPPr,"Run 5/6 Refit (prev Template)","pe");
  leg2->AddEntry(grF,"FONLL Calculation","l");
  leg2->Draw("same");

  // Write to Root File if open
  if(makeROOT){
    file3->Close();
    file4->Close();
    file->cd();
    grP->Write("PreviousData");
    //grC->Write("same P");
    gr2->Write("HT2");
    grF->Write("FONLL");
    grFmax->Write("FONLLmax");
    grFmin->Write("FONLLmin");
    gr0->Write("HT0");
    // grPr->Write("PrevTempMyData");
    //grPPr->Write("PrevTempPreData");
  }

  // Make PDF with output canvases
  if(makePDF)
  {
    //Set front page
    TCanvas* fp = new TCanvas("fp","Front Page",100,0,1000,900);
    fp->cd();
    TBox *bLabel = new TBox(0.01, 0.88, 0.99, 0.99);
    bLabel->SetFillColor(38);
    bLabel->Draw();
    TLatex tl;
    tl.SetNDC();
    tl.SetTextColor(kWhite);
    tl.SetTextSize(0.033);
    char tlName[100];
    char tlName2[100];

    TString titlename = FileName;
    int found = titlename.Last('/');
    if(found >= 0){
      titlename.Replace(0, found+1, "");
    } 
    sprintf(tlName, "RUN 12 NPE-h   #Delta#phi Correlations");
    tl.SetTextSize(0.05);
    tl.SetTextColor(kWhite);
    tl.DrawLatex(0.05, 0.92,tlName);

    TBox *bFoot = new TBox(0.01, 0.01, 0.99, 0.12);
    bFoot->SetFillColor(38);
    bFoot->Draw();
    tl.SetTextColor(kWhite);
    tl.SetTextSize(0.05);
    tl.DrawLatex(0.05, 0.05, (new TDatime())->AsString());
    tl.SetTextColor(kBlack);
    tl.SetTextSize(0.03);
    tl.DrawLatex(0.1, 0.14, titlename);
    sprintf(tlName,"TEST");
    tl.DrawLatex(0.1, 0.8,tlName);

    // Place canvases in order
    TCanvas* temp = new TCanvas();
    sprintf(name, "FFOutput/%s.pdf[", FileName);
    temp->Print(name);
    sprintf(name, "FFOutput/%s.pdf", FileName);

    temp = deltaPhi; 
    temp->Print(name);
    temp = fitResult0;
    temp->Print(name);
    temp = fitResult2;
    temp->Print(name);
    // temp = fitResultC;
    // temp->Print(name);
    temp = c1;
    temp->Print(name);

    sprintf(name, "FFOutput/%s.pdf]", FileName);
    temp->Print(name);
  }
  if(makeROOT)
  {
    file->Write();
    file->Close();
  }
}
//_________________________________________________________________________________
void multipleSplinesWithHistogramsVb(int iEventLook = 163, int nEvents = 1000, int nPoints = 9, double seed = 231) 
{
	double lowerBound = 10; //bounds for random vector function
	double upperBound = 20;
	double lowerErrorBound = 1;
	double upperErrorBound = 2;

	//Load the data
	vector< vector<double> > xEvents, yEvents, yErrorEvents; //each of these is a vector of vectors (of randomized data points)
	for(int i = 0; i < nEvents; i++) 
	{
		vector <double> xData, yData, yErrorData; //temporary vectors that are only used to get random values from FillRand function
		FillRandVectors(nPoints, xData, yData, yErrorData, seed*(i+1), lowerBound, upperBound, lowerErrorBound, upperErrorBound); //populates random vectors for y values and y error vector
		xEvents.push_back(xData);
		yEvents.push_back(yData);
		yErrorEvents.push_back(yErrorData);
	}

	//Intialization of the variables
	const int npar = nPoints;
	const int orderSpline = 4;
	const int nbreak = npar+2-orderSpline;
	double stepSpline = 0.01;
	double xminBSplineWorkspace = 0;
	double xmaxBSplineWorkspace = 9;
	double startCSplineWorkspace = 15.;
	double stepCSplineWorkspace = 1.5;

	acc_GLOB = gsl_interp_accel_alloc ();
	spline_GLOB = gsl_spline_alloc (gsl_interp_cspline, nPoints);	
	bw_GLOB = gsl_bspline_alloc(orderSpline, nbreak);
	
	//B- and C-splines
	clock_t tbstart, tbstop, tcstart, tcstop;
	vector <double> timeb, timec;

	vector< vector<double> > xBSplineValues, yBSplineValues;
	vector< vector<double> > xCSplineValues, yCSplineValues; 

//Setup for the C-spline_________________________________________________________________________
	TMinuit *myMinuit = new TMinuit(npar);  //initialize TMinuit with a maximum of npar 
	myMinuit->SetFCN(fcn);
	myMinuit->SetPrintLevel(-1);//No output: -1, output:1

	double arglist[10];
	int ierflg = 0;
	arglist[0] = 1;
	myMinuit->mnexcm("SET ERR", arglist, 1, ierflg);

	//Initialize Minuit
	vector<double> vstart, vstep;
	for(int i=0; i<npar; i++) 	//set starting values and step sizes for parameters
	{
		vstart.push_back(startCSplineWorkspace);
		vstep.push_back(stepCSplineWorkspace);
	}

	for (int i = 0; i < npar; i++) {
		stringstream ss;
		ss<<"a"<<i;
		myMinuit->mnparm(i, ss.str().c_str(), vstart.at(i), vstep.at(i), 0, 0, ierflg);
	}

//Setup for the B-spline_________________________________________________________________________

	//Looping begins for the calculations of the B and C-splines for each event
	for(int i = 0; i < (int)xEvents.size(); i++)
	{
		//Populate the global variables
		xData_GLOB = xEvents.at(i);
		yData_GLOB = yEvents.at(i);
		yErrorData_GLOB = yErrorEvents.at(i);

		tbstart = clock();
		vector< vector<double> > bSplineValues = bSpline(nPoints, npar, xEvents.at(i), yEvents.at(i), yErrorEvents.at(i), stepSpline, xminBSplineWorkspace, xmaxBSplineWorkspace);
		tbstop = clock();
		timeb.push_back(((float)tbstop-(float)tbstart)/ (CLOCKS_PER_SEC/1000.) );		

		std::cout<<timeb.back()<<std::endl;

		xBSplineValues.push_back(bSplineValues.at(0));
		yBSplineValues.push_back(bSplineValues.at(1));

		tcstart = clock();
		vector< vector<double> > cSplineValues = cSpline(nPoints, npar, xEvents.at(i), stepSpline, myMinuit);
		tcstop = clock();
		timec.push_back(((float)tcstop-(float)tcstart)/ (CLOCKS_PER_SEC/1000.) );		

		xCSplineValues.push_back(cSplineValues.at(0));
		yCSplineValues.push_back(cSplineValues.at(1));
	}

	//Histograms______________________________________________________________________________________

	//Time
	int nbins = 100;
	double xlow = 0;
	double xup = 1.;

	TH1D *hTimeB = new TH1D("Time","Timing; time [ms]; Number of Events", nbins, xlow, xup); 
	hTimeB->SetStats(0);
	hTimeB->SetMarkerStyle(10);
	TH1D *hTimeC = new TH1D("TimeC","Timing; time [ms]; Number of Events", nbins, xlow, xup); 
	hTimeC->SetLineColor(kRed);
	hTimeC->SetMarkerStyle(10);
	hTimeC->SetStats(0);

	for(int i=0; i<(int)timec.size(); i++) 
	{
		hTimeB->Fill(timeb.at(i));
		hTimeC->Fill(timec.at(i));	
	}

	//Interpolation
	vector <double> interpB, interpC;
	for(int i = 0; i < (int)yEvents.size(); i++)
	{
		for(int j = 0; j < (int)yEvents[i].size(); j++)
		{
			int indexForB = binarySearch(xBSplineValues[i], xEvents[i][j]);
			int indexForC = binarySearch(xCSplineValues[i], xEvents[i][j]);

			interpB.push_back( (yEvents[i][j]-yBSplineValues[i][indexForB])/yErrorEvents[i][j] );
			interpC.push_back( (yEvents[i][j]-yCSplineValues[i][indexForC])/yErrorEvents[i][j] );
		}
	}	

	//Test graphs for splines
	TGraph *GCspline = new TGraph(xCSplineValues[iEventLook].size(), &xCSplineValues[iEventLook][0], &yCSplineValues[iEventLook][0]);
	GCspline->SetLineColor(kRed);
	TGraph *GBspline = new TGraph(xBSplineValues[iEventLook].size(), &xBSplineValues[iEventLook][0], &yBSplineValues[iEventLook][0]);
	TGraph *Gdata = new TGraph(xEvents[0].size(), &xEvents[iEventLook][0], &yEvents[iEventLook][0]);
		Gdata->SetMarkerStyle(20);

	int nbinsI = 101;
	double xlowI = -0.1;
	double xupI = 0.1;
	TH1D *hInterpB = new TH1D("Interp B","Interpolation; Distance between spline and data normalized by error; Number of Events", nbinsI, xlowI, xupI); 
	for(int i=0; i<(int)interpB.size(); i++) hInterpB->Fill(interpB.at(i));
	hInterpB->SetStats(0);

	TH1D *hInterpC = new TH1D("Interp C","Interpolation; Distance between spline and data normalized by error; Number of Events", nbinsI, xlowI, xupI); 
	for (int i=0; i<(int)interpC.size(); i++) hInterpC->Fill(interpC.at(i));
	hInterpC->SetLineColor(kGreen);
	hInterpC->SetStats(0);	

	//Draws______________________________________________________________________________________

	//Interpolation 
	TLegend *legInterp = new TLegend(0.9,0.70,0.75,0.85);
	legInterp->SetLineColor(kWhite); 
	legInterp->SetFillColor(kWhite);
	legInterp->SetMargin(0.3); 
	legInterp->AddEntry(hInterpB,"b-spline","l");
	legInterp->AddEntry(hInterpC,"c-spline","l");
	legInterp->SetTextSize(0.05);

	TCanvas *c1 = new TCanvas("c1", "Interpolation distance");
	c1->cd();
	hInterpB->Draw("");
	hInterpC->Draw("same");
	legInterp->Draw();

	//Time
	TLegend *legTime = new TLegend(0.9,0.70,0.75,0.85);
	legTime->SetLineColor(kWhite); 
	legTime->SetFillColor(kWhite);
	legTime->SetMargin(0.3); 
	legTime->AddEntry(hTimeB,"b-spline","l");
	legTime->AddEntry(hTimeC,"c-spline","l");
	legTime->SetTextSize(0.05);

	TCanvas *c2 = new TCanvas("c2", "Computation time");
	c2->cd();
	hTimeB->Draw();
//	hTimeC->Draw("same");
	legTime-> Draw();

	TCanvas *c3 = new TCanvas("c3", "Test splines");
	c3->cd();
	Gdata->Draw("ap");
	GCspline->Draw("samel");
	GBspline->Draw("samel");

	//Free the memory used
	gsl_spline_free (spline_GLOB); 
 	gsl_interp_accel_free (acc_GLOB);
	gsl_bspline_free(bw_GLOB);
}
Ejemplo n.º 21
0
//______________________________________________________________________________
vector< vector<double> > cSpline(int nPoints, int npar, vector <double> xData, vector <double> yData, vector <double> yErrorData, double stepSpline =.01, double start = 10., double step = 0.01)
{
	//Populate the global variables
	xData_GLOB = xData;
	yData_GLOB = yData;
	yErrorData_GLOB = yErrorData;

	//Initialize Minuit
	vector<double> vstart, vstep;
	for(int i=0; i<npar; i++) 	//set starting values and step sizes for parameters
	{
		vstart.push_back(start);
		vstep.push_back(step);
	}

	TMinuit *myMinuit = new TMinuit(npar);  //initialize TMinuit with a maximum of npar (5)
	myMinuit->SetFCN(fcn);
	myMinuit->SetPrintLevel(-1);//No output: -1, output:1

	double arglist[10];
	int ierflg = 0;
	arglist[0] = 1;
	myMinuit->mnexcm("SET ERR", arglist, 1, ierflg);

	for (int i = 0; i < npar; i++) {
		stringstream ss;
		ss<<"a"<<i;
		myMinuit->mnparm(i, ss.str().c_str(), vstart.at(i), vstep.at(i), 0, 0, ierflg);
	}

	//Perform the Minuit fit
	arglist[0] = 500;
	arglist[1] = 1.;
	myMinuit->mnexcm("MIGRAD", arglist, 2, ierflg); //minimization

	//Retrieve best-fit parameters
	vector< double > bestFitParams, e_bestFitParams;
	for(int i=0; i<npar; i++)
	{
		double par, epar;
		myMinuit->GetParameter(i, par, epar); //retrieve best fit parameters
		bestFitParams.push_back(par);
		e_bestFitParams.push_back(epar);
	}

	//Store the best-fit spline in a TGraph
	gsl_spline_init (spline_GLOB, &xData[0], &bestFitParams[0], xData.size()); //initialize the spline

	int nPointsSpline = int ((xData[nPoints-1]-xData[0])/stepSpline); //calculate the number of points of the spline
	vector< double > xSpline, ySpline;
	for (int i= 0; i < nPointsSpline; i++){
		xSpline.push_back(xData[0]+i*stepSpline);
		ySpline.push_back(gsl_spline_eval (spline_GLOB, xSpline.back(), acc_GLOB));
	}

	//Construct a vector of vectors that will store the xSpline values and the ySpline values
	vector< vector<double> > cSplineValues;
	cSplineValues.push_back(xSpline);
	cSplineValues.push_back(ySpline);

	return cSplineValues;
}
Ejemplo n.º 22
0
void fill_minEE_class::Loop()
{


   TFile *fpyt = new TFile("files/pythiaD6T_ee_v1.root");
   TTree *tree_pyt = (TTree*)gDirectory->Get("tree_");


   //   TFile *fpom = (TFile*)gROOT->GetListOfFiles()->FindObject("files/DiffractiveMC.root");
   TFile *fpom = new TFile("files/DiffractiveMC_ee_v1.root");
   TTree *tree_pom = (TTree*)gDirectory->Get("tree_");

   //   TFile *fzee = (TFile*)gROOT->GetListOfFiles()->FindObject("files/ZetaSkim_ee.root");
   TFile *fzee = new TFile("files/ZetaSkim_ee_v1.root");
   //   TFile *fzee = new TFile("files/ZetaSkim_mm.root");
   TTree *tree_zee = (TTree*)gDirectory->Get("tree_");



   //   Int_t hnbin = 25;
   Float_t llow = 0.;
   Float_t lup = 250.;
   TH1F *Hpompyt = new TH1F("Hpompyt", "pompyt", hnbin, llow, lup);
   TH1F *Hpythia = new TH1F("Hpythia", "pythia", hnbin, llow, lup);
   TH1F *Hdata = new TH1F("Hdata", "data", hnbin, llow, lup);
   TH1F *HSum = new TH1F("HSum", "HSum", hnbin, llow, lup);

   NCanvas(1,1);
   //Go to  Pythia

   fChain =tree_pyt;
   Init(fChain);


   Long64_t nentries = fChain->GetEntriesFast();   
   cout << "number of entries in Pythia = " << nentries << endl; 
   
   Long64_t nbytes = 0, nb = 0;
   for (Long64_t jentry=0; jentry<nentries;jentry++) {
     Long64_t ientry = LoadTree(jentry);
     if (ientry < 0) break;
     
     nb = fChain->GetEntry(jentry);   nbytes += nb;
     // if (Cut(ientry) < 0) continue;     
     if (numberOfVertexes == 1){
     Hpythia->Fill(TMath::Min(energyTot_PF_EE_minus,energyTot_PF_EE_plus));
     }
   }


   // go to Pompyt

   fChain = tree_pom;
   Init(fChain);
   nentries = fChain->GetEntriesFast();
   cout << "number of entries in Pompyt = " << nentries << endl; 
   
   nbytes = 0, nb = 0;
   for (jentry=0; jentry<nentries;jentry++) {
     ientry = LoadTree(jentry);
     if (ientry < 0) break;
     
     nb = fChain->GetEntry(jentry);   nbytes += nb;
     // if (Cut(ientry) < 0) continue;
     if (numberOfVertexes == 1){
       Hpompyt->Fill(TMath::Min(energyTot_PF_EE_minus,energyTot_PF_EE_plus));
     }
   }
   
   
   // go to  Zee

   fChain = tree_zee;
   Init(fChain);
   nentries = fChain->GetEntriesFast();
   cout << "number of entries in Zee = " << nentries << endl; 
   nbytes = 0, nb = 0;
   for (jentry=0; jentry<nentries;jentry++) {
     ientry = LoadTree(jentry);
     if (ientry < 0) break;
     
     nb = fChain->GetEntry(jentry);   nbytes += nb;
     // if (Cut(ientry) < 0) continue;
     //      Zee->cd();
     if (numberOfVertexes == 1){
     Hdata->Fill(TMath::Min(energyTot_PF_EE_minus,energyTot_PF_EE_plus));
     }
   }
     


   // Show the results

   MyC->cd(1);

   Hpythia->Draw();
   Hpompyt->Draw("SAMES");
   Hdata->Draw("SAMES");
   


  //  cout << Pcdata->lenght() << endl;

  NHtoV(Hdata, Pcdata, Pedata);
  NHtoV(Hpompyt, Pcpompyt, Pepompyt);
  NHtoV(Hpythia, Pcpythia, Pepythia);


 cout << " the content of data[2] is = " << Pcdata[2] << "+-"<<Pedata[2] << endl ;
 cout << " the content of pythia[2] is = " << Pcpythia[2] << "+-"<<Pepythia[2] << endl ;
 cout << " the content of pythia[2] is = " << Pcpompyt[2] << "+-"<<Pepompyt[2] << endl ;


 // Here  we go: the minuit show
 
  TMinuit *gMinuit = new TMinuit(NPAR);  //initialize TMinuit with a maximum of NPAR params
  gMinuit->SetFCN(fcn);
  
  Double_t arglist[NPAR]; // ???
  Int_t ierflg = 0;

// Set starting values and step sizes for parameters

  Double_t vstart[NPAR] ;
  Double_t step[NPAR] ;
  Double_t par[NPAR] ,fpar[NPAR];
  char parName[NPAR];
  Int_t n;
  parName[0] = "Pythia";
  parName[1] = "Pompyt";

  par[0] = Hdata->Integral()/Hpythia->Integral();
  par[1] = 0.05*Hdata->Integral()/Hpompyt->Integral();


  for (n=0 ; n<NPAR ; n++)
    {
      vstart[n] = par[n]  ;
      step[n] = 0.5 ;
      sprintf(parName,"a%d",n);
      gMinuit->mnparm(n, parName, vstart[n], step[n], 0,0,ierflg);
    }

  cout << "par[0] set to = " << par[0] << " while par[1] = " << par[1] << endl;
  arglist[0] = 1;

  gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);  
  gMinuit->mnexcm("SET PRINT", arglist,1,ierflg);

  //Scan on parameter = 1
  arglist[0] = 1;
  gMinuit->mnexcm("SCAN",  arglist,1,ierflg);
  
  //Maximum number of calls
  arglist[0] = 500;
  gMinuit->mnexcm("MIGRAD", arglist,1,ierflg);
 


  // Print results
  Double_t amin,edm,errdef;
  Int_t nvpar,nparx,icstat;

  gMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
  gMinuit->mnprin(3,amin);


  //Get the final fit parameters
  for (n=0 ; n<NPAR ; n++)
    {
      Double_t parameter, erro ;
      gMinuit->GetParameter(n,parameter,erro) ;
      fpar[n] = parameter ;
    }
  
  cout << " The final parameter values are: "<< fpar[0] << " , " << fpar[1] << endl;

  Float_t SD_frac = (fpar[1]*Hpompyt->Integral())/Hdata->Integral();
  //  Float_t NSD_events = fpar[0]*Hpythia->Integral();
  // Float_t Data_events = Hdata->Integral();

  cout << " The fraction of SD events is = " << SD_frac << endl;


  // }
  // void fill_minEE_class::show(){


  //Show the final plot

  MyC->cd(1);

  Hpythia->Scale(fpar[0]); 
  Hpompyt->Scale(fpar[1]); 

  Hdata->SetMarkerColor(2);
  Hdata->GetXaxis()->SetTitle("Min(EE-,EE+) Energy [GeV] ");
  Hdata->GetYaxis()->SetTitle("Entries");
  Hpompyt->SetLineColor(4);
  Hpythia->SetLineColor(6);
  Hpompyt->SetLineStyle(2);
  Hpythia->SetLineStyle(2);
   
  Float_t DMax = 1.2*Hdata->GetMaximum();
  Hdata->SetMaximum(DMax);
  Hdata->Draw("p");

  Hpythia->Draw("SAMES");
  Hpompyt->Draw("SAMES");
  
  HSum->Add(Hpythia);
  HSum->Add(Hpompyt);
  HSum->SetLineColor(1);
  HSum->SetLineStyle(1);
  HSum->Draw("SAMES");

}
Ejemplo n.º 23
0
void parab_fit(double ch2,jack &a,jack &b,jack &c,double *X,jvec Y,const char *path,bool fl_parab=1)
{
  ofstream out(path);
  out<<"@type xydy\n";
  
  double MX=0;
  //copy X
  nc_fit=Y.nel;
  X_fit=new double[nc_fit];
  for(int iel=0;iel<nc_fit;iel++)
    if(use[iel])
    {
      X_fit[iel]=X[iel];
      out<<X[iel]<<" "<<Y[iel]<<endl;
      if(X[iel]>MX) MX=X[iel];
    }
  Y_fit=new double[nc_fit];
  err_Y_fit=new double[nc_fit];
  
  TMinuit minu;
  minu.SetPrintLevel(0);
  
  int npars=3;
  minu.DefineParameter(0,"A",0.0,0.0001,0,0);
  minu.DefineParameter(1,"B",0.0,0.0001,0,0);
  minu.DefineParameter(2,"C",0.0,0.0001,0,0);
  if(!fl_parab)
    {
      minu.FixParameter(0);
      npars--;
    }
  minu.SetFCN(chi2_wr);
  
  for(int ijack=0;ijack<=njack;ijack++)
    {
      minu.DefineParameter(2,"C",fixed_A[ijack],0.0001,0,0);
      minu.FixParameter(2);
      if(ijack>0)
        minu.SetPrintLevel(-1);
      
      for(int iel=0;iel<nc_fit;iel++)
        {
          Y_fit[iel]=Y.data[iel].data[ijack];
          err_Y_fit[iel]=Y[iel].err();
        }
      
      //minimize
      minu.Migrad();
      
      //get back parameters
      double dum;
      minu.GetParameter(0,a.data[ijack],dum);
      minu.GetParameter(1,b.data[ijack],dum);
      minu.GetParameter(2,c.data[ijack],dum);
    }
  
  out<<"&\n@type xy\n";
  for(double t=0;t<MX;t+=MX/100)
    out<<t<<" "<<parab(a[njack],b[njack],c[njack],t)<<endl;
  
  out.close();
}
Ejemplo n.º 24
0
// -- main function
void fit_chi2(TH1D* dataInput, TH1D* sigTemplate, TH1D* bkgTemplate, std::string prefix, Double_t& sigFrac, Double_t& sigFrac_err)
{
  gStyle->SetOptStat(kFALSE);
  gStyle->SetCanvasColor(0);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetPadBorderMode(0);
  gStyle->SetFrameBorderMode(0);

  Double_t scale=1.;

  data = (TH1D*)dataInput->Clone();
  data->SetName("data");
  data->SetLineColor(1);
  data->SetMarkerColor(1);
  data->SetXTitle("Fisher's isolation [GeV]");
  data->Sumw2();
  scale = 1.0/(Double_t)data->Integral(0,1000); 
  cout << "scale for data = " << scale << endl;
  data->Scale(scale);


  fit_result = (TH1D*)dataInput->Clone();
  fit_result->SetName("fit_result");
  fit_result->SetLineColor(8); 
  fit_result->SetMarkerColor(8);
  fit_result->SetLineStyle(2);
  fit_result->Sumw2();
  fit_result->Reset();


  signal_pos = (TH1D*)sigTemplate->Clone();
  signal_pos->SetName("signal_pos");
  signal_pos->SetLineColor(2);
  signal_pos->SetMarkerColor(2);
  signal_pos->SetFillColor(2);
  signal_pos->SetXTitle("Fisher's isolation [GeV]");
  signal_pos->Sumw2();
  scale = 1.0/(Double_t)signal_pos->Integral(0,1000); 
  cout << "scale for signal template = " << scale << endl;
  signal_pos->Scale(scale);


  background_pos = (TH1D*)bkgTemplate->Clone();
  background_pos->SetName("background_pos");
  background_pos->SetLineColor(4);
  background_pos->SetMarkerColor(4);
  background_pos->SetFillColor(4);
  background_pos->SetXTitle("Fisher's isolation [GeV]");
  background_pos->Sumw2();
  scale = 1.0/(Double_t)background_pos->Integral(0,1000); 
  cout << "scale for background template = " << scale << endl;
  background_pos->Scale(scale);



  TMinuit *gMinuit = new TMinuit(1);  //initialize TMinuit with a maximum of 5 (1param??) params
  gMinuit->SetFCN(fcn); // sets function to minimize: fcn is Chi2 with errors on templates

  Double_t arglist[10];
  Int_t ierflg = 0; // status flag, it is 0 when ereything goes fine

  // -- sets error
  arglist[0] = 1;
  gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);


  Double_t vstart = 0.5;
  Double_t step = 0.001;
  gMinuit->mnparm(0, "fsig", vstart, step, 0,1,ierflg);



  // Now ready for minimization step
  arglist[0] = 1000;
  arglist[1] = 0.01;
  gMinuit->mnexcm("MIGRAD", arglist ,2,ierflg);

  Double_t fsig=0;
  Double_t fsigerr=0;
  Double_t chi2 = 0;


  if ( ierflg == 0 ) 
    {

      // Print results
      Double_t amin,edm,errdef;
      Int_t nvpar,nparx,icstat;
      gMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
      gMinuit->mnprin(3,amin);
      chi2 = gMinuit->fAmin;
      gMinuit->GetParameter(0, fsig, fsigerr);  
      cout << "Fsig = " << fsig << " +- " << fsigerr << endl;

      TCanvas* c1 = new TCanvas("c1","",500,500);

      data->Draw();
      TH1D* signal_display = (TH1D*)signal_pos->Clone();
      signal_display->SetName("signal_display");
      signal_display->Scale(fsig/signal_display->Integral(0,1000));
      signal_display->SetFillStyle(3001);
      signal_display->Draw("histsame");

      TH1D* background_display = (TH1D*)background_pos->Clone();
      background_display->SetName("background_display");
      background_display->Scale((1-fsig)/background_display->Integral(0,1000));
      background_display->SetFillStyle(3001);
      background_display->Draw("histsame");

      fit_result->Draw("histesame");

      char result[300];
      sprintf(result,"fsig = %.3lf #pm %.3lf",fsig,fsigerr);
      sigFrac = fsig;
      sigFrac_err = fsigerr;

      TLegend* leg = new TLegend(0.2,0.6,0.4,0.9);
      leg->SetHeader(result);
      leg->SetFillColor(0);
      leg->SetFillStyle(0);
      leg->SetTextSize(0.045);
      leg->SetBorderSize(0);
      leg->AddEntry(data,"data");
      leg->AddEntry(fit_result,"fit");
      leg->AddEntry(signal_display,"signal template");
      leg->AddEntry(background_display,"background template");
      leg->Draw("same");

      std::string outputFile = prefix + ".eps";
      c1->Print(outputFile.data());

      outputFile = prefix + ".gif";
      c1->Print(outputFile.data());

      outputFile = prefix + ".C";
      c1->Print(outputFile.data());
    }
    
  else{
    cout << "Fit failed!\n";
    sigFrac = 0;
    sigFrac_err = 0;
  }

  
  return;

}
Ejemplo n.º 25
0
void fit(boot &A,boot &B,boot &C,boot &D)
{
  //copy ml
  ml_fit=new double[nens];
  for(int iens=0;iens<nens;iens++) ml_fit[iens]=ml[iens].med();
  
  //alloc dM2Pi and dM2K
  dM2Pi_fit=new double[nens];
  err_dM2Pi_fit=new double[nens];
  dM2K_fit=new double[nens];
  err_dM2K_fit=new double[nens];
  
  TMinuit minu;
  minu.SetPrintLevel(-1);
  
  int npars=4;
  minu.DefineParameter(0,"A",0.0,0.0001,0,0);
  minu.DefineParameter(1,"B",0.0,0.0001,0,0);
  minu.DefineParameter(2,"C",0.0,0.0001,0,0);
  minu.DefineParameter(3,"D",0.0,0.0001,0,0);
  minu.SetFCN(chi2_wr);
  
  double C2;
  for(int iboot=0;iboot<nboot+1;iboot++)
    {
      if(iboot>0) minu.SetPrintLevel(-1);
      
      minu.DefineParameter(4,"a380",lat[0][iboot],0.0001,0,0);
      minu.DefineParameter(5,"a390",lat[1][iboot],0.0001,0,0);
      minu.DefineParameter(6,"a405",lat[2][iboot],0.0001,0,0);
      minu.DefineParameter(7,"a420",lat[3][iboot],0.0001,0,0);
      minu.FixParameter(4);
      minu.FixParameter(5);
      minu.FixParameter(6);
      minu.FixParameter(7);
      
      for(int iens=0;iens<nens;iens++)
        {
          dM2Pi_fit[iens]=dM2Pi.data[iens].data[iboot];
          err_dM2Pi_fit[iens]=dM2Pi.data[iens].err();
          dM2K_fit[iens]=dM2K.data[iens].data[iboot];
          err_dM2K_fit[iens]=dM2K.data[iens].err();
        }
      
      //minimize
      minu.Migrad();
      
      //get back parameters
      double dum;
      minu.GetParameter(0,A.data[iboot],dum);
      minu.GetParameter(1,B.data[iboot],dum);
      minu.GetParameter(2,C.data[iboot],dum);
      minu.GetParameter(3,D.data[iboot],dum);
      
      double lat_med[4]={lat[0].med(),lat[1].med(),lat[2].med(),lat[3].med()};
      if(iboot==nboot) C2=chi2(A.data[iboot],B[iboot],C[iboot],D[iboot],lat_med,true);
    }
  
  //calculate the chi2
  cout<<"A=("<<A<<"), B=("<<B<<"), C=("<<C<<"), D=("<<D<<")"<<endl;
  cout<<"Chi2 = "<<C2<<" / "<<2*nens-npars<<" = "<<C2/(2*nens-npars)<<endl;
  
  delete[] ml_fit;
  delete[] dM2Pi_fit;
  delete[] err_dM2Pi_fit;
  delete[] dM2K_fit;
  delete[] err_dM2K_fit;
}
Ejemplo n.º 26
0
//___________________________________________________________________________
Double_t* Ifit( TFile* fin, std::string name, std::string output=".", std::string xTitle="", std::string yTitle="Events", int rebin=1, int channel=0, int fit_data=1 )
{
    Double_t* fitted = new Double_t[8];

    TCanvas *c1 = new TCanvas("HF1", "Histos1", 258,92,748,702);
    c1->Range(-104.4905,-2560.33,537.9965,11563.46);
    c1->SetFillColor(0);
    c1->SetBorderMode(0);
    c1->SetBorderSize(2);
    c1->SetLeftMargin(0.1626344);
    c1->SetRightMargin(0.05913978);
    c1->SetTopMargin(0.05349183);
    c1->SetBottomMargin(0.1812779);
    c1->SetFrameBorderMode(0);
    c1->SetFrameBorderMode(0);

    double count=0;
    dataColl.clear();
    sigColl.clear();
    bkgColl.clear();

    totalColl.clear();
    ctauColl.clear();

    //Get data from looping tree

    //TFile *fin = new TFile("results/15Dec_LepJet_MCDATA/Template_EvtChi2_Top_Hadronic_Mass.root");
    //TFile *fin = new TFile("results/15Dec_LepJet_MCDATA/Template_EvtChi2_Top_Leptonic_Mbl.root");


    //   TH1D *hsig = new TH1D();
    //   TH1D *hbkg = new TH1D();
    TH1D *hsig_toymc = new TH1D();
    TH1D *hbkg_toymc = new TH1D();

    char hname[30];
    std::string ch;
    if( channel == 1 )
        ch="_El";
    else if( channel == 2)
        ch="_Mu";
    else
        ch="";

    TH1D * hsig = (TH1D*)((TH1D*)fin->Get(("SigMC"+ch).c_str()))->Clone();
    TH1D * hbkg = (TH1D*)((TH1D*)fin->Get(("BkgMC"+ch).c_str()))->Clone();
    TH1D *hEGdata;
    hEGdata = (TH1D*)((TH1D*)fin->Get(("DATA"+ch).c_str()))->Clone();

    // hsig->Sumw2();
    //hbkg->Sumw2();

    // hsig->Rebin(2);
    // hbkg->Rebin(2);
    // hEGdata->Rebin(2);
    // hbkg_toymc->Rebin(2);
    // hsig_toymc->Rebin(2);

    hsig->Rebin(rebin);
    hbkg->Rebin(rebin);
    hEGdata->Rebin(rebin);

    // normalize template
    hsig->Scale(1./hsig->Integral());
    hbkg->Scale(1./hbkg->Integral());  
    if(fit_data==0){
        hsig_toymc->Scale(1./hsig_toymc->Integral());
        hbkg_toymc->Scale(1./hbkg_toymc->Integral());
    }

  TH1D *hsum = new TH1D();
  int ntemplate = 1000.;
  float sigfrac = 0.5;
  TH1D *hsum_norm = new TH1D();
  TH1D *hdata = new TH1D();

  int ndata=0;
  if ( fit_data>0 ) {
    hdata = (TH1D*)hEGdata->Clone();
    ndata = hdata->GetEntries();
  }else { //generate toymc
    hsum = (TH1D*)hsig_toymc->Clone();
    hsum->Scale(toymc_sig);
    hsum->Add(hbkg_toymc,toymc_bkg);
    
    hsum_norm = (TH1D*)hsum->Clone();  
    hsum_norm->Scale(1./hsum->Integral());
    hdata = (TH1D*)hsum_norm->Clone();
    //ndata = (int) gRandom->Poisson(hsum->Integral());
    ndata=toymc_sig+toymc_bkg;
    hdata->FillRandom(hsum_norm, ndata);
  }
  if(ndata==0) {
    printf(" ---  no events in the fit \n");
    fitted[0] = 0.;
    fitted[1] = 0.;
    fitted[2] = 0.;
    fitted[3] = 0.;
    fitted[4] = 0.;
    fitted[5] = 0.;
    fitted[6] = 0.;
    fitted[7] = 0.;
    fin_data->Close();
    fin->Close();
    fin_gjet6000->Close();

    return fitted;
  }    

  printf(" --------- before the fit ------------- \n");
  printf("Nsig %2.3f, Nbg %2.3f, Ntemplate %3.3f \n", hsig->Integral(), hbkg->Integral(), ntemplate);
  printf("Purity %2.3f, init size %4.3f,  test sample size %4d\n", hsig->Integral()/hsum->Integral(), hsum->Integral(), ndata);
  printf(" -------------------------------------- \n");

  int nbins = hdata->GetNbinsX();
  for (int ibin=1; ibin<=nbins; ibin++) {
    dataColl.push_back(hdata->GetBinContent(ibin));
    sigColl.push_back(hsig->GetBinContent(ibin));
    bkgColl.push_back(hbkg->GetBinContent(ibin));    
  }
  printf( " -----  Got %d, %d, %d events for fit ----- \n ", dataColl.size(), sigColl.size(), bkgColl.size() );  
  if ( dataColl.size() != sigColl.size() || sigColl.size()!=bkgColl.size() ) {
    printf(" error ...  inconsistent hit collection size \n");
    fin_data->Close();
    fin->Close();
    fin_gjet6000->Close();

    return fitted;
  }

  //--------------------------------------------------
  //init parameters for fit
  Double_t vstart[10] = {1., 1.};
  vstart[0] = sigfrac*ndata;
  vstart[1] = (1-sigfrac)*ndata;
 
  TMinuit *gMinuit = new TMinuit(NPAR);  
  gMinuit->Command("SET STR 1");
  gMinuit->SetFCN(fcn);
  Double_t arglist[10];
  Int_t ierflg = 0;
  
  arglist[0] = 1;
  gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);
  arglist[0] = 1;
  gMinuit->mnexcm("SET PRINT", arglist ,1,ierflg);

  Double_t step[] = { 0.1, 0.1,};

  gMinuit->mnparm(0,  "Signal yield"  , vstart[0],  step[0], 0., ndata*2.  , ierflg);
  gMinuit->mnparm(1,  "background yield"  , vstart[1],  step[1], 0., ndata*2. , ierflg);
  
  printf(" --------------------------------------------------------- \n");
  printf(" Now ready for minimization step \n --------------------------------------------------------- \n");
  
  arglist[0] = 2000; // number of iteration
  arglist[1] = 1.;
  gMinuit->mnexcm("MIGRAD", arglist ,2,ierflg);
  printf (" -------------------------------------------- \n");
  printf("Finished.  ierr = %2.2f \n", ierflg);

  info.clear();
  info_err.clear();

  double para[NPAR+1],errpara[NPAR+1];
  if ( ierflg == 0 ) 
    {
      for(int j=0; j<=NPAR-1;j++) {
        gMinuit->GetParameter(j, para[j],errpara[j]);
        para[NPAR] = dataColl.size();
        info.push_back(para[j]);
        info_err.push_back(errpara[j]);
        printf("Parameter (yeild) %d = %f +- %f\n",j,para[j],errpara[j]);
	
      }
      printf(" fitted yield %2.3f \n", (para[0]+para[1])/ndata );

      info.push_back(sigColl.size());

      //do minos if fit sucessed.
//       printf("         ---------------------------------------------------------\n");
//       printf("          Now call for minos step \n");
//       printf("         ---------------------------------------------------------\n");
      
//       arglist[0] = 200; // number of iteration
//       arglist[1] = 1;
//       gMinuit->mnexcm("MINOS", arglist ,2,ierflg);
//       printf("         --------------------------------------------------------- \n");
//       printf("         Done Minos.  ierr = %d \n", ierflg);
//       Double_t amin;
//       gMinuit->mnprin(1,amin);
    }
  else {
    printf(" *********** Fit failed! ************\n");
    gMinuit->GetParameter(0, para[0],errpara[0]);
    gMinuit->GetParameter(1, para[1],errpara[1]);
    para[0]=0.; errpara[0]=0.;
  }

  
  // Print results
  Double_t amin,edm,errdef;
  Int_t nvpar,nparx,icstat;
  gMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
  gMinuit->mnprin(1,amin);  
  gMinuit->mnmatu(1);
  printf(" ========= happy ending !? =========================== \n");
  
  printf("FCN =  %3.3f \n", amin);

  double yerr[100];
  for(int i=0;i<100;i++){
    yerr[i] = 0.;
  }

  hsig->Scale(para[0]);
  hbkg->Scale(para[1]);
  TH1D *hfit = (TH1D*)hbkg->Clone();
  hfit->Add(hsig);

  hsig->SetLineColor(4);
  hsig->SetLineWidth(2);
//   hsig->SetFillColor(5);
//   hsig->SetFillStyle(3001);

//   hbkg->SetLineWidth(2);
  // plot
  c1->Draw();  
    gStyle->SetOptStat(0);
    gStyle->SetOptTitle(0); 
  //gPad->SetLogy();
  hdata->SetLineColor(1);

  hdata->SetXTitle(xTitle.c_str());
  hdata->SetYTitle(yTitle.c_str());
  hdata->SetTitle("");
  hdata->SetMarkerStyle(8);
  hdata->SetMinimum(0.);
  hdata->GetXaxis()->SetNdivisions(505);
  hdata->GetXaxis()->SetLabelFont(42);
  hdata->GetXaxis()->SetLabelSize(0.05);
  hdata->GetXaxis()->SetTitleSize(0.06);
  hdata->GetXaxis()->SetTitleOffset(1.15);
  hdata->GetXaxis()->SetTitleFont(42);
  hdata->GetYaxis()->SetNdivisions(505);
  hdata->GetYaxis()->SetLabelFont(42);
  hdata->GetYaxis()->SetLabelSize(0.035);
  hdata->GetYaxis()->SetTitleSize(0.06);
  hdata->GetYaxis()->SetTitleOffset(1.21);
  hdata->GetYaxis()->SetTitleFont(42);

  float ymax = hdata->GetMaximum();
  if ( hfit->GetMaximum() > hdata->GetMaximum() ) ymax = hfit->GetMaximum();
  if ( hdata->GetMaximum() < 15 ) ymax = 15;
  hdata->SetMaximum(ymax*1.4);
  hfit->SetMaximum(ymax*1.4);
  hsig->SetMaximum(ymax*1.4);
  hbkg->SetMaximum(ymax*1.4);

  hdata->Draw("p e");

  hbkg->SetMarkerStyle(0);
  hbkg->SetFillColor(2);
  hbkg->SetLineWidth(1);
  hbkg->SetLineColor(2);
  hbkg->SetFillStyle(3005);
  hbkg->SetError(yerr);
  hbkg->Draw("h same");

  hsig->SetMarkerStyle(0);
  hsig->SetError(yerr);
  hsig->Draw("h same");

  hfit->SetMarkerStyle(0);
  hfit->SetLineColor(1);
  hfit->SetLineWidth(2);
  hfit->SetError(yerr);
  //printf("nbins hfit %d \n", hfit->GetNbinsX());
  hfit->Draw("h same");
  hdata->Draw("p e same");
  
  TLegend *tleg = new TLegend(0.5241935,0.6344725,0.8682796,0.9331352,NULL,"brNDC");
  char text[50];
  sprintf(text,"Top Mass");
  //tleg->SetHeader(text);
  tleg->SetBorderSize(0);
  tleg->SetTextSize(0.03120357);
  tleg->SetLineColor(1);
  tleg->SetLineStyle(1);
  tleg->SetLineWidth(1);
  tleg->SetFillColor(0);
  tleg->SetFillStyle(0);
  sprintf(text,"Data %5.1f events",hdata->Integral());
  tleg->AddEntry(hdata,text,"pl");
  sprintf(text,"Fitted %5.1f events",hfit->Integral());
  
  tleg->AddEntry(hfit,text,"l");
  sprintf(text,"SIG %5.1f #pm %5.1f events",para[0], errpara[0]);
  tleg->AddEntry(hsig,text,"f");
  sprintf(text,"BKG %5.1f #pm %5.1f events",para[1], errpara[1]);
  
  tleg->AddEntry(hbkg,text,"f");
  tleg->Draw();
  
  TLatex *tlx = new TLatex(6.247421e-06,9218.143,"CMS #sqrt{s} = 8TeV, L=19.7 fb^{-1}");
  tlx->SetTextSize(0.035);
  tlx->SetLineWidth(2);
  tlx->Draw();

  //gPad->RedrawAxis();
  
  if(fit_data>0) hdata->Chi2Test(hfit,"P");

  c1->SaveAs((output+"/FittingResults_"+name+ch+".pdf").c_str());
  return fitted;

//   float sig_part = hsig->Integral(ibin1,hfit->GetNbinsX());
//   float sig_part_err = hsig->Integral(ibin1,hfit->GetNbinsX())*errpara[0]/para[0];
//   float bkg_part = hbkg->Integral(ibin1,hfit->GetNbinsX());
//   float bkg_part_err = hbkg->Integral(ibin1,hfit->GetNbinsX())*errpara[1]/para[1];
//   printf("%s Data %5.1f events, fitted %5.1f\n", EBEE, hdata->Integral(), hfit->Integral());
//   printf("%s Data %5.1f, and fitted (in 5GeV) %5.1f events \n", EBEE, hdata->Integral(ibin1,hfit->GetNbinsX()), hfit->Integral(ibin1,hfit->GetNbinsX()));
//   printf("%s SIG %5.1f #pm %5.1f events \n", EBEE, para[0], errpara[0]);
//   printf("%s SIG (in 5GeV) %5.1f #pm %5.1f events \n", EBEE, sig_part, sig_part_err);
//   printf("%s BKG %5.1f #pm %5.1f events \n", EBEE, para[1], errpara[1]);
//   printf("%s BKG (in 5GeV) %5.1f #pm %5.1f events \n", EBEE, bkg_part, bkg_part_err);
   

//   char fname[30];
//   sprintf(fname,"plots/test_Ifit%s_%d_%d.pdf",EBEE, jetbin, ptbin);
  
//   printf("----- fit results with signal projection   ----------- \n");
//   if(fit_data>0) hdata->Chi2Test(hfit,"P");
//   //ftemplate->Close();

//   fitted[0] = para[0];
//   fitted[1] = errpara[0]/TMath::Sqrt(2);
//   fitted[2] = para[1];
//   if (fit_data==2 ) fitted[2] += hdata->GetBinContent(hdata->GetNbinsX()+1);
//   fitted[3] = errpara[1]/TMath::Sqrt(2);
//   fitted[4] = sig_part;
//   fitted[5] = sig_part_err/TMath::Sqrt(2);
//   fitted[6] = bkg_part;
//   fitted[7] = bkg_part_err/TMath::Sqrt(2);
  
//   if(fit_data==0){
//     fin_filter->Close();
//     fin_data->Close();
//     fin->Close();
//     fin_gjet6000->Close();
//     fin_DYMC->Close();
//     fin_DYData->Close();
//     fin_WJetMC->Close();
//     fin_WJetData->Close();
//     fin_WJetTemplate->Close();
//     fin_WJetTemplate_alt->Close();
//   }

  return fitted;
}
//___________________________________________________________________________
Double_t* Ifit(int shift, Double_t& dataResult, Double_t& dataErr, std::string dataFile, 
	       TH1D* hsig, TH1D* hbkg, TH1D* hEGdata, Double_t* FitPar,
	       int ptbin=30, char EBEE[10]="EB", int fit_data=2)
{
  
  printf(" *** calling Ifit for %s , ptbin %d *** \n\n", EBEE,ptbin);

  cout << "The number of bins are: " << endl;
  cout << "hdata nbins = " << hEGdata->GetNbinsX() << endl;
  cout << "hsig nbins = " << hsig->GetNbinsX() << endl;
  cout << "hbkg nbins = " << hbkg->GetNbinsX() << endl;
  

  TCanvas *c1 = new TCanvas("HF1", "Histos1", 0, 0, 600, 600);
  gStyle->SetOptFit(0);

  if(fit_data != 3) dataColl.clear();
  sigColl.clear();
  bkgColl.clear();

  totalColl.clear();
  ctauColl.clear();
  Para.clear();
  Para_err.clear();

  info.clear();
  info_err.clear();

  float ptmax=0.;  
  if(ptbin== 21) ptmax= 23;
  if(ptbin== 23) ptmax= 26;
  if(ptbin== 26) ptmax= 30;
  if(ptbin== 30) ptmax= 35;
  if(ptbin== 35) ptmax= 40;
  if(ptbin== 40) ptmax= 45;
  if(ptbin== 45) ptmax= 50;
  if(ptbin== 50) ptmax= 60;
  if(ptbin== 60) ptmax= 85;
  if(ptbin== 85) ptmax= 120;
  if(ptbin== 120) ptmax= 300;
  if(ptbin== 300) ptmax= 500;



  Double_t* fitted = new Double_t[6];
  fitted[0] = 0.;    fitted[1] = 0.;    fitted[2] = 0.;    fitted[3] = 0.;
  fitted[4] = 0.;    fitted[5] = 0.;

  char hname[30];


  hsig->SetLineColor(1);
  hbkg->SetLineColor(1);
  hsig->SetNdivisions(505,"XY");
  hbkg->SetNdivisions(505,"XY");
  hsig->SetTitle("");
  hbkg->SetTitle("");
  hsig->SetXTitle("combined ISO (GeV)");
  hbkg->SetXTitle("combined ISO (GeV)");

  TH1F *hsum = (TH1F*)hsig->Clone();  
  hsum->Add(hbkg,1);
  float ntemplate = 1.;
  if (hsum->Integral()>1.) ntemplate = hsum->Integral();
  float sigfrac = hsig->Integral()/ntemplate*0.8;

  TH1F *hsum_norm = (TH1F*)hsum->Clone();  
  hsum_norm->Scale(1./hsum->Integral());

  TH1F *hdata = new TH1F();
  int ndata=0;
  if ( fit_data==1 ) {
    hdata = (TH1F*)hEGdata->Clone();
    ndata = (int)hdata->Integral();    
    for(int ibin=1; ibin<=hdata->GetNbinsX(); ibin++){
      for(int ipoint=0; ipoint<hdata->GetBinContent(ibin); ipoint++) {
	dataColl.push_back(hdata->GetBinCenter(ibin));
      }
    }
    ndata = dataColl.size();
  }else if (fit_data==2 ){
      hdata = (TH1F*)hEGdata->Clone();
    hdata -> Reset();
    dataColl.clear();
    FILE *infile =  fopen(dataFile.data(),"r");  
    float xdata, xdata1, xdata2; // combined isolation, pt, eta

    int flag = 1;
    while (flag!=-1){
      flag =fscanf(infile,"%f %f %f",&xdata, &xdata1, &xdata2);
      if( xdata1 >= ptbin && xdata1 < ptmax && xdata<20.) {
	if((strcmp(EBEE,"EB")==0 && TMath::Abs(xdata2)<1.45) ||
	   (strcmp(EBEE,"EE")==0 && TMath::Abs(xdata2)<2.5 && TMath::Abs(xdata2)>1.7) ) {
 	  dataColl.push_back(xdata);
	  hdata->Fill(xdata);
 	}
      } 
    }// keep reading files as long as text exists
    ndata = dataColl.size();

    printf("test print data 2 %2.3f \n", dataColl[2]);    
//     cout << "ndata in dataColl = " << ndata << endl;
    if ( ndata == 0 ) {
      printf(" no data to fit \n");
      return fitted;
    }
  }

  if(ndata==0) {
    printf(" ---  no events in the fit \n");
    return fitted;
  }
    
  //test fit the template and get PDFs
  TCanvas *c10 = new TCanvas("c10","c10",1000,500);
  c10->Divide(2,1);
  c10->cd(1);

  double par[20] = {hsig->GetMaximum(), 1., 0.6, 0.3,
		    hbkg->GetMaximum(), -.45, -0.05, 0.03, 1., 1., 1., 1.};

  if(strcmp(EBEE,"EE")==0) { par[2]=-0.1, par[3]=0.2; par[6]=-0.15; par[7]=0.02; };
  int fit_status;

  TF1 *f1 = new TF1("f1", exp_conv, -1., 20., 11);
  TF1 *fmcsigfit = new TF1("fmcsigfit", exp_conv, -1., 20., 11);
  fmcsigfit->SetLineColor(4);
  fmcsigfit->SetLineWidth(2);

  f1->SetNpx(10000);
  f1->SetParameters(par);
  f1->SetLineWidth(2);
  c10->cd(1);
  fit_status = hsig->Fit(f1,"","",-1., 5.);

  hsig->Draw();
  f1->Draw("same");
  if ( fit_status > 0 ) {
     printf("fit signal template failed. QUIT \n");
     return fitted;
  }
  if(para_index>0 && para_index<4){
    double tmppar = f1->GetParameter(para_index);
    f1->SetParameter(para_index, tmppar+para_sigma*f1->GetParError(para_index));
  }

  TF1 *fmcsig = (TF1*)f1->Clone();
  TF1 *fmcsigcorr = (TF1*)f1->Clone();
  fmcsig->SetNpx(10000);
  fmcsigcorr->SetNpx(10000);
  fmcsigfit->SetNpx(10000);
  
  TCanvas *c101 = new TCanvas("c101","c101",1000,500);
  c101->Divide(2,1);
  c101->cd(1);

  fmcsig->SetLineColor(1);
//   fmcsig->Draw();
//   f1->Draw("same");
  TH1F *htmp1 = (TH1F*)fmcsig->GetHistogram();
//   TH1F *htmp2 = (TH1F*)fmcsigcorr->GetHistogram();
  
  TH2F *htmp2 = new TH2F("htmp2","",210, -1., 20., 100, 0., htmp1->GetMaximum()*1.25);

  htmp2->SetNdivisions(505,"XY");
  htmp2->SetXTitle("Iso");
  htmp2->SetYTitle("A.U.");
  htmp2->SetLineColor(1);

//   htmp2->Draw();
//   htmp1->Draw("same");
//   htmp2->Add(htmp1,-1);
//   htmp2->Divide(htmp1);
  htmp2->GetXaxis()->SetRangeUser(-1., 10.);
  htmp2->SetMinimum(-1.);
  //htmp2->SetMaximum(1.5);
  htmp2->Draw();
  fmcsig->Draw("same");
//   fmcsigcorr->Draw("same");
  
  TLegend *tleg1 = new TLegend(0.5, 0.7, 0.93, 0.92);
  tleg1->SetHeader("");
  tleg1->SetFillColor(0);
  tleg1->SetShadowColor(0);
  tleg1->SetBorderSize(0);
  tleg1->AddEntry(fmcsig,"Zee data","l");
  //tleg1->AddEntry(fmcsigcorr,"corrected shape","l");
  tleg1->AddEntry(fmcsigfit,"shape from data","l");
  tleg1->Draw();

  //return fitted;
       
  SigPDFnorm = f1->Integral(-1.,20.);
  printf("status %d, sig area %3.3f \n", fit_status,f1->Integral(-1., 20.));


  f1->SetParameter(2,f1->GetParameter(2)+0.2);
  f1->SetParameter(3,f1->GetParameter(3)+0.1);

  Para.push_back(f1->GetParameter(0));
  Para.push_back(f1->GetParameter(1));
  Para.push_back(f1->GetParameter(2));
  Para.push_back(f1->GetParameter(3));

  Para_err.push_back(f1->GetParError(0));
  Para_err.push_back(f1->GetParError(1));
  Para_err.push_back(f1->GetParError(2));
  Para_err.push_back(f1->GetParError(3));

  c10->cd(2);
  TF1 *fbkgfit = new TF1("fbkgfit", expinv_power, -1., 20., 11);  

  TF1 *f3 = new TF1("f3", expinv_power, -1., 20., 11);
  fbkgfit->SetNpx(10000);  
  fbkgfit->SetLineColor(4);
  fbkgfit->SetLineWidth(2);

  f3->SetNpx(10000);
  f3->SetLineWidth(2);
  f3->SetParameters(f1->GetParameters());
    
  f3->SetParLimits(5,-5.,0.);
  f3->SetParLimits(6,-0.5,0.);
  f3->SetParLimits(7,0.001,0.2);
  f3->SetParLimits(8,0.5,5.);
  if ( strcmp(EBEE,"EB")==0 ){  
//     f3->FixParameter(8,1.);
//     f3->FixParameter(6,-0.1);
    f3->SetParLimits(8,1.,1.5);
  }

  float bkg_bend_power = 1.;
  if ( ptbin==21 ) bkg_bend_power = 4.5;
  if ( ptbin==23 ) bkg_bend_power = 4.;
  if ( ptbin==26 ) bkg_bend_power = 3.5;
  if ( ptbin==30 ) bkg_bend_power = 2.6;
  if ( ptbin==35 ) bkg_bend_power = 2.2;
  if ( ptbin==40 ) bkg_bend_power = 2.;
  if ( ptbin==45 ) bkg_bend_power = 2.;
  if ( ptbin==50 ) bkg_bend_power = 1.8;
  if ( ptbin==60 ) bkg_bend_power = 1.5;
  if ( ptbin==85 ) bkg_bend_power = 1.;
  if ( ptbin==120 ) bkg_bend_power = 1.;


  if ( strcmp(EBEE,"EE")==0 ){  
    f3->SetParameter(8,bkg_bend_power);
    f3->SetParLimits(8,bkg_bend_power-1., bkg_bend_power+1.);
  }

  f3->FixParameter(0,f3->GetParameter(0));
  f3->FixParameter(1,f3->GetParameter(1));
  f3->FixParameter(2,f3->GetParameter(2));
  f3->FixParameter(3,f3->GetParameter(3));

  hbkg->SetMaximum(hbkg->GetMaximum()*3.);
  fit_status = hbkg->Fit(f3,"b","",-1., 20.);
  hbkg->Draw();
  if ( fit_status > 0 ) {
    printf("fit background template failed. QUIT \n");    
    return fitted;
  }else {
    f3->Draw("same");
  }

  TF1 *fmcbkg = (TF1*)f3->Clone();
  fmcbkg->SetLineColor(1);
  c101->cd(2);

  htmp1 = (TH1F*)fmcbkg->GetHistogram();
  htmp2 = new TH2F("htmp2","",210, -1., 20., 100, 0., htmp1->GetMaximum()*1.25);

  htmp2->SetNdivisions(505,"XY");
  htmp2->SetXTitle("Iso");
  htmp2->SetYTitle("A.U.");
  htmp2->SetLineColor(1);

  htmp2->GetXaxis()->SetRangeUser(-1., 20.);
  htmp2->SetMinimum(-1.);
  htmp2->SetMaximum(1.5);
  htmp2->Draw();
  fmcbkg->Draw("same");

  TLegend *tleg2 = new TLegend(0.25, 0.2, 0.6, 0.42);
  tleg2->SetHeader("");
  tleg2->SetFillColor(0);
  tleg2->SetShadowColor(0);
  tleg2->SetBorderSize(0);
  if ( strcmp(EBEE,"EB")==0 ){  
    tleg2->AddEntry(fmcbkg,"MC shape","l");
  }else {
    tleg2->AddEntry(fmcbkg,"Data SB shape","l");
  }
  tleg2->AddEntry(fbkgfit,"shape from data","l");
  tleg2->Draw();
  
  if(para_index>4){
    double tmppar = f3->GetParameter(para_index);
    f3->SetParameter(para_index, tmppar+para_sigma*f3->GetParError(para_index));
  }

//   f3->SetParameter(5,-0.5);
//   f3->SetParameter(6,-0.05);
//   f3->SetParameter(7,0.02);
//   f3->SetParameter(8,1.);

  Para.push_back(f3->GetParameter(4));
  Para.push_back(f3->GetParameter(5));
  Para.push_back(f3->GetParameter(6));
  Para.push_back(f3->GetParameter(7)); 
  Para.push_back(f3->GetParameter(8)); 

  Para_err.push_back(f3->GetParError(4));
  Para_err.push_back(f3->GetParError(5));
  Para_err.push_back(f3->GetParError(6));
  Para_err.push_back(f3->GetParError(7));
  Para_err.push_back(f3->GetParError(8));

  BkgPDFnorm = f3->Integral(-1., 20.);
  printf("status %d, bkg area %3.3f \n", fit_status,f3->Integral(-1., 20.)/hdata->GetBinWidth(2));

  //test PDFs
  TCanvas *c11 = new TCanvas("c11","c11",1000,500);
  c11->Divide(2,1);
  c11->cd(1);
  TF1 *f11 = new TF1("f11",exp_conv_norm, -1., 20., 11);
  f11->SetNpx(10000);
  f11->SetParameters(f3->GetParameters());
  f11->Draw();
  printf(" SIG PDF area %2.3f \n", f11->Integral(-1., 20.));

  c11->cd(2);
  TF1 *f12 = new TF1("f12",expinv_power_norm, -1., 20., 11);
  f12->SetNpx(10000);
  f12->SetParameters(f3->GetParameters());
  f12->Draw();
  printf(" BKG PDF area %2.3f \n", f12->Integral(-1., 20.));

  //c1->cd();

  printf(" --------- before the fit ------------- \n");
  printf("Nsig %2.3f, Nbg %2.3f, Ntemplate %3.3f \n", hsig->Integral(), hbkg->Integral(), ntemplate);
  printf("Purity %2.3f, init size %4.3f,  fit sample size %4d\n", hsig->Integral()/hsum->Integral(), hsum->Integral(), ndata);
  printf(" -------------------------------------- \n");



  printf( " -----  Got %d, %d, %d events for fit ----- \n ", dataColl.size(),
	  sigColl.size(), bkgColl.size() );  

  //--------------------------------------------------
  //init parameters for fit
  Double_t vstart[11] = {1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.};
  vstart[0] = sigfrac*ndata;
  vstart[1] = (1-sigfrac)*ndata;
  for (int ii=0; ii<9; ii++) {    
    vstart[ii+2] = Para[ii]; //8 shape parameters
  }
  TMinuit *gMinuit = new TMinuit(NPAR);  
  gMinuit->Command("SET STR 1");
  gMinuit->SetFCN(fcn);
  Double_t arglist[11];
  Int_t ierflg = 0;
  
  arglist[0] = 1;
  gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);
  arglist[0] = 1;
  gMinuit->mnexcm("SET PRINT", arglist ,1,ierflg);

  Double_t step[] = { 1.,1.,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,};

  for ( int ii=0; ii<9; ii++){
    printf(" para %d, %.5f, err %.5f \n", ii, Para[ii], Para_err[ii]);
  }

  float sigma = 3.;
  gMinuit->mnparm(0,  "Signal yield"  , vstart[0],  step[0], 0., ndata*2.  , ierflg);
  gMinuit->mnparm(1,  "background yield"  , vstart[1],  step[1], 0., ndata*2. , ierflg);

//   gMinuit->mnparm(2,  "constant"     , Para[0],  0.00,  Para[0], Para[0] , ierflg);
//   gMinuit->mnparm(3,  "exp tail"     , Para[1],  0.01,  Para[1]-sigma*Para_err[1], Para[1]+sigma*Para_err[1], ierflg);
//   gMinuit->mnparm(4,  "exg mean"     , Para[2],  0.01,  Para[2]-sigma*Para_err[2], Para[2]+sigma*Para_err[2], ierflg);
//   gMinuit->mnparm(5,  "exg width"    , Para[3],  0.01,  Para[3]-sigma*Para_err[3], Para[3]+sigma*Para_err[3], ierflg);
//   gMinuit->mnparm(6,  "constant"     , Para[4],  0.00,  Para[4]                  , Para[4]                  , ierflg);
//   gMinuit->mnparm(7,  "bg exp turnon", Para[5],  0.01,  Para[5]-sigma*Para_err[5], Para[5]+sigma*Para_err[5], ierflg);
//   gMinuit->mnparm(8,  "bg x offset  ", Para[6],  0.01,  Para[6]-sigma*Para_err[6], Para[6]+sigma*Para_err[6], ierflg);
//   gMinuit->mnparm(9,  "bg bend slope", Para[7],  0.01,  0.001                    , 0.1                      , ierflg);
// //   gMinuit->mnparm(10, "bg bend power", Para[8],  0.01,  Para[8]-sigma*Para_err[8], Para[8]+sigma*Para_err[8], ierflg);
//   gMinuit->mnparm(10, "bg bend power", Para[8],  0.01,  0.5                       , 5.                       , ierflg);

//   gMinuit->mnparm(2,  "constant"     , Para[0], TMath::Abs(Para[0]*0.0) ,  Para[0], Para[0], ierflg);
//   gMinuit->mnparm(3,  "exp tail"     , Para[1], TMath::Abs(Para[1]*0.01) ,  Para[1]-sigma*Para_err[1], Para[1]+sigma*Para_err[1], ierflg); 
// //   gMinuit->mnparm(3,  "exp tail"     , Para[1], TMath::Abs(Para[1]*0.1) ,  0.8    , 1.3    , ierflg);
//   gMinuit->mnparm(4,  "exg mean"     , Para[2], TMath::Abs(Para[2]*0.1) ,  0.5    , 1.0    , ierflg);
//   gMinuit->mnparm(5,  "exg width"    , Para[3], TMath::Abs(Para[3]*0.1) ,  0.25   , 0.5    , ierflg);
//   gMinuit->mnparm(6,  "constant"     , Para[4], TMath::Abs(Para[4]*0.0) ,  Para[4], Para[4], ierflg);
//   gMinuit->mnparm(7,  "bg exp turnon", Para[5], TMath::Abs(Para[5]*0.1) ,  -0.7   , -0.3   , ierflg);
//   gMinuit->mnparm(8,  "bg x offset  ", Para[6], TMath::Abs(Para[6]*0.0) ,  -0.15  , -0.05  , ierflg);
//   gMinuit->mnparm(9,  "bg bend slope", Para[7], TMath::Abs(Para[7]*0.1) ,  0.01   , 0.05   , ierflg);
//   gMinuit->mnparm(10, "bg bend power", Para[8], TMath::Abs(Para[8]*0.1) ,  0.5    , 1.5    , ierflg);

  gMinuit->mnparm(2,  "constant"     , Para[0],  0.00,  Para[0], Para[0] , ierflg);
  gMinuit->mnparm(3,  "exp tail"     , Para[1],  0.00,  Para[1]-sigma*Para_err[1], Para[1]+sigma*Para_err[1], ierflg);
  gMinuit->mnparm(4,  "exg mean"     , Para[2],  0.00,  Para[2]-sigma*Para_err[2], Para[2]+sigma*Para_err[2], ierflg);
  gMinuit->mnparm(5,  "exg width"    , Para[3],  0.00,  Para[3]-sigma*Para_err[3], Para[3]+sigma*Para_err[3], ierflg);
  gMinuit->mnparm(6,  "constant"     , Para[4],  0.00,  Para[4]                  , Para[4]                  , ierflg);
  gMinuit->mnparm(7,  "bg exp turnon", Para[5],  0.00,  Para[5]-sigma*Para_err[5], Para[5]+sigma*Para_err[5], ierflg);
  gMinuit->mnparm(8,  "bg x offset  ", Para[6],  0.00,  Para[6]-sigma*Para_err[6], Para[6]+sigma*Para_err[6], ierflg);
  gMinuit->mnparm(9,  "bg bend slope", Para[7],  0.00,  0.001                    , 0.1                      , ierflg);
  gMinuit->mnparm(10, "bg bend power", Para[8],  0.00,  Para[8]-sigma*Para_err[8], Para[8]+sigma*Para_err[8], ierflg);
  
  printf(" --------------------------------------------------------- \n");
  printf(" Now ready for minimization step \n --------------------------------------------------------- \n");
  
  arglist[0] = 500; // number of iteration
  gMinuit->mnexcm("MIGRAD", arglist,1,ierflg);
  //can do scan
//   arglist[0] = 0;
//   gMinuit->mnexcm("SCAN", arglist,1,ierflg);

  printf (" -------------------------------------------- \n");
  printf("Finished.  ierr = %d \n", ierflg);

  double para[NPAR+1],errpara[NPAR+1];

  double tmp_errpara[NPAR+1];

  for(int j=0; j<=NPAR-1;j++) { tmp_errpara[j]=0.1; }
  for(int j=2; j<=NPAR-1;j++) { 
    if(Para_err[j-2]!=0.) tmp_errpara[j]=TMath::Abs(Para_err[j-2]); 
  }
  
  int ni=6;       if ( strcmp(EBEE,"EE")==0 ) { ni=6; }//if(ptbin==21) ni=0;}
  
  if ( ierflg == 0 ) {
    for(int i=0; i<ni; i++) {
      float istep[10] = {0.,0.,0.,0.,0.,0.,0.};
      if (i<(ni-1)) {
	istep[i] = 0.001;
      }else {
	for (int j=0; j<ni-1; j++) {istep[j] = 0.001;}
      }

      for(int j=0; j<=NPAR-1;j++) {
	gMinuit->GetParameter(j, para[j], errpara[j]);
	if (errpara[j] != 0. ) {
	  tmp_errpara[j] = TMath::Abs(errpara[j]);
	}
      }

      if ( strcmp(EBEE,"EB")==0 ) {

	sigma = 10.;

 	if ( i==(ni-1) ) { sigma=5.;istep[1]=istep[4]=0.; }
	if ( ptbin==21 && i==1 ){ sigma=3.; }
 	if ( ptbin==21 && i==(ni-1) ){ sigma=20.; }
	if ( ptbin==23 && i==0 ){ para[7]=-0.5; }
	if ( ptbin==23 && i==1 ){ istep[1]=0.; istep[3]=0.01; }
 	if ( ptbin==23 && i==3 ){ istep[1]=0.01; istep[3]=0.0; }
	if ( ptbin==23 && i==(ni-1) ){ sigma=20.; }
 	if ( ptbin==26 && i==1 ){ sigma=5.; }	
	if ( ptbin==26 && i==(ni-1) ){ sigma=20.; }
	if ( ptbin==30 && i==(ni-1) ){ sigma=3.; }
 	if ( ptbin==35 && i==(ni-1) ) { sigma=10.; }
 	if ( ptbin==40 && i==(ni-1) ) { sigma=5.; istep[4]=0.01; }
 	if ( ptbin==45 && i==(ni-1) ) { sigma=10.; }
	if ( ptbin==60 && i==0 ) { para[3]=1.; para[4]=0.6; para[5]=0.32; para[7]=-0.45; para[9]=0.025; para[10] = 1.;}
 	if ( ptbin==60 && i==(ni-1) ) { sigma=5.; istep[4]=0.01;}
	if ( ptbin>=85 && i==(ni-1) ){ sigma=3.; }
	if ( ptbin==300 ) { istep[2]=istep[3]=istep[4]=0.; }// para[7] = -5.11907e-02; istep[1]=0.; }
	float tmp8=0.;
	
// 	if( i!= (ni-1) ) {
	  gMinuit->mnparm(0,  "Signal yield"  ,   para[0],  1., para[0]-100.*tmp_errpara[0], para[0]+100.*tmp_errpara[0], ierflg);
	  gMinuit->mnparm(1,  "background yield", para[1],  1., para[1]-100.*tmp_errpara[1], para[1]+100.*tmp_errpara[1], ierflg);
	  gMinuit->mnparm(2,  "constant"     , para[2],  0., para[2]-100.*tmp_errpara[2], para[2]+100.*tmp_errpara[2], ierflg);
	  gMinuit->mnparm(6,  "constant"     , para[6],  0., para[6]-100.*tmp_errpara[6], para[6]+100.*tmp_errpara[6], ierflg);
	  gMinuit->mnparm(3,  "exp tail"     , para[3],  istep[4],  para[3]-sigma*tmp_errpara[3], para[3]+sigma*tmp_errpara[3], ierflg);
	  gMinuit->mnparm(4,  "exg mean"     , para[4],  istep[3],  para[4]-sigma*tmp_errpara[4], para[4]+sigma*tmp_errpara[4], ierflg);
	  gMinuit->mnparm(5,  "exg width"    , para[5],  istep[2],  para[5]-sigma*tmp_errpara[5], para[5]+sigma*tmp_errpara[5], ierflg);
	  gMinuit->mnparm(7,  "bg exp turnon", para[7],  istep[1],  para[7]-sigma*tmp_errpara[7], para[7]+sigma*tmp_errpara[7], ierflg);
	  gMinuit->mnparm(8,  "bg x offset  ", para[8],  tmp8    ,  para[8]-sigma*tmp_errpara[8], para[8]+sigma*tmp_errpara[8], ierflg);
	  gMinuit->mnparm(9,  "bg bend slope", para[9],  istep[0],  para[9]-sigma*tmp_errpara[9], para[9]+sigma*tmp_errpara[9], ierflg);      
	  float sigma10=5.;
	  if ( para[10]-sigma10*tmp_errpara[10] < 1. )// && i!=(ni-1))
	    gMinuit->mnparm(10, "bg bend power", para[10],  istep[0], 1.,  para[10]+sigma10*tmp_errpara[10], ierflg);      
	  else
	    gMinuit->mnparm(10, "bg bend power", para[10],  istep[0], para[10]-sigma10*tmp_errpara[10],  para[10]+sigma10*tmp_errpara[10], ierflg);      
// 	}else {
// 	  gMinuit->mnparm(2,  "constant"     , Para[0], TMath::Abs(Para[0]*0.0) ,  Para[0], Para[0], ierflg);
// 	  //gMinuit->mnparm(3,  "exp tail"     , Para[1], TMath::Abs(Para[1]*0.01) ,  Para[1]-sigma*Para_err[1], Para[1]+sigma*Para_err[1], ierflg); 
// 	  gMinuit->mnparm(3,  "exp tail"     , Para[1], TMath::Abs(Para[1]*0.0) ,  0.8    , 1.3    , ierflg);
// 	  gMinuit->mnparm(4,  "exg mean"     , Para[2], TMath::Abs(Para[2]*0.1) ,  0.5    , 1.0    , ierflg);
// 	  gMinuit->mnparm(5,  "exg width"    , Para[3], TMath::Abs(Para[3]*0.1) ,  0.25   , 0.5    , ierflg);
// 	  gMinuit->mnparm(6,  "constant"     , Para[4], TMath::Abs(Para[4]*0.0) ,  Para[4], Para[4], ierflg);
// 	  gMinuit->mnparm(7,  "bg exp turnon", Para[5], TMath::Abs(Para[5]*0.0) ,  -0.7   , -0.3   , ierflg);
// 	  gMinuit->mnparm(8,  "bg x offset  ", Para[6], TMath::Abs(Para[6]*0.0) ,  -0.15  , -0.05  , ierflg);
// 	  gMinuit->mnparm(9,  "bg bend slope", Para[7], TMath::Abs(Para[7]*0.1) ,  0.01   , 0.05   , ierflg);
// 	  gMinuit->mnparm(10, "bg bend power", Para[8], TMath::Abs(Para[8]*0.1) ,  0.5    , 1.5    , ierflg);
// 	}


	if( ptbin >=300 ) { 
	  gMinuit->mnparm(3,  "exp tail"  , 1.257281,  0.0,  para[1]-3.*tmp_errpara[1], para[1]+3.*tmp_errpara[1], ierflg);
	  gMinuit->mnparm(4,  "exg mean"  , 0.856906,  0.0,  para[2]-3.*tmp_errpara[2], para[2]+3.*tmp_errpara[2], ierflg);
	  gMinuit->mnparm(5,  "exg width" , 0.320847,  0.0,  para[3]-3.*tmp_errpara[3], para[3]+3.*tmp_errpara[3], ierflg);
	}      

    }else{	

	sigma=10.;
	if ( i==0 ) { para[10] = bkg_bend_power; tmp_errpara[10] = 0.3; }
 	if ( i==(ni-1) ) { sigma=3.;istep[1]=istep[4]=0.; } //test of not changing signal template
     	if ( i==(ni-1) ) { istep[4]=0.;}

   	if ( ptbin==21 && i==(ni-1) ) { sigma=20.;}
  	if ( ptbin==23 && i==0 ) { sigma=5.;}
  	if ( ptbin==23 && i==(ni-1) ) { sigma=10.;}
	if ( ptbin<30 && ptbin>21 && i==1 ){ istep[1]=0.; istep[3]=0.01; }
 	if ( ptbin<30 && ptbin>21 && i==3 ){ istep[1]=0.01; istep[3]=0.0; }
	if ( ptbin==26 && i==1 ) { para[7] = -0.8; }
	if ( ptbin==26 && i==(ni-1) ) { sigma=10.; }
  	if ( ptbin==30 && i==(ni-1) ) { sigma=10.; }
 	if ( ptbin==35) {para[7] = -0.75;}
 	if ( ptbin==40 && i==0) {para[7] = -0.65; para[10] = 2.;}
	if ( ptbin==45 && i==(ni-1) ) {sigma=5.;}
	if ( ptbin==85 && i==(ni-1) ) {sigma=10.; istep[4]=0.01;}
	if (ptbin >= 85 ) { para[10] = bkg_bend_power; tmp_errpara[10] = 1.; }

	if ( ptbin==120 ) { para[7] = -0.615255; istep[1]=0.;}

	
//     	if ( ptbin==120 && i==0 ) { 
// 	  para[3] = 1.446454; para[4]=-0.016373; para[5]=0.163238;
// 	  istep[2]=istep[3]=istep[4]=0.; sigma=5.; tmp_errpara[10]=0.2;
// 	}
//     	if ( ptbin==120 && i==(ni-1) ) { istep[2]=istep[3]=istep[4]=0.; sigma=5.;}

	gMinuit->mnparm(0,  "Signal yield"  ,   para[0],  1., para[0]-100.*tmp_errpara[0], para[0]+100.*tmp_errpara[0], ierflg);
	gMinuit->mnparm(1,  "background yield", para[1],  1., para[1]-100.*tmp_errpara[1], para[1]+100.*tmp_errpara[1], ierflg);
	gMinuit->mnparm(2,  "constant"     , para[2],  0.,  para[2], para[2] , ierflg);
	gMinuit->mnparm(6,  "constant"     , para[6],  0.,  para[6], para[6], ierflg);	
	gMinuit->mnparm(3,  "exp tail"     , para[3],  istep[4],  para[3]-sigma*tmp_errpara[3], para[3]+sigma*tmp_errpara[3], ierflg);
	gMinuit->mnparm(4,  "exg mean"     , para[4],  istep[3],  para[4]-sigma*tmp_errpara[4], para[4]+sigma*tmp_errpara[4], ierflg);
	gMinuit->mnparm(5,  "exg width"    , para[5],  istep[2],  para[5]-sigma*tmp_errpara[5], para[5]+sigma*tmp_errpara[5], ierflg);
	gMinuit->mnparm(7,  "bg exp turnon", para[7],  istep[1],  para[7]-sigma*tmp_errpara[7], para[7]+sigma*tmp_errpara[7], ierflg);
	gMinuit->mnparm(8,  "bg x offset  ", para[8],  0.00,      para[8]-sigma*tmp_errpara[8], para[8]+sigma*tmp_errpara[8], ierflg);
	gMinuit->mnparm(9,  "bg bend slope", para[9],  istep[0],  para[9]-sigma*tmp_errpara[9], para[9]+sigma*tmp_errpara[9], ierflg);	
  
	float minerr=1.;
	//if ( tmp_errpara[10] > 0.5) tmp_errpara[10] = 0.5;
	float sigma10=5.;
	if ( para[10]-sigma10*tmp_errpara[10] < 1. ) 
	  gMinuit->mnparm(10, "bg bend power", para[10],  istep[0], minerr,  para[10]+sigma10*tmp_errpara[10], ierflg);
	else 
	  gMinuit->mnparm(10, "bg bend power", para[10],  istep[0], para[10]-sigma10*tmp_errpara[10],  para[10]+sigma10*tmp_errpara[10], ierflg);

      }
      printf(" ************ \n");
      printf("  do %d th fit  \n", i);
      if(i==5 && dataFile.find("toy")    != std::string::npos)
	{
	  cout << "dataResult = " << dataResult << "\t dataErr = " << dataErr << endl;
	  // fixed turn on at +- 1 sigma
	  gMinuit->mnparm(7,  "bg exp turnon", dataResult-(float)shift*dataErr,  0.00,  para[7]-sigma*tmp_errpara[7], para[7]+sigma*tmp_errpara[7], ierflg);

	}
      else if(dataFile.find("toy")    == std::string::npos)
	{
	  dataResult = para[7];
	  dataErr    = tmp_errpara[7];
	}
      arglist[0] = 500; // number of iteration
      gMinuit->mnexcm("MIGRAD", arglist ,1,ierflg);      
      if ( ierflg != 0 ) {
  	printf("fit failed at %d iteration \n", i);
  	c1->cd();	c1->Draw();  	hdata->Draw("phe");
  	return fitted;
      }
    }
  }
 
  Double_t amin,edm,errdef; 
  if ( ierflg == 0 ) {
    for(int j=0; j<=NPAR-1;j++) {
      gMinuit->GetParameter(j, para[j],errpara[j]);
      info.push_back(para[j]);
      info_err.push_back(errpara[j]);
      printf("Parameter  %d = %f +- %f\n",j,para[j],errpara[j]);	
    }
    para[NPAR] = dataColl.size();
    printf(" fitted yield %2.3f \n", (para[0]+para[1])/ndata );
    
    info.push_back(sigColl.size());
    
    for(int j=0; j<=NPAR-1;j++) {
      tmp_errpara[j] = errpara[j];
      if( tmp_errpara[j] == 0. ) tmp_errpara[j] = par[j]*.1;      
    }
    //do minos if fit sucessed.

  }
  if (ierflg != 0 )  {
    printf(" *********** Fit failed! ************\n");
    gMinuit->GetParameter(0, para[0],errpara[0]);
    gMinuit->GetParameter(1, para[1],errpara[1]);
    para[0]=0.; errpara[0]=0.;

    c1->cd();
    c1->Draw();  
    //gPad->SetLogy();
    hdata->SetNdivisions(505,"XY");
    hdata->SetXTitle("comb. ISO (GeV)");
    hdata->SetYTitle("Entries");
    hdata->SetTitle("");
    hdata->SetMarkerStyle(8);
    hdata->SetMinimum(0.);
    if ( hdata->GetMaximum()<10.) hdata->SetMaximum(15.);
    else hdata->SetMaximum(hdata->GetMaximum()*1.25);
    if ( strcmp(EBEE,"EE")==0 &&ptbin == 15 ) hdata->SetMaximum(hdata->GetMaximum()*1.25);
   
    hdata->Draw("phe");  

    return fitted;    
  }

  
  // Print results
//   Double_t amin,edm,errdef;
  Int_t nvpar,nparx,icstat;
  gMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
  gMinuit->mnprin(1,amin);  
  gMinuit->mnmatu(1);
  printf(" ========= happy ending !? =========================== \n");
  
  printf("FCN =  %3.3f \n", amin);

  //use new PDF form
  double tmppar[12];
  for(int ii=0; ii<9; ii++){
    tmppar[ii] = para[ii+2];
    fmcsigfit->SetParameter(ii,tmppar[ii]);
    fbkgfit->SetParameter(ii,tmppar[ii]);
  }

  c101->cd(1);
  
  //fmcsigfit->SetParameters(tmppar);
  //fmcsigfit->SetParameter(2,0.1);
  //fmcsigfit->SetLineStyle(2);

  fmcsigfit->Draw("same");
  c101->cd(2);

  fbkgfit->SetParameter(4,fbkgfit->GetParameter(4)*fmcbkg->Integral(-1., 20.)/fbkgfit->Integral(-1., 20.));
  fbkgfit->Draw("same");

  char fname[100];
  sprintf(fname,"plots/template_Ifit%s_%d.pdf",EBEE,ptbin);
  c101->SaveAs(fname);


  f11->SetParameters(tmppar);
  SigPDFnorm = f11->Integral(-1., 20.);
  f12->SetParameters(tmppar);
  BkgPDFnorm = f12->Integral(-1., 20.);


  // plot
  c1->cd();
  c1->Draw();  
  //gPad->SetLogy();
   hdata->SetNdivisions(505,"XY");
   hdata->SetXTitle("comb. ISO (GeV)");
   hdata->SetYTitle("Entries");
   hdata->SetTitle("");
   hdata->SetMarkerStyle(8);
   hdata->SetMinimum(0.);
   if ( hdata->GetMaximum()<10.) hdata->SetMaximum(15.);
   else hdata->SetMaximum(hdata->GetMaximum()*1.5);
   if ( strcmp(EBEE,"EE")==0 &&ptbin == 15 ) hdata->SetMaximum(hdata->GetMaximum()*1.2);

   hdata->Draw("p e ");

  f11->SetParameter(0, para[0]*f11->GetParameter(0)/f11->Integral(-1., 20.)*hdata->GetBinWidth(2));
//   f11->SetFillColor(5);
  f11->SetLineColor(4);
  //f11->SetFillColor(603);
  f11->SetLineWidth(2);
//   f11->SetFillStyle(3001);
  f11->Draw("same");

  f12->SetParameter(4, para[1]*f12->GetParameter(4)/f12->Integral(-1., 20.)*hdata->GetBinWidth(2));
//   f12->SetFillColor(8);
  f12->SetLineColor(2);
  //f12->SetFillColor(603);
  f12->SetLineWidth(2);
//   f12->SetFillStyle(3013);
  f12->Draw("same");

  TF1 *f13 = new TF1("f13",sum_norm, -1., 20 ,11);
  f13->SetNpx(10000);
  f13->SetParameters(f12->GetParameters());
  f13->SetParameter(0, para[0]*f11->GetParameter(0)/f11->Integral(-1., 20.)*hdata->GetBinWidth(2));
  f13->SetParameter(4, para[1]*f12->GetParameter(4)/f12->Integral(-1., 20.)*hdata->GetBinWidth(2));  
  f13->SetLineWidth(2);
  f13->SetLineColor(1);
  f13->Draw("same");
  f11->Draw("same");
  hdata->Draw("pe same");

//   cout << "The number of bins are: " << endl;
//   cout << "hdata nbins = " << hdata->GetNbinsX() << endl;
//   cout << "hsig nbins = " << hsig->GetNbinsX() << endl;
//   cout << "hbkg nbins = " << hbkg->GetNbinsX() << endl;

  // get chi2/NDF
  double chi2ForThisBin=0;
  int nbinForThisBin=0;
  chi2Nbins(f13, hdata, chi2ForThisBin, nbinForThisBin);
  for(int epar=0; epar < 11; epar++)
    {
//       cout << "f11 parameter " << epar << " = " << 
// 	f11->GetParameter(epar) << endl;
      FitPar[epar] = f11->GetParameter(epar);
    }

  for(int epar=0; epar < 11; epar++)
    {
//       cout << "f12 parameter " << epar << " = " << 
// 	f12->GetParameter(epar) << endl;
      FitPar[epar+11] = f12->GetParameter(epar);
    }

  for(int epar=0; epar < 11; epar++)
    {
//       cout << "f13 parameter " << epar << " = " << 
// 	f13->GetParameter(epar) << endl;
      FitPar[epar+22] = f13->GetParameter(epar);

    }

//   cout << "hdata integral = " << hdata->Integral() << endl;
//   cout << endl;

//   printf("fit area %3.2f; sig area %3.2f; bg area %3.2f\n", f13->Integral(-1., 20.)/hdata->GetBinWidth(2),  f11->Integral(-1., 20.)/hdata->GetBinWidth(2),f12->Integral(-1., 20.)/hdata->GetBinWidth(2));

//   for(int i=0; i<12; i++){
//     printf(" fit para %d = %4.3f \n", i, f13->GetParameter(i));
//   }

   TLegend *tleg = new TLegend(0.5, 0.7, 0.93, 0.92);
   char text[50];
   sprintf(text,"%s Pt %d ~ %.0f GeV",EBEE, ptbin, ptmax);
   tleg->SetHeader(text);
   tleg->SetFillColor(0);
   tleg->SetShadowColor(0);
   tleg->SetBorderSize(0);
   sprintf(text,"#chi^{2}/NDF = %.1f/%d",chi2ForThisBin,nbinForThisBin);
   tleg->AddEntry(hdata,text,"");
   sprintf(text,"Data %.1f events",hdata->Integral());
   tleg->AddEntry(hdata,text,"pl");
   sprintf(text,"Fitted %.1f events",para[0]+para[1]);//f13->Integral(-1., 20.)/hdata->GetBinWidth(2));
   tleg->AddEntry(f13,text,"l");
   sprintf(text,"SIG %.1f #pm %.1f events",para[0], errpara[0]);
   tleg->AddEntry(f11,text,"f");
   sprintf(text,"BKG %.1f #pm %.1f events",para[1], errpara[1]);
   tleg->AddEntry(f12,text,"f");
   tleg->Draw();


   gPad->RedrawAxis();

   printf("%s, ptbin %d, Data %.1f events \n",EBEE, ptbin, hdata->Integral());
   printf("Fitted %.1f (in 5GeV) %.1f events \n",para[0]+para[1],f13->Integral(-1.,5.));
   printf("SIG %.1f #pm %.1f events \n",para[0], errpara[0]);
   printf("SIG (in 5GeV) %.1f #pm %.1f events \n",f11->Integral(-1.,5.)/hdata->GetBinWidth(2), f11->Integral(-1.,5.)*errpara[0]/para[0]/hdata->GetBinWidth(2));
   printf("BKG %.1f #pm %.1f events \n",para[1], errpara[1]);
   printf("BKG (in 5GeV) %.1f #pm %.1f events \n",f12->Integral(-1.,5.)/hdata->GetBinWidth(2), f12->Integral(-1.,5.)*errpara[1]/para[1]/hdata->GetBinWidth(2));
   
   float purity = f11->Integral(-1.,5.)/hdata->GetBinWidth(2)/(f11->Integral(-1.,5.)/hdata->GetBinWidth(2)+f12->Integral(-1.,5.)/hdata->GetBinWidth(2));
   float purity_err = purity*errpara[0]/para[0];
   printf("Purity (in 5GeV) %.3f #pm %.3f  \n", purity, purity_err);


//   hsig->Scale(para[0]/hsig->Integral());
//   hbkg->Scale(para[1]/hbkg->Integral());
//   hbkg->Add(hsig);

//   hsig->SetLineColor(1);
//   hsig->SetFillColor(5);
//   hsig->SetFillStyle(3001);

//   hbkg->SetLineWidth(2);


//   hsig->Draw("same");
//   hbkg->Draw("same");


  sprintf(fname,"plots/unbinned_free_Ifit%s_%d.pdf",EBEE,ptbin);
  if (para_index>0) sprintf(fname,"plots/unbinned_Ifit%s_%d_para%d_sigma%1.0f.pdf",EBEE,ptbin,para_index,para_sigma);
  if(Opt_SavePDF == 1) {
    c1->SaveAs(fname);


  } else {

   c1->Close();
   c10->Close();
   c101->Close();
   c11->Close();

  }

  printf("----- fit results with signal projection   ----------- \n");

  fitted[0] = para[0];
  fitted[1] = errpara[0];
  fitted[2] = para[1];
  fitted[3] = errpara[1];
  fitted[4] = f11->Integral(-1.,5.)/hdata->GetBinWidth(2);
  fitted[5] = f11->Integral(-1.,5.)*errpara[0]/para[0]/hdata->GetBinWidth(2);

  return fitted;
}
 //  fit with 2 components
void fit_chi2_err_two_components(TH1F* dataInput, TH1F* sigTemplate, TH1F* bkgTemplate1,/* TH1F* bkgTemplate2,*/ std::string prefix, 
                                Double_t& sigFrac, Double_t& sigFrac_intial , Double_t& sigFrac_err, 
                                /*Double_t& bkg1Frac, Double_t& bkg1Frac_intial , Double_t& bkg1Frac_err,*/ Double_t& FitChi2)

/*  fit with 3 components
void fit_chi2_err_manytimes(TH1F* dataInput, TH1F* sigTemplate, TH1F* bkgTemplate1, TH1F* bkgTemplate2, std::string prefix, 
			    	Double_t& sigFrac, Double_t& sigFrac_intial , Double_t& sigFrac_err, 
			    	Double_t& bkg1Frac, Double_t& bkg1Frac_intial , Double_t& bkg1Frac_err, Double_t& FitChi2)
*/

//void fit_chi2_err(TH1F* dataInput, TH1F* sigTemplate, TH1F* bkgTemplate, Double_t& sigFrac, Double_t& sigFrac_err)
//void fit_chi2_err(TH1F* dataInput, TH1F* sigTemplate, TH1F* bkgTemplate, Double_t& sigFrac, Double_t& sigFrac_err, Double_t& FitChi2)
{
  gStyle->SetOptStat(kFALSE);
  gStyle->SetCanvasColor(0);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetPadBorderMode(0);
  gStyle->SetFrameBorderMode(0);

  Double_t scale=1.;




  data = (TH1D*)dataInput->Clone();
  data->SetName("data");
  data->SetLineColor(1);
  data->SetMarkerColor(1);
  data->SetXTitle("SigmaIetaIeta");
  data->Sumw2();
//  scale = 1.0/(Double_t)data->Integral(0,1000); 
  scale = 1.0/(Double_t)data->Integral();
//  scale = 1.0/(Double_t)data->Integral();//changed by Yu-hsiang
  //cout << "scale for data = " << scale << endl;
  data->Scale(scale);


  fit_result = (TH1D*)dataInput->Clone();
  fit_result->SetName("fit_result");
  fit_result->SetLineColor(8); 
  fit_result->SetMarkerColor(8);
  fit_result->SetLineStyle(2);
  fit_result->Sumw2();
  fit_result->Reset();


  signal_pos = (TH1D*)sigTemplate->Clone();
  signal_pos->SetName("signal_pos");
  signal_pos->SetLineColor(2);
  signal_pos->SetMarkerColor(2);
  signal_pos->SetFillColor(2);
  signal_pos->SetXTitle("SigmaIetaIeta");
  signal_pos->Sumw2();
//  scale = 1.0/(Double_t)signal_pos->Integral(0,1000); 
  scale = 1.0/(Double_t)signal_pos->Integral();
//  scale = 1.0/(Double_t)signal_pos->Integral();//changed by Yu-hsiang
  //cout << "scale for signal template = " << scale << endl;
  signal_pos->Scale(scale);


  background_pos1 = (TH1D*)bkgTemplate1->Clone();
  background_pos1->SetName("background_pos1");
  background_pos1->SetLineColor(4);
  background_pos1->SetMarkerColor(4);
  background_pos1->SetFillColor(4);
  background_pos1->SetXTitle("SigmaIetaIeta");
  background_pos1->Sumw2();
//  scale = 1.0/(Double_t)background_pos->Integral(0,1000); 
  scale = 1.0/(Double_t)background_pos1->Integral();
//  scale = 1.0/(Double_t)background_pos->Integral();//changed by Yu-hsiang
  //cout << "scale for background template = " << scale << endl;
  background_pos1->Scale(scale);

/*
  background_pos2 = (TH1D*)bkgTemplate2->Clone();
  background_pos2->SetName("background_pos2");
  background_pos2->SetLineColor(7);
  background_pos2->SetMarkerColor(7);
  background_pos2->SetFillColor(7);
  background_pos2->SetXTitle("SigmaIetaIeta");
  background_pos2->Sumw2();
  scale = 1.0/(Double_t)background_pos2->Integral();
  //cout << "scale for background template = " << scale << endl;
  background_pos2->Scale(scale);
*/

//////////  count the number of points and the dof   



  int Number_of_points =0 ;

//  for (int i=1;i<2000;i++){ //the Sig or Bkg histo has 2000 bins
   for (int i=1;i<= sigTemplate->GetNbinsX();i++){ 
    if(/* ( ( bkgTemplate2->GetBinContent(i) ) != 0) ||*/ ( ( bkgTemplate1->GetBinContent(i) ) != 0) || ( ( sigTemplate->GetBinContent(i) ) != 0 ) ){
    Number_of_points = Number_of_points+1;

    }
  }
//cout<<"Number_of_points:"<<Number_of_points<<endl;
int dof = Number_of_points-1 ;//dof=Number_of_points - free_par
                              //and in this case we normalize it so free_par =1
//cout<<"dof of this fit:"<<dof<<endl;



/////////


  TMinuit *gMinuit = new TMinuit(1); // initialize TMinuit with a maximum of 1 params
//  TMinuit *gMinuit = new TMinuit(2);  //initialize TMinuit with a maximum of 5 (1param??) params
  gMinuit->SetFCN(fcn); // sets function to minimize: fcn is Chi2 with errors on templates

  Double_t arglist[10];
  Int_t ierflg = 0; // status flag, it is 0 when ereything goes fine

  // -- sets error
  arglist[0] = 1;
  gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);

  // set first parameter
  Double_t vstart = sigFrac_intial;
  //Double_t vstart = 0.48 ;//0.11;//intial value
  Double_t step = 0.001;
  gMinuit->mnparm(0, "fsig", vstart, step, 0,1,ierflg);

/*
  // set second parameter
    vstart = bkg1Frac_intial;
//    vstart = 0.4; //0.69;//intial value
    step = 0.001;
  gMinuit->mnparm(1, "fbk1", vstart, step, 0,1,ierflg);
*/

  // Now ready for minimization step
  arglist[0] = 1000;
  arglist[1] = 0.01;
  gMinuit->mnexcm("MIGRAD", arglist ,2,ierflg);

  Double_t fsig=0;
  Double_t fsigerr=0;
  Double_t fbk1=0;
//  Double_t fbk1err=0;
  Double_t chi2 = 0;


  if ( ierflg == 0 ) 
    {

      // Print results
      Double_t amin,edm,errdef;
      Int_t nvpar,nparx,icstat;
      gMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
      gMinuit->mnprin(3,amin);
      chi2 = (gMinuit->fAmin)/dof;
      gMinuit->GetParameter(0, fsig, fsigerr );  

//      gMinuit->GetParameter(1, fbk1, fbk1err );
      //cout << "Fsig = " << fsig << " +- " << fsigerr << endl;
      //cout << "Fbk1 = " << fbk1 << " +- " << fbk1err << endl;
      //cout << "Chi2/degree of freedom = " << chi2 <<endl;
	fbk1 = 1 - fsig ; 
//      TCanvas* c1 = new TCanvas("c1","",500,500);

  TH2F *htmp2 = new TH2F("htmp2","",100, 0., 0.025, 100, 0., data->GetMaximum()*1.25);

  htmp2->SetNdivisions(505,"XY");
  htmp2->SetXTitle("SigmaIetaIeta");
  htmp2->SetYTitle("A.U.");
  htmp2->SetLineColor(1); 

//     htmp2->Draw();


  TH1D* signal_display = (TH1D*)signal_pos->Clone();
  signal_display->SetName("signal_display");
  Double_t scale_sig = signal_display->Integral();
  signal_display->Scale(fsig/scale_sig);
  signal_display->SetFillStyle(3001);

      
  TH1D* background_display1 = (TH1D*)background_pos1->Clone();
  background_display1->SetName("background_display1");
  Double_t scale_background1 = background_display1->Integral();
  background_display1->Scale(fbk1/scale_background1);
  background_display1->SetFillStyle(3001);

/*
  TH1D* background_display2 = (TH1D*)background_pos2->Clone();
  background_display2->SetName("background_display2");
  Double_t scale_background2 = background_display2->Integral();
  background_display2->Scale((1-fsig-fbk1)/scale_background2);
  background_display2->SetFillStyle(3001);
*/

  fit_result->GetXaxis()->SetRangeUser(100,600);
  fit_result->GetYaxis()->SetRangeUser(0.,0.2);
  fit_result->SetXTitle("mass of hadronic top");
//  fit_result->SetXTitle("#sigma_{i#eta i#eta}");
  fit_result->SetTitleSize(0.04,"X");
  fit_result->GetXaxis()->SetLabelSize(0.04);

  //fit_result->Draw("histe");
  //data->Draw("esame");
  //signal_display->Draw("histsame");
  //background_display1->Draw("histsame");
  //background_display2->Draw("histsame");

  char result[300];
  sprintf(result,"fsig = %.3lf #pm %.3lf",fsig,fsigerr );
  sigFrac = fsig;
  sigFrac_err = fsigerr ;
//  bkg1Frac =fbk1;
//  bkg1Frac_err =fbk1err;

  FitChi2 = chi2;

  TLegend* leg = new TLegend(0.9,0.6,0.6,0.9);
  leg->SetHeader(result);
  leg->SetFillColor(0);
  leg->SetFillStyle(0);
  leg->SetTextSize(0.035);
  leg->SetBorderSize(0);
  leg->AddEntry(data,"data");
  leg->AddEntry(fit_result,"fit");
  leg->AddEntry(signal_display,"signal template");
  leg->AddEntry(background_display1,"background template1");
//  leg->AddEntry(background_display2,"background template2");
  //leg->Draw("same");


      std::string outputFile = "plots_of_fit_results/"+  prefix + ".eps";
      //c1->Print(outputFile.data());

//      outputFile = prefix + ".gif";
      outputFile = "plots_of_fit_results/"+  prefix + ".gif";
      //c1->Print(outputFile.data());

      outputFile = "plots_of_fit_results/"+ prefix + ".C";
      //c1->Print(outputFile.data());

      outputFile = "plots_of_fit_results/"+ prefix + ".pdf";
      //c1->Print(outputFile.data());

    }

    
  else{
    //cout << "Fit failed!\n";
    sigFrac = 0;
    sigFrac_err = 0;
  }

  
  return;

}
Ejemplo n.º 29
0
std::vector<double> run_fit(double parOOR, double parOEFG, double parOFTMR,
                            double parOTO, double parSRS) {
    TMinuit minuit;
    double arglist[10];
    int iflag;
    arglist[0] = -1;
    minuit.mnexcm("SET PRINT",arglist,1,iflag);
    minuit.mnexcm("SET NOW",arglist,0,iflag);
    minuit.SetFCN(fcn);
    arglist[0] = 2;
    minuit.mnexcm("SET STR",arglist,1,iflag);
    minuit.mnparm(0,"parOOR",parOOR,0.1,0,0,iflag);//or
    minuit.mnparm(1,"parEFG",parOEFG,0.1,0,0,iflag);//efgp
    minuit.mnparm(2,"parFTMR",parOFTMR,0.1,0,0,iflag);//ftr
    minuit.mnparm(3,"parTO",parOTO,0.1,0,0,iflag);//top
    minuit.mnparm(4,"parSRS",parSRS,0.1,0,0,iflag);//srs

    if (parSRS == 0)
        minuit.FixParameter(4);

    arglist[0] = 10000;
    arglist[1] = 0.0001;
    minuit.mnexcm("MIGRAD",arglist,2,iflag);
    minuit.mnexcm("HESSE",arglist,0,iflag);

    double fmin, fedm,errdef;
    int npari, nparx, istat;
    minuit.mnstat(fmin,fedm,errdef,npari,nparx,istat);

    double val,err;
    std::vector<double> ret_ary;
    for(int p = 0; p < 5; p++) {
        minuit.GetParameter(p, val, err);
        ret_ary.push_back(val);
    }
    ret_ary.push_back(fmin);

    return ret_ary;
}
Ejemplo n.º 30
0
void testZeeMCSmearWithScale(string datareco = "jan16 or nov30",int phtcorr = 231, int test_fitdet= 1, string test_smearmethod = "corrSmear or uncorrSmear",string test_fitmethod = "lh or lhpoisson",int fixscale = 0,int fitstra = 1, int testpaircat=0, double test_fitlow = 70, double test_fithigh = 110, double test_binwidth = 1.0){
  
  
  

  int phtcorr_test =  phtcorr; 
  if( phtcorr_test == 486){
    phtcorr = 485;
  }


  fitdet = test_fitdet; 
  
  smearMethod = test_smearmethod ;
  
  testOnlyCat = testpaircat; 
  
  fitrangeLow = test_fitlow; 
  fitrangeHigh = test_fithigh; 
  binwidth = test_binwidth;
  
  
  fitmethod = test_fitmethod; 
  
  
  gStyle->SetOptStat(0);
  gStyle->SetNdivisions(508,"X");
  gStyle->SetNdivisions(512,"Y");
    
  
  int mc = 1; 

  fillMapIndex();
  

  TString filename; 
  
  
    
  fChainMC = new TChain("Analysis");
  fChainData = new TChain("Analysis");
  
  
  
  string dataset; 
  int iflag = 2; 
  if( datareco == "nov30"){
    iflag = 1; 
    dataset = "DoubleElectronRun2011AB30Nov2011v1AOD";
  }else if( datareco == "jan16"){
    iflag = 2; 
    dataset = "DoubleElectronRun2011AB16Jan2012v1AOD"; 
  }else{
    cout<<"dataset ? " << datareco.c_str()<<endl; 
    return; 
  }
  

  ///MC

  filename = TString(Form("/home/raid2/yangyong/data/CMSSW/v1/CMSSW_4_2_8/src/zSelector/dielectrontree/makeDiElectronTree.v3.DYJetsToLL_TuneZ2_M50_7TeVmadgraphtauolaFall11PU_S6_START42_V14Bv1AODSIMallstat.etcut20.corr%d.eleid1.datapu6.mcpu1.r1to92.scale0.root",phtcorr));
  
  cout<<filename<<endl; 
  fChainMC->Add(filename);
  
  //fChainMC->SetBranchAddress("isRealData", &isRealData);
  fChainMC->SetBranchAddress("elescr9", elescr9);
  fChainMC->SetBranchAddress("elesceta", elesceta);
  fChainMC->SetBranchAddress("eleen", eleen);
  
  //fChainMC->SetBranchAddress("eleen0", eleen0);
  fChainMC->SetBranchAddress("mpair", &mpair);
//   fChainMC->SetBranchAddress("mpair0", &mpair0);
  fChainMC->SetBranchAddress("eleeta", eleeta);
   fChainMC->SetBranchAddress("eleieta", eleieta);
  fChainMC->SetBranchAddress("eleiphi", eleiphi);
   fChainMC->SetBranchAddress("runNumber", &runNumber);
   fChainMC->SetBranchAddress("evtNumber", &evtNumber);
   fChainMC->SetBranchAddress("lumiBlock", &lumiBlock);
  fChainMC->SetBranchAddress("eleetrue", eleetrue);
//   fChainMC->SetBranchAddress("eleetruenofsr", eleetruenofsr);
//   fChainMC->SetBranchAddress("eleetrueplusfsrdrbc003", eleetrueplusfsrdrbc003);
//   fChainMC->SetBranchAddress("eleetrueplusfsrdrbc004", eleetrueplusfsrdrbc004);
   fChainMC->SetBranchAddress("eleetrueplusfsrdrbc005", eleetrueplusfsrdrbc005);
//   fChainMC->SetBranchAddress("eleetrueplusfsrdrbc006", eleetrueplusfsrdrbc006);
//   fChainMC->SetBranchAddress("eleetrueplusfsrdrbc007", eleetrueplusfsrdrbc007);
//   fChainMC->SetBranchAddress("eleetrueplusfsrdrbc008", eleetrueplusfsrdrbc008);
//   fChainMC->SetBranchAddress("eleetrueplusfsrdrbc009", eleetrueplusfsrdrbc009);
   fChainMC->SetBranchAddress("eleetrueplusfsrdrbc01", eleetrueplusfsrdrbc01);
//   fChainMC->SetBranchAddress("eletrueelematched", eletrueelematched);
//   fChainMC->SetBranchAddress("eletrueelematchednofsr", eletrueelematchednofsr);
   fChainMC->SetBranchAddress("weight", &weight);
   
  //Data
   filename = TString(Form("/home/raid2/yangyong/data/CMSSW/v1/CMSSW_4_2_8/src/zSelector/dielectrontree/makeDiElectronTree.v3.%s.etcut20.corr%d.eleid1.datapu0.mcpu0.r1to131.scale0.root",dataset.c_str(),phtcorr));
   
   cout<<filename<<endl; 
  fChainData->Add(filename);
  
  
  fChainData->SetBranchAddress("isRealData", &isRealData);
  fChainData->SetBranchAddress("elescr9", elescr9);
  fChainData->SetBranchAddress("elesceta", elesceta);
  fChainData->SetBranchAddress("eleen", eleen);
  fChainData->SetBranchAddress("eleen0", eleen0);
  fChainData->SetBranchAddress("mpair", &mpair);
  fChainData->SetBranchAddress("mpair0", &mpair0);
  fChainData->SetBranchAddress("eleeta", eleeta);
  fChainData->SetBranchAddress("eleieta", eleieta);
  fChainData->SetBranchAddress("eleiphi", eleiphi);
  fChainData->SetBranchAddress("runNumber", &runNumber);
  fChainData->SetBranchAddress("evtNumber", &evtNumber);
  fChainData->SetBranchAddress("lumiBlock", &lumiBlock);
  
  
  NMC = fChainMC->GetEntries();
  NData = fChainData->GetEntries();
  cout<<"nMC " << NMC <<" "<< NData <<endl; 
    
  
  filename = TString(Form("testZeeMCSmearWithScale.%s.%s.%s.testpair%d.fitrange%dto%d.binwidth%2.2f.fitdet%d.corr%d.fitstra%d.fixscale%d.etcut%d.root",datareco.c_str(),test_smearmethod.c_str(),test_fitmethod.c_str(),testpaircat,int(fitrangeLow+0.1),int(fitrangeHigh+0.1),binwidth,fitdet,phtcorr_test,fitstra,fixscale,etcut));
  TFile *fnew = new TFile(filename,"recreate");
  
  //filename = TString(Form("testZeeMCSmearWithScale.%s.%s.%s.testpair%d.fitrange%dto%d.binwidth%2.2f.fitdet%d.corr%d.fitstra%d.fixscale%d.etcut%d.txt",datareco.c_str(),test_smearmethod.c_str(),test_fitmethod.c_str(),testpaircat,int(fitrangeLow+0.1),int(fitrangeHigh+0.1),binwidth,fitdet,phtcorr,fitstra,fixscale,etcut));
  //txtout.open(filename,ios::out);
  

  TTree *mytree = new TTree("Analysis","");
  
  float mcfitpar[8] = {0};
  float mcfitparErr[8] = {0};
  int mcfitStatus;
  float fAmin;
  mytree->Branch("mcfitpar",mcfitpar,"mcfitpar[8]/F");
  mytree->Branch("mcfitparErr",mcfitparErr,"mcfitparErr[8]/F");
  mytree->Branch("mcfitStatus",&mcfitStatus,"mcfitStatus/I");
  mytree->Branch("fAmin",&fAmin,"fAmin/F");
  
  rv_mass = new RooRealVar("rv_mass","mass",100,0,1E6);
  rv_weight = new RooRealVar("rv_weight","weight",1.0,0,1E6);
  
  for(int j=0;j<20;j++){
    string sname = string(Form("mpairmc_indscpair%d",j));
    makeRootDataSetAndTH1F(sname,int( (fitrangeHigh-fitrangeLow)/binwidth+0.1),fitrangeLow,fitrangeHigh);
    sname = string(Form("mpairdata_indscpair%d",j));
    makeRootDataSetAndTH1F(sname,int( (fitrangeHigh-fitrangeLow)/binwidth+0.1),fitrangeLow,fitrangeHigh);
  }
  
  int sc1cat; 
  int sc2cat; 
  
  
  cout<<" nMC " <<NMC <<endl; 
  for(int n=0; n< NMC; n++){
    fChainMC->GetEntry(n);
    if(phtcorr==94){
      if(evtNumber%2==0) continue;
    }
    
    ///same as 485, for test purpose only
    if(phtcorr_test==486){
      if(evtNumber%2==0) continue;
    }
    
    

    if(n%500000==0) cout<<"n " << n <<endl;
    
    if(fitdet==1){
      if( fabs(elesceta[0])>1.48 || fabs(elesceta[1])>1.48) continue; 
    }else if( fitdet==2){
      if( fabs(elesceta[0])<1.48 || fabs(elesceta[1])<1.48) continue; 
    }
    
    
    ///scale r9 in MC
    for(int j=0; j<2; j++){
      if(fabs(elesceta[j])<1.48) elescr9[j] *= 1.004;
      else elescr9[j] *= 1.006;
    }
    
    
    ///get pair index
    sc1cat = scCategoryEight(elesceta[0],elescr9[0]);
    sc2cat = scCategoryEight(elesceta[1],elescr9[1]);
    if(sc2cat < sc1cat){
      exChangeTwoNumber(sc1cat,sc2cat);
    }
    int indpair; 
    if(fitdet==1){
      indpair = map_indscpairBarrel[sc1cat][sc2cat]; 
    }else{
      indpair = map_indscpairEndcap[sc1cat][sc2cat]; 
    }
    
    
    //test one category
    if(testOnlyCat >=0 && indpair != testOnlyCat) continue;
    float e1true;
    if( fabs(elesceta[0])<1.48){
      e1true = eleetrueplusfsrdrbc005[0];
    }else{
      e1true = eleetrueplusfsrdrbc01[0];
    }
    float e2true;
    if( fabs(elesceta[1])<1.48){
      e2true = eleetrueplusfsrdrbc005[1];
    }else{
      e2true = eleetrueplusfsrdrbc01[1];
    }
    if(e1true <1 || e2true<1) continue; 
    
    vindpair.push_back(indpair);
    sc1cat = scCategoryEight(elesceta[0],elescr9[0]);
    sc2cat = scCategoryEight(elesceta[1],elescr9[1]);

    
    if(fitdet==2){ //Endcap, starting with 4,5,6,7
      sc1cat -=4; 
      sc2cat -=4; 
    }
    
    vsc1cat.push_back(sc1cat);
    vsc2cat.push_back(sc2cat);
    vele1eta.push_back(eleeta[0]);
    vele1ieta.push_back(eleieta[0]);
    vele1iphi.push_back(eleiphi[0]);
    vele2eta.push_back(eleeta[1]);
    vele2ieta.push_back(eleieta[1]);
    vele2iphi.push_back(eleiphi[1]);
    vele1en.push_back(eleen[0]);
    vele2en.push_back(eleen[1]);
    vmpair.push_back(mpair);
    vweight.push_back(weight);
    
    
    vele1etrue.push_back(e1true);
    vele2etrue.push_back(e2true);
    
    
    if( eleen[0]* sin(2*atan(exp(-eleeta[0]))) < etcut) continue; 
    if( eleen[1]* sin(2*atan(exp(-eleeta[1]))) < etcut) continue; 
    
    string sname = string(Form("mpairmc_indscpair%d",indpair));
    fillRootDataSetAndTH1F(sname,mpair,weight);
    
  }
  
  
  setMap_cat_runbin();
  loadRunbyRunScaleCorrectionNoR9(iflag,phtcorr);
  loadScaleCorrectionR9(iflag,phtcorr);
  
  
  for(int n=0; n< NData; n++){
    fChainData->GetEntry(n);
    if(n%500000==0) cout<<"n " << n <<endl;

    if(fitdet==1){
      if( fabs(elesceta[0])>1.48 || fabs(elesceta[1])>1.48) continue; 
    }else if( fitdet==2){
      if( fabs(elesceta[0])<1.48 || fabs(elesceta[1])<1.48) continue; 
    }
    
    float scorr = 1.0; 
    for(int j=0; j<2; j++){
      float dEoE = energyScaleRunNoR9(elesceta[j]);
      float dEoE1 = energyScaleR9(elesceta[j],elescr9[j]);
      eleen[j] *= 1.0/(1+dEoE) * 1.0/(1+dEoE1);
      scorr *= 1.0/(1+dEoE) * 1.0/(1+dEoE1);
    }
    mpair *= sqrt(scorr);
    if( eleen[0]*sin(2*atan(exp(-eleeta[0]))) < etcut) continue; 
    if( eleen[1]*sin(2*atan(exp(-eleeta[1]))) < etcut) continue; 
    
    sc1cat = scCategoryEight(elesceta[0],elescr9[0]);
    sc2cat = scCategoryEight(elesceta[1],elescr9[1]);
    if(sc2cat < sc1cat){
      exChangeTwoNumber(sc1cat,sc2cat);
    }
    int indpair; 
    if(fitdet==1){
      indpair = map_indscpairBarrel[sc1cat][sc2cat]; 
    }else{
      indpair = map_indscpairEndcap[sc1cat][sc2cat]; 
    }
    
    
    string sname = string(Form("mpairdata_indscpair%d",indpair));
    fillRootDataSetAndTH1F(sname,mpair,1);
  }
  
  
  for(int j=0;j<10;j++){
    string sname = string(Form("mpairmc_indscpair%d",j));
    string snamed = string(Form("mpairdata_indscpair%d",j));
    cout<<"mpair catpair "     <<  th1f_map[sname]->GetEntries()<<" "<<  th1f_map[snamed]->GetEntries()<<endl; 
  }
  
  generateGaussRandom();
  
  //return; 

  TMinuit *minuit; 
  int npar = 8; 
  minuit  = new TMinuit(npar); 
  
  //minuit->SetFCN(function);
  //minuit->SetFCN(function1);
  minuit->SetFCN(function2);
  
  
  //settings
  Double_t arglist[1];
  Int_t ierflg = 0;
  //double STEPMN = 0.01;
  double STEPMN = 0.0001;
  
  // 1 for Chi square
  // 0.5 for negative log likelihood
  if(fitmethod== "lh" || fitmethod == "lhpoisson"){
    minuit->SetErrorDef(0.5);
  }else{
    minuit->SetErrorDef(1);
  }
    double fitpar[10];
    double fitparErr[10];
    
  double smearcat[4] = {1.1,1.1,1.1,1.1};
  double smearcatMax[4] = {3,3,3,3};

  double deltaEcat[4] = {0,0,0,0};
  
  
  if(smearMethod=="uncorrSmear"){
    smearcatMax[0] = 0.05;
    smearcatMax[1] = 0.05;
    smearcatMax[2] = 0.05;
    smearcatMax[3] = 0.05;

    smearcat[0] = 0.007;
    smearcat[1] = 0.01;
    smearcat[2] = 0.015;
    smearcat[3] = 0.02;
    
    if(fitdet==2){
      smearcat[0] = 0.02;
      smearcat[1] = 0.02;
      smearcat[2] = 0.02;
      smearcat[3] = 0.02;
    }
    
  }
  

  for(int j=0; j<4; j++){
    TString parname = TString (Form("smearcat%d",j));
    if(smearMethod=="corrSmear"){
      minuit->mnparm(j, parname, smearcat[j], STEPMN, 0.5,smearcatMax[j],ierflg);
    }else  if(smearMethod=="uncorrSmear"){
      minuit->mnparm(j, parname, smearcat[j], STEPMN, 0,smearcatMax[j],ierflg);
    }

    fitpar[j] = smearcat[j]; //initialized values
  }
  
  for(int j=4; j<npar; j++){
    TString parname = TString (Form("scalecat%d",j-4));
    minuit->mnparm(j, parname, deltaEcat[j-4], STEPMN, -0.03,0.03,ierflg);
    fitpar[j] = deltaEcat[j-4]; //initialized values
  }
  

  if(fixscale==1){
    for(int j=4; j<npar; j++){
      minuit->FixParameter(j);
    }
  }
  


  if(testpaircat==1){
    minuit->FixParameter(0);
    minuit->FixParameter(2);
    minuit->FixParameter(3);

    minuit->FixParameter(4);
    minuit->FixParameter(6);
    minuit->FixParameter(7);

  }else if( testpaircat==0){
    minuit->FixParameter(1);
    minuit->FixParameter(2);
    minuit->FixParameter(3);

    minuit->FixParameter(5);
    minuit->FixParameter(6);
    minuit->FixParameter(7);

  } else if( testpaircat==2){
    minuit->FixParameter(0);
    minuit->FixParameter(1);
    minuit->FixParameter(3);

    minuit->FixParameter(4);
    minuit->FixParameter(5);
    minuit->FixParameter(7);

  } else if( testpaircat==3){
    minuit->FixParameter(0);
    minuit->FixParameter(1);
    minuit->FixParameter(2);

    minuit->FixParameter(4);
    minuit->FixParameter(5);
    minuit->FixParameter(6);
    
  }  
  
  arglist[0] = 0.0001;
  minuit->mnexcm("SET EPS",arglist,1,ierflg);
  
  //minuit->mnsimp();
  ////arglist[0] = 1; 
  ///minuit->mnexcm("SET STR",arglist,1,ierflg);
  //minuit->mnexcm("MIGRAD", arglist ,1,ierflg);
  
  arglist[0] = fitstra; 
  minuit->mnexcm("SET STR",arglist,1,ierflg);

  bool dofit = true; 
  
  if( dofit){
    minuit->Migrad();
    if (!minuit->fCstatu.Contains("CONVERGED")) {
      mcfitStatus = 1; //first try not converged.
      minuit->Migrad();
    }else{
      mcfitStatus = 0;
      
    }
  }
    
  double ftest[1000]; 

  double atest[1000];
  
  //minuit->GetParameter(0,fitpar[0],fitparErr[0]);

  if (!minuit->fCstatu.Contains("CONVERGED")) {
    printf("No convergence at fitting, routine Fit \n");
    printf("Minuit return string: %s \n",minuit->fCstatu.Data());
    mcfitStatus = 2;  //2nd try not converged.
  }else{
    mcfitStatus = -1;
  }
  fAmin = minuit->fAmin;

  for(int j=0; j<npar; j++){
    minuit->GetParameter(j,fitpar[j],fitparErr[j]);
    mcfitpar[j] = fitpar[j];
    mcfitparErr[j] = fitparErr[j];
  }
  
  
  double par[10];
  
  for(int j=0;j<npar;j++){
    par[j] = fitpar[j];
  }
  
  
  bool printScan = false; 
  //bool printScan = true; 
  par[0] = 0.0076; 
  
  if(printScan && testpaircat>=0){
    double  fmin = function2(par,true);
    
    
    float x1 = fitpar[testpaircat] - 0.1;
    float x2 = fitpar[testpaircat] + 0.1;
    float teststep = 0.01;
    if(smearMethod=="uncorrSmear"){
      x1 =  fitpar[testpaircat] - 0.005 >0 ? fitpar[testpaircat] - 0.005: 0;
      x2 =  fitpar[testpaircat] +0.005;
      teststep = 0.001;
    }
    
    double dmin1 = 1;
    double dmin2 = 1;
    double fitparErrLow[10];
    double fitparErrHigh[10];
  
    int ntest = 0; 
    for(float x = x1; x <= x2; x += teststep){
      
      cout<<"x " << x <<endl; 
      
      
      par[testpaircat]  = x ;
    
      //double  f = function2(par,false);
      double  f = function2(par,true);
    
      if(fabs(f-fmin-1)< dmin1 && x < fitpar[testpaircat]){
	dmin1 = fabs(f-fmin-0.5);
	fitparErrLow[testpaircat] = fitpar[testpaircat] -x;
      }
      if(fabs(f-fmin-1)< dmin2 && x > fitpar[testpaircat]){
	dmin2 = fabs(f-fmin-0.5);
	fitparErrHigh[testpaircat] = x-fitpar[testpaircat];
      }
      atest[ntest] = x; 
      ftest[ntest] = f; 
      ntest ++; 
    }
    
    cout<<"fitpar[testpaircat]" << fitpar[testpaircat]<<" +/- "<<fitparErr[testpaircat]<<" - "<< fitparErrLow[testpaircat]<<" + "<< fitparErrHigh[testpaircat]<<endl; 
  
    TCanvas *can0 = new TCanvas("can0","c000",200,10,550,500);
    setTCanvasNice(can0);
    TGraph *gr = new TGraph(ntest,atest,ftest);
    gr->Draw("ap");
    //TF1 *ff = new TF1("ff","[0]+[1]*x+[2]*x*x",0,0.0);
    //gr->Fit(ff,"r");
  
    can0->Print("testconverge1.pdf");
    can0->Print("testconverge1.C");
    
  }
  
  mytree->Fill();
  mytree->Write();
  fnew->Write();
  fnew->Close();


}