Exemplo n.º 1
0
//____________________________________________________________________
void fitCircle(Int_t n=10000) {
   //generates n points around a circle and fit them
   TCanvas *c1 = new TCanvas("c1","c1",600,600);
   c1->SetGrid();
   gr = new TGraph(n);
   if (n> 999) gr->SetMarkerStyle(1);
   else        gr->SetMarkerStyle(3);
   TRandom3 r;
   Double_t x,y;
   for (Int_t i=0;i<n;i++) {
      r.Circle(x,y,r.Gaus(4,0.3));
      gr->SetPoint(i,x,y);
   }
   c1->DrawFrame(-5,-5,5,5);
   gr->Draw("p");

   //Fit a circle to the graph points
   TVirtualFitter::SetDefaultFitter("Minuit");  //default is Minuit
   TVirtualFitter *fitter = TVirtualFitter::Fitter(0, 3);
   fitter->SetFCN(myfcn);

   fitter->SetParameter(0, "x0",   0, 0.1, 0,0);
   fitter->SetParameter(1, "y0",   0, 0.1, 0,0);
   fitter->SetParameter(2, "R",    1, 0.1, 0,0);

   Double_t arglist[1] = {0};
   fitter->ExecuteCommand("MIGRAD", arglist, 0);

   //Draw the circle on top of the points
   TArc *arc = new TArc(fitter->GetParameter(0),
      fitter->GetParameter(1),fitter->GetParameter(2));
   arc->SetLineColor(kRed);
   arc->SetLineWidth(4);
   arc->Draw();
}
Exemplo n.º 2
0
//____________________________________________________________________
void ErrorIntegral() {
   fitFunc = new TF1("f",f,0,1,NPAR);
   TH1D * h1     = new TH1D("h1","h1",50,0,1);

   double  par[NPAR] = { 3.14, 1.};
   fitFunc->SetParameters(par);

   h1->FillRandom("f",1000); // fill histogram sampling fitFunc
   fitFunc->SetParameter(0,3.);  // vary a little the parameters
   h1->Fit(fitFunc);             // fit the histogram

   h1->Draw();

   /* calculate the integral*/
   double integral = fitFunc->Integral(0,1);

   TVirtualFitter * fitter = TVirtualFitter::GetFitter();
   assert(fitter != 0);
   double * covMatrix = fitter->GetCovarianceMatrix();

   /* using new function in TF1 (from 12/6/2007)*/
   double sigma_integral = fitFunc->IntegralError(0,1);

   std::cout << "Integral = " << integral << " +/- " << sigma_integral
             << std::endl;

   // estimated integral  and error analytically

   double * p = fitFunc->GetParameters();
   double ic  = p[1]* (1-std::cos(p[0]) )/p[0];
   double c0c = p[1] * (std::cos(p[0]) + p[0]*std::sin(p[0]) -1.)/p[0]/p[0];
   double c1c = (1-std::cos(p[0]) )/p[0];

   // estimated error with correlations
   double sic = std::sqrt( c0c*c0c * covMatrix[0] + c1c*c1c * covMatrix[3]
      + 2.* c0c*c1c * covMatrix[1]);

   if ( std::fabs(sigma_integral-sic) > 1.E-6*sic )
      std::cout << " ERROR: test failed : different analytical  integral : "
                << ic << " +/- " << sic << std::endl;
}
Exemplo n.º 3
0
int TwoHistoFit2D(bool global = true) {

    // create two histograms

    int nbx1 = 50;
    int nby1 = 50;
    int nbx2 = 50;
    int nby2 = 50;
    double xlow1 = 0.;
    double ylow1 = 0.;
    double xup1 = 10.;
    double yup1 = 10.;
    double xlow2 = 5.;
    double ylow2 = 5.;
    double xup2 = 20.;
    double yup2 = 20.;

    TH2D * h1 = new TH2D("h1","core",nbx1,xlow1,xup1,nby1,ylow1,yup1);
    TH2D * h2 = new TH2D("h2","tails",nbx2,xlow2,xup2,nby2,ylow2,yup2);

    double iniParams[10] = { 100, 6., 2., 7., 3, 100, 12., 3., 11., 2. };
    // create fit function
    TF2 * func = new TF2("func",my2Dfunc,xlow2,xup2,ylow2,yup2, 10);
    func->SetParameters(iniParams);

    // fill Histos
    int n1 = 50000;
    int n2 = 50000;
    //  h1->FillRandom("func", n1);
    //h2->FillRandom("func",n2);
    FillHisto(h1,n1,iniParams);
    FillHisto(h2,n2,iniParams);

    // scale histograms to same heights (for fitting)
    double dx1 = (xup1-xlow1)/double(nbx1);
    double dy1 = (yup1-ylow1)/double(nby1);
    double dx2 = (xup2-xlow2)/double(nbx2);
    double dy2 = (yup2-ylow2)/double(nby2);
//   h1->Sumw2();
//   h1->Scale( 1.0 / ( n1 * dx1 * dy1 ) );
    // scale histo 2 to scale of 1
    h2->Sumw2();
    h2->Scale(  ( double(n1) * dx1 * dy1 )  / ( double(n2) * dx2 * dy2 ) );


    if (global) {
        // fill data structure for fit (coordinates + values + errors)
        std::cout << "Do global fit" << std::endl;
        // fit now all the function together

        // fill data structure for fit (coordinates + values + errors)
        TAxis *xaxis1  = h1->GetXaxis();
        TAxis *yaxis1  = h1->GetYaxis();
        TAxis *xaxis2  = h2->GetXaxis();
        TAxis *yaxis2  = h2->GetYaxis();

        int nbinX1 = h1->GetNbinsX();
        int nbinY1 = h1->GetNbinsY();
        int nbinX2 = h2->GetNbinsX();
        int nbinY2 = h2->GetNbinsY();

        /// reset data structure
        coords = std::vector<std::pair<double,double> >();
        values = std::vector<double>();
        errors = std::vector<double>();


        for (int ix = 1; ix <= nbinX1; ++ix) {
            for (int iy = 1; iy <= nbinY1; ++iy) {
                if ( h1->GetBinContent(ix,iy) > 0 ) {
                    coords.push_back( std::make_pair(xaxis1->GetBinCenter(ix), yaxis1->GetBinCenter(iy) ) );
                    values.push_back( h1->GetBinContent(ix,iy) );
                    errors.push_back( h1->GetBinError(ix,iy) );
                }
            }
        }
        for (int ix = 1; ix <= nbinX2; ++ix) {
            for (int iy = 1; iy <= nbinY2; ++iy) {
                if ( h2->GetBinContent(ix,iy) > 0 ) {
                    coords.push_back( std::make_pair(xaxis2->GetBinCenter(ix), yaxis2->GetBinCenter(iy) ) );
                    values.push_back( h2->GetBinContent(ix,iy) );
                    errors.push_back( h2->GetBinError(ix,iy) );
                }
            }
        }

        TVirtualFitter::SetDefaultFitter("Minuit");
        TVirtualFitter * minuit = TVirtualFitter::Fitter(0,10);
        for (int i = 0; i < 10; ++i) {
            minuit->SetParameter(i, func->GetParName(i), func->GetParameter(i), 0.01, 0,0);
        }
        minuit->SetFCN(myFcn);

        double arglist[100];
        arglist[0] = 0;
        // set print level
        minuit->ExecuteCommand("SET PRINT",arglist,2);

// minimize
        arglist[0] = 5000; // number of function calls
        arglist[1] = 0.01; // tolerance
        minuit->ExecuteCommand("MIGRAD",arglist,2);

        //get result
        double minParams[10];
        double parErrors[10];
        for (int i = 0; i < 10; ++i) {
            minParams[i] = minuit->GetParameter(i);
            parErrors[i] = minuit->GetParError(i);
        }
        double chi2, edm, errdef;
        int nvpar, nparx;
        minuit->GetStats(chi2,edm,errdef,nvpar,nparx);

        func->SetParameters(minParams);
        func->SetParErrors(parErrors);
        func->SetChisquare(chi2);
        int ndf = coords.size()-nvpar;
        func->SetNDF(ndf);

        std::cout << "Chi2 Fit = " << chi2 << " ndf = " << ndf << "  " << func->GetNDF() << std::endl;

        // add to list of functions
        h1->GetListOfFunctions()->Add(func);
        h2->GetListOfFunctions()->Add(func);
    }
    else {
        // fit independently
        h1->Fit(func);
        h2->Fit(func);
    }



    // Create a new canvas.
    TCanvas * c1 = new TCanvas("c1","Two HIstogram Fit example",100,10,900,800);
    c1->Divide(2,2);
    gStyle->SetOptFit();
    gStyle->SetStatY(0.6);

    c1->cd(1);
    h1->Draw();
    func->SetRange(xlow1,ylow1,xup1,yup1);
    func->DrawCopy("cont1 same");
    c1->cd(2);
    h1->Draw("lego");
    func->DrawCopy("surf1 same");
    c1->cd(3);
    func->SetRange(xlow2,ylow2,xup2,yup2);
    h2->Draw();
    func->DrawCopy("cont1 same");
    c1->cd(4);
    h2->Draw("lego");
    gPad->SetLogz();
    func->Draw("surf1 same");

    return 0;
}
Exemplo n.º 4
0
int makeInvMassHistosNoBGKK(){
    //Set global style stuff
    gROOT->Reset();
    gROOT->SetStyle("Plain");
    gStyle->SetPalette(1);
    gStyle->SetCanvasColor(kWhite);
    gStyle->SetCanvasBorderMode(0);
    gStyle->SetPadBorderMode(0);
    gStyle->SetTitleBorderSize(0);
    gStyle->SetOptStat(0);
    gStyle->SetOptFit(1);
    gStyle->SetErrorX(0);
    gStyle->SetTitleW(0.9);
    gStyle->SetTitleSize(0.05, "xyz");
    gStyle->SetTitleSize(0.06, "h");

    int NUM_PT_BINS = 20;
    int NUM_MASS_BINS = 1000;
    double MASS_LOW = 0.0;
    double MASS_HIGH = 2.0;
    string particles [8];
    particles[0] = "K*^{+} + K*^{0}";
    particles[1] = "K*^{-} + #bar{K}*^{0}";
    particles[2] = "K*^{+}";
    particles[3] = "K*^{-}";
    particles[4] = "K*^{0}";
    particles[5] = "#bar{K}*^{0}";
    particles[6] = "K*^{0} + #bar{K}*^{0}";
    particles[7] = "K*^{+} + K*^{-}";
//at decay point
//    string folder = "/Users/jtblair/Downloads/kstar_data/decayed/pt02/";
//reconstructed
    string folder = "/Users/jtblair/Downloads/kstar_data/reconstructed/pt02/";

    string files[20];
    files[0] = "invm_[0.0,0.2].dat";
    files[1] = "invm_[0.2,0.4].dat";
    files[2] = "invm_[0.4,0.6].dat";
    files[3] = "invm_[0.6,0.8].dat";
    files[4] = "invm_[0.8,1.0].dat";
    files[5] = "invm_[1.0,1.2].dat";
    files[6] = "invm_[1.2,1.4].dat";
    files[7] = "invm_[1.4,1.6].dat";   
    files[8] = "invm_[1.6,1.8].dat";
    files[9] = "invm_[1.8,2.0].dat";
    files[10] = "invm_[2.0,2.2].dat";
    files[11] = "invm_[2.2,2.4].dat";
    files[12] = "invm_[2.4,2.6].dat";
    files[13] = "invm_[2.6,2.8].dat";
    files[14] = "invm_[2.8,3.0].dat";
    files[15] = "invm_[3.0,3.2].dat";
    files[16] = "invm_[3.2,3.4].dat";
    files[17] = "invm_[3.4,3.6].dat";
    files[18] = "invm_[3.6,3.8].dat";
    files[19] = "invm_[3.8,4.0].dat";
/*
    string files[8];
    files[0] = "invm_[0.0,0.5].dat";
    files[1] = "invm_[0.5,1.0].dat";
    files[2] = "invm_[1.0,1.5].dat";
    files[3] = "invm_[1.5,2.0].dat";
    files[4] = "invm_[2.0,2.5].dat";
    files[5] = "invm_[2.5,3.0].dat";
    files[6] = "invm_[3.0,3.5].dat";
    files[7] = "invm_[3.5,4.0].dat";
*/

    Int_t PARTICLE_NUM = 5;

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

    TH1D *kstar0mass = new TH1D("kstar0mass", Form("Fit value of M*_{0} vs. p_{T} for %s", particles[PARTICLE_NUM].c_str()), NUM_PT_BINS, 0.0, 4.0);
    TH1D *kstar0width = new TH1D("kstar0width", Form("#Gamma_{tot}(M=M*_{0}) vs p_{T} for %s", particles[PARTICLE_NUM].c_str()), NUM_PT_BINS, 0.0, 4.0);
    TH1D *kstar0collWidth = new TH1D("kstar0collWidth", Form("Fit value of #Gamma_{coll} component vs. p_{T} for %s", particles[PARTICLE_NUM].c_str()), NUM_PT_BINS,0.0, 4.0);
    TH1D *kstar0decWidth = new TH1D("kstar0decWidth", Form("#Gamma_{dec}(M=M*_{0}) component vs. p_{T} for %s;p_{T} (GeV/c);Width (GeV/c^2)", particles[PARTICLE_NUM].c_str()), NUM_PT_BINS,0.0, 4.0);
   
    kstar0mass->GetXaxis()->SetTitle("p_{T} (GeV/c)");
    kstar0mass->GetYaxis()->SetTitle("Mass (GeV/c^{2})");
    kstar0width->GetXaxis()->SetTitle("p_{T} (GeV/c)");
    kstar0width->GetYaxis()->SetTitle("Width (GeV/c^2)");
    kstar0collWidth->GetXaxis()->SetTitle("p_{T} (GeV/c)");
    kstar0collWidth->GetYaxis()->SetTitle("Width (GeV/c^2)");

    kstar0mass->SetStats(kFALSE);
    kstar0width->SetStats(kFALSE);
    kstar0collWidth->SetStats(kFALSE);
    kstar0decWidth->SetStats(kFALSE);

    TF1 *massline = new TF1("massline", "[0]", 0.0, 4.0);
    massline->SetParameter(0, 0.892);
    massline->SetLineColor(2);
    massline->SetLineStyle(7);

    TF1 *widthline = new TF1("widthline", "[0]", 0.0, 4.0);
    widthline->SetParameter(0, 0.042);

    double mass = 0.0, width = 0.0, collWidth = 0.0, massBG=0.0;
    double massError = 0.0, widthError= 0.0, collWidthError = 0.0, massBGError=0.0;

    TCanvas *canvas[9];
    TCanvas *diffCanvas[9];
    TPaveStats *st;
    TPad *pad;

    //ofstream integrals;
    //integrals.open("kstarbar_integrals.txt");

    for(int nfile = 0; nfile < NUM_PT_BINS; nfile++){
        double meanPT = (double)(nfile*2+1)/10.0;
        string filename = folder+files[nfile];
        string ptLower = filename.substr(filename.find("[")+1, 3);
        string ptHigher = filename.substr(filename.find(",")+1, 3);   
        TH1D* histos[8];
        TH1D* newHistos[8];
        TH1D* diffHistos[8];
        TH1D* bg[8];
        for(int i=0; i<8; i++){
            if(nfile<5){
                histos[i] = new TH1D(Form("ptbin0%dparticle%d",nfile*2+1, i), Form("Invariant Mass for (%s), %s < p_{T} < %s",particles[i].c_str(), ptLower.c_str(), ptHigher.c_str()), NUM_MASS_BINS, MASS_LOW, MASS_HIGH);
            newHistos[i] = new TH1D(Form("newptbin0%dparticle%d",nfile*2+1, i), Form("Invariant Mass for (%s), %s < p_{T} < %s",particles[i].c_str(), ptLower.c_str(), ptHigher.c_str()), 250, MASS_LOW, MASS_HIGH);

            }else{
                histos[i] = new TH1D(Form("ptbin%dparticle%d",nfile*2+1, i), Form("Invariant Mass for (%s), %s < p_{T} < %s",particles[i].c_str(), ptLower.c_str(), ptHigher.c_str()), NUM_MASS_BINS, MASS_LOW, MASS_HIGH);
                newHistos[i] = new TH1D(Form("newptbin%dparticle%d",nfile*2+1, i), Form("Invariant Mass for (%s), %s < p_{T} < %s",particles[i].c_str(), ptLower.c_str(), ptHigher.c_str()), 250, MASS_LOW, MASS_HIGH);

            }
            histos[i]->GetXaxis()->SetTitle("Invariant Mass (GeV/c^{2})");
            histos[i]->GetYaxis()->SetTitle("Counts");
        }

        ifstream input;
        input.open(filename.c_str());
        string line = "";
        if(input.good()){
            getline(input, line);
        }

        double massBin=0.0;
        double invMass[8];
        for(int i=0; i<8; i++){
            invMass[i] = 0.0;
        }
        int lineNumber = 1;
        while(1){
            input >> massBin >> invMass[0] >> invMass[1] >> invMass[2] >> invMass[3] >> invMass[4] >> invMass[5] >> invMass[6] >> invMass[7];
            if(!input.good())break;
            for(int i =0; i<8; i++){
                histos[i]->SetBinContent(lineNumber, invMass[i]/500.0);
            }
            if(lineNumber > 440 && lineNumber < 460 && nfile==6){
//               printf("mass: %.12f invMass[6]: %.12f\n", massBin, invMass[6]);
            }
            lineNumber++;
        }
         

        printf("****** Fits for file: %s ******\n", filename.c_str());
        for(int i=PARTICLE_NUM; i<PARTICLE_NUM+1; i++){
           
            //add the K*0 distribution to the K*0bar (K*0 = 4 for decay, K*0 = 3 for reconstructed)
            histos[i]->Add(histos[3]);
            if(nfile==0){
                canvas[i] = new TCanvas(Form("c%i", i),Form("c%i", i), 0,0,900,900);
                canvas[i]->Divide(5,4);
                diffCanvas[i] = new TCanvas(Form("diffC%i", i),Form("diffC%i", i), 0,0,900,900);
                diffCanvas[i]->Divide(5,4);
            }
            //rebin
            //histos[i]->Sumw2();
            histos[i]->Rebin(4);

            //Fixing the errors to a percentage of the signal region:
            for(int ibin=1; ibin < histos[i]->GetNbinsX(); ibin++){
                histos[i]->SetBinError(ibin, histos[i]->GetBinContent((int)(0.892*(250.0/2.0)))*0.05);
                newHistos[i]->SetBinContent(ibin, histos[i]->GetBinContent(ibin));
                newHistos[i]->SetBinError(ibin, histos[i]->GetBinError(ibin));
            }
            
            pad = (TPad*)canvas[i]->cd(nfile+1);
            histos[i]->SetLineColor(1);
            histos[i]->SetLineWidth(1);
            histos[i]->GetXaxis()->SetRangeUser(0.7, 1.2);
            histos[i]->GetYaxis()->SetRangeUser(0, 1.5*histos[i]->GetBinContent(histos[i]->GetMaximumBin()));
            //histos[i]->SetStats(kFALSE);
            
            //histos[i]->Draw("HIST");

            printf("mean PT: %f\n", meanPT);

            TF1 *fit = new TF1(Form("fitPTbin%d00particle%d", nfile*2+1, i), FitFunRelBW, 0.68, 1.05, 5);
            //TF1 *fit = new TF1(Form("fitPTbin%d00particle%d", nfile*2+1, i), "gaus(0)", 0.86, 0.92);


            fit->SetParNames("BW Area", "Mass", "Width", "PT", "Temp");
            fit->SetParameters(TMath::Power(10.0, (float)(nfile)/1.7), 0.89, 0.1, 0.5, 0.130);
            //fit->SetParNames("BW Area", "Mass", "Width");
            //fit->SetParameters(100, 0.89, 0.0474);
            //fit->SetParLimits(0, -10, 1.5e9);
            Float_t max = histos[i]->GetXaxis()->GetBinCenter(histos[i]->GetMaximumBin());
            //if(max < 0.91 && max > 0.892){
            //    fit->SetParLimits(1, max-0.001, max+0.001);
            //}else{
                fit->SetParLimits(1, 0.82, 0.98);
            //}
            //fit->SetParLimits(2, 0.005, 0.15);
            fit->FixParameter(2, 0.042);
            fit->FixParameter(3, meanPT);
            //fit->SetParLimits(4, 0.05, 0.2);
            fit->FixParameter(4, 0.100001);
            fit->SetLineColor(2);

            printf("%s\n", fit->GetName());

            histos[i]->Fit(Form("fitPTbin%d00particle%d", nfile*2+1, i), "BRIM", "SAME");
            TVirtualFitter *fitter = TVirtualFitter::GetFitter();
           
            histos[i]->SetStats(1);
            histos[i]->Draw();
            gPad->Update();
            pad->Update();
            st = (TPaveStats*)histos[i]->FindObject("stats");
            st->SetX1NDC(0.524);
            st->SetY1NDC(0.680);
            st->SetX2NDC(0.884);
            st->SetY2NDC(0.876);
            //fit->Draw("SAME");
            //histos[i]->Draw();
            gPad->Update();
            pad->Update();
            printf("\n");
    
            diffHistos[i] = (TH1D*)histos[i]->Clone(Form("diffPTbin%d00particl%d", nfile*2+1, i));
            diffHistos[i]->Add(fit, -1);
            diffCanvas[i]->cd(nfile+1);
            diffHistos[i]->Draw("HIST E");
            diffHistos[i]->Write();

            //counting bins
            Float_t integral = histos[i]->Integral(1, 500)*500.0;
            //integrals << integral <<" \n";
            histos[i]->Write();
            fit->Write();
            //Do mass and width vs. pT plots just for K*0
            if(i==PARTICLE_NUM){
                mass = fit->GetParameter(1);
                massError = fit->GetParError(1);

                collWidth = fit->GetParameter(2);
                collWidthError = fit->GetParError(2);

                width = Gamma(mass, collWidth);

                kstar0mass->SetBinContent(nfile+1, mass);
                kstar0mass->SetBinError(nfile+1, massError);

                kstar0width->SetBinContent(nfile+1, width);
                Double_t widthError = TMath::Sqrt((GammaDerivative(mass)**2)*fitter->GetCovarianceMatrixElement(1,1) + fitter->GetCovarianceMatrixElement(2,2) + 2.0*GammaDerivative(mass)*fitter->GetCovarianceMatrixElement(1,2));
                kstar0width->SetBinError(nfile+1, widthError);

                kstar0collWidth->SetBinContent(nfile+1, collWidth);
                kstar0collWidth->SetBinError(nfile+1, collWidthError);

                kstar0decWidth->SetBinContent(nfile+1, width - collWidth);
                Double_t decWidthError = TMath::Sqrt((GammaDerivative(mass)**2)*fitter->GetCovarianceMatrixElement(1,1));
                kstar0decWidth->SetBinError(nfile+1, decWidthError);

                if(nfile==4){
                    TCanvas *singlecanvas = new TCanvas("singlecanvas", "singlecanvas", 0,0,600,600);
                    singlecanvas->cd();
                    printf("Got here! \n");
                    histos[i]->Draw("HIST E SAME");

                    fit->SetLineColor(8);
                    fit->SetLineStyle(1);
                    
                    fit->Draw("SAME");
                    if(fitter){
                        printf("sig11: %f, sig12: %f, sig21: %f, sig22: %f GammaDer(0.8): %f GammaDer(0.85): %f GammaDer(0.9): %f\n", TMath::Sqrt(fitter->GetCovarianceMatrixElement(1,1)), fitter->GetCovarianceMatrixElement(2,1), fitter->GetCovarianceMatrixElement(1,2), TMath::Sqrt(fitter->GetCovarianceMatrixElement(2,2)), GammaDerivative(0.8), GammaDerivative(0.85), GammaDerivative(0.9));
                    }
                }
            }
        }
        printf("************************************************************\n");
         
    }
        //integrals.close();
/*
    TH2D *gammaPlot = new TH2D("gammaPlot", "#Gamma_{tot}(M_{0}*);M_{0}*;#Gamma_{coll};#Gamma_{tot}", 100, 0.82, 0.9, 100, 0.0, 0.08);
    for(int im = 0; im<100; im++){
        for(int ig = 0; ig < 100; ig++){
            gammaPlot->SetBinContent(im+1, ig+1, Gamma(((0.9-0.82)/(100.0))*((double)(im)) + 0.82, ((0.08)/100.0)*((double)(ig))));
        }
    }

    TH1D *gammaMassDpnd = gammaPlot->ProjectionX("gammaMassDpnd");
*/
    TCanvas *masscanvas = new TCanvas("masscanvas", "masscanvas", 50,50, 600, 600);
    masscanvas->cd();
    kstar0mass->Draw();
    massline->Draw("SAME");
    masscanvas->Write();

    for(int i=PARTICLE_NUM; i<PARTICLE_NUM+1; i++){
        canvas[i]->Write();
    }
    kstar0mass->Write();
    kstar0collWidth->Write();
    kstar0decWidth->Write();
    kstar0width->Write();
//    gammaPlot->Write();
//    gammaMassDpnd->Write();
}
Exemplo n.º 5
0
void FitDijetMass_Data() {

  
  TFile *inf  = new TFile("MassResults_ak7calo.root");
  TH1F *hCorMassDen     = (TH1F*) inf->Get("DiJetMass");
  hCorMassDen->SetXTitle("Corrected Dijet Mass (GeV)");
  hCorMassDen->SetYTitle("Events/GeV");
  hCorMassDen->GetYaxis()->SetTitleOffset(1.5);
  hCorMassDen->SetMarkerStyle(20);
  hCorMassDen->GetXaxis()->SetRangeUser(120.,900.);



  gROOT->ProcessLine(".L tdrstyle.C");
  setTDRStyle();
  tdrStyle->SetErrorX(0.5);
  tdrStyle->SetPadRightMargin(0.08);
  tdrStyle->SetLegendBorderSize(0);
  gStyle->SetOptFit(1111);
  tdrStyle->SetOptStat(0); 

  
  TCanvas* c2 = new TCanvas("c2","DijetMass", 500, 500);
  /////// perform 4 parameters fit
  TF1 *func = new TF1("func", "[0]*((1-x/7000.+[3]*(x/7000)^2)^[1])/(x^[2])", 
  100., 1000.);
  func->SetParameter(0, 1.0e+08);
  func->SetParameter(1, -1.23);
  func->SetParameter(2, 4.13);
  func->SetParameter(3, 1.0);

  func->SetLineColor(4);
  func->SetLineWidth(3);

  TVirtualFitter::SetMaxIterations( 10000 );
  TVirtualFitter *fitter;
  TMatrixDSym* cov_matrix;

  int fitStatus = hCorMassDen->Fit("func","LLI","",130.0, 800.0); // QCD fit
 
  TH1F *hFitUncertainty = hCorMassDen->Clone("hFitUncertainty");
  hFitUncertainty->SetLineColor(5);
  hFitUncertainty->SetFillColor(5);
  hFitUncertainty->SetMarkerColor(5);

  if (fitStatus == 0) {
    fitter = TVirtualFitter::GetFitter();
    double* m_elements = fitter->GetCovarianceMatrix();
    cov_matrix = new TMatrixDSym( func->GetNumberFreeParameters(),m_elements);
    cov_matrix->Print();
    double x, y, e;

    for(int i=0;i<hFitUncertainty->GetNbinsX();i++)
      {
	x = hFitUncertainty->GetBinCenter(i+1);
	y = func->Eval(x);
	e = QCDFitUncertainty( func, *cov_matrix, x);
	hFitUncertainty->SetBinContent(i+1,y);
	hFitUncertainty->SetBinError(i+1,e);
      }
  }

  hCorMassDen->Draw("ep");
  gPad->Update();
  TPaveStats *st = (TPaveStats*)hCorMassDen->FindObject("stats");
  st->SetName("stats1");
  st->SetX1NDC(0.3); //new x start position
  st->SetX2NDC(0.6); //new x end position
  st->SetTextColor(4);
  hCorMassDen->GetListOfFunctions()->Add(st);



  /////// perform 2 parameters fit
  TF1 *func2 = new TF1("func2", "[0]*(1-x/7000.)/(x^[1])", 100., 1000.);
  func2->SetParameter(0, 10000.);
  func2->SetParameter(1, 5.0);
  func2->SetLineWidth(3);

  fitStatus = hCorMassDen->Fit("func2","LLI","",130.0, 800.0); // QCD fit

  TH1F *hFitUncertainty2 = hCorMassDen->Clone("hFitUncertainty2");
  hFitUncertainty2->SetLineColor(kGray);
  hFitUncertainty2->SetFillColor(kGray);
  hFitUncertainty2->SetMarkerColor(kGray);

  if (fitStatus == 0) {
    fitter = TVirtualFitter::GetFitter();
    double* m_elements = fitter->GetCovarianceMatrix();
    cov_matrix = new TMatrixDSym( func2->GetNumberFreeParameters(),m_elements);
    cov_matrix->Print();
    double x, y, e;

    for(int i=0;i<hFitUncertainty2->GetNbinsX();i++)
      {
	x = hFitUncertainty2->GetBinCenter(i+1);
	y = func2->Eval(x);
	e = QCDFitUncertainty( func2, *cov_matrix, x);
	hFitUncertainty2->SetBinContent(i+1,y);
	hFitUncertainty2->SetBinError(i+1,e);
      }
  }

  hFitUncertainty->Draw("E3 same");
  hCorMassDen->Draw("ep sames");
  hFitUncertainty2->Draw("E3 same");
  hCorMassDen->Draw("ep sames");
  func2->Draw("same");
  c2->SetLogy(1);



/*
  

  TH1F *hCorMass     = hCorMassDen->Clone("hCorMass");


  for(int i=0; i<hCorMass->GetNbinsX(); i++){
    hCorMass->SetBinContent(i+1, hCorMassDen->GetBinContent(i+1) * hCorMassDen->GetBinWidth(i+1));
    hCorMass->SetBinError(i+1, hCorMassDen->GetBinError(i+1) * hCorMassDen->GetBinWidth(i+1));
  } 




  // Our observable is the invariant mass
  RooRealVar invMass("invMass", "Corrected dijet mass", 
		     100., 1000.0, "GeV");
  RooDataHist data( "data", "", invMass, hCorMass);

   //////////////////////////////////////////////




   // make QCD model
  RooRealVar p0("p0", "# events", 600.0, 0.0, 10000000000.);
  RooRealVar p1("p1","p1", 3.975, -10., 10.) ;  
  RooRealVar p2("p2","p2", 5.302, 4., 8.) ; 
  RooRealVar p3("p3","p3", -1.51, -100., 100.) ; 



//    // define QCD line shape
  RooGenericPdf qcdModel("qcdModel", "pow(1-@0/7000.+@3*(@0/7000.)*(@0/7000.),@1)*pow(@0/7000.,-@2)",
			 RooArgList(invMass,p1,p2,p3)); 

   // full model
   RooAddPdf model("model","qcd",RooArgList(qcdModel), RooArgList(p0)); 



   //plot sig candidates, full model, and individual componenets 

   //   __ _ _    
   //  / _(_) |_  
   // | |_| | __| 
   // |  _| | |_  
   // |_| |_|\__| 


 // Important: fit integrating f(x) over ranges defined by X errors, rather
  // than taking point at center of bin

   RooFitResult* fit = model.fitTo(data, Minos(kFALSE), Extended(kTRUE),
				   SumW2Error(kFALSE),Save(kTRUE), Range(130.,800.),
				   Integrate(kTRUE) );

   // to perform chi^2 minimization fit instead
   //    RooFitResult* fit = model.chi2FitTo(data, Extended(kTRUE), 
   // 				       Save(),Range(50.,526.),Integrate(kTRUE) );

   fit->Print();


   //plot data 
   TCanvas* cdataNull = new TCanvas("cdataNull","fit to dijet mass",500,500);
   RooPlot* frame1 = invMass.frame() ; 
   data.plotOn(frame1, DataError(RooAbsData::SumW2) ) ; 
   model.plotOn(frame1, LineColor(kBlue)) ; 
   model.plotOn(frame1, VisualizeError(*fit, 1),FillColor(kYellow)) ;   
   data.plotOn(frame1, DataError(RooAbsData::SumW2) ) ; 
   model.plotOn(frame1, LineColor(kBlue)) ; 
   model.paramOn(frame1, Layout(0.4, 0.85, 0.92)); 
   TPaveText* dataPave = (TPaveText*) frame1->findObject("model_paramBox");
   dataPave->SetY1(0.77);
   gPad->SetLogy();
   frame1->GetYaxis()->SetNoExponent();
   frame1->GetYaxis()->SetRangeUser(5E-2,5E+4);
   frame1->GetYaxis()->SetTitle("Events / bin");
   frame1->GetYaxis()->SetTitleOffset(1.35);
   frame1->SetTitle("fit to data with QCD lineshape");
   frame1->Draw() ;


    
    // S h o w   r e s i d u a l   a n d   p u l l   d i s t s
    // -------------------------------------------------------
    
   //// Construct a histogram with the residuals of the data w.r.t. the curve
   RooHist* hresid = frame1->residHist() ;
   // Create a new frame to draw the residual distribution and add the distribution to the frame
   RooPlot* frame2 = invMass.frame(Title("Residual Distribution")) ;
   frame2->addPlotable(hresid,"P") ;


    
   ///// Construct a histogram with the pulls of the data w.r.t the curve
   RooHist* hpull = frame1->pullHist() ;   
   //// Create a new frame to draw the pull distribution and add the distribution to the frame
   RooPlot* frame3 = invMass.frame(Title("Pull Distribution")) ;
   frame3->addPlotable(hpull,"P") ;


   TCanvas* cResidual = new TCanvas("cResidual","Residual Distribution",1000,500);
   cResidual->Divide(2) ;
   cResidual->cd(1) ; gPad->SetLeftMargin(0.15) ; frame1->GetYaxis()->SetTitleOffset(1.6) ; frame2->Draw() ;
   cResidual->cd(2) ; gPad->SetLeftMargin(0.15) ; frame1->GetYaxis()->SetTitleOffset(1.6) ; frame3->Draw() ;
  
*/
}
void Fit_electron_nsigma_Mean(TH1F *mh1NisgmaE_unlike[NpT_bins_run12_MB],TH1F *mh1NisgmaE_like[NpT_bins_run12_MB],TH1F *mh1NisgmaE_unlike_like[NpT_bins_run12_MB])
{
  gStyle->SetOptFit(1111);
  
  TH1F *Mean=new TH1F("Mean","",    NpT_bins_run12_MB,pt_run12_MB);
  TH1F *Mean_u=new TH1F("Mean_u","",NpT_bins_run12_MB,pt_run12_MB);
  TH1F *Mean_d=new TH1F("Mean_d","",NpT_bins_run12_MB,pt_run12_MB);
  
  TH1F *Sigma=new TH1F("Sigma","",NpT_bins_run12_MB,pt_run12_MB);
  TH1F *Sigma_u=new TH1F("Sigma_u","",NpT_bins_run12_MB,pt_run12_MB);
  TH1F *Sigma_d=new TH1F("Sigma_d","",NpT_bins_run12_MB,pt_run12_MB);
  
  
  TCanvas *c2=new TCanvas("c2","",1200,1000);
  TCanvas *c3=new TCanvas("c3","",1200,1000);

  TCanvas *c4=new TCanvas("c4","",1200,1000);
  TCanvas *c5=new TCanvas("c5","",1200,1000);

  c2->Divide(3,3,0.001,0.001);
  c3->Divide(3,3,0.001,0.001);

  c4->Divide(3,3,0.001,0.001);
  c5->Divide(3,3,0.001,0.001);

  int Npad=1;
  for(Int_t ipt=0;ipt<NpT_bins_run12_MB;ipt++)
    {
      TF1 *f1 = new TF1(TString("f1"),"gaus",-5,5);      
      if(ipt<9)
        {
          c2->cd(Npad++);
          gPad->SetLogy(1);
        }
      else if(ipt<18)
        {
          c3->cd(Npad++);
          gPad->SetLogy(1);
        }

      else if(ipt<27)
        {
          c4->cd(Npad++);
          gPad->SetLogy(1);
        }

      else if(ipt<36)
        {
          c5->cd(Npad++);
          gPad->SetLogy(1);
        }

      if(Npad==10) Npad=1;

      mh1NisgmaE_unlike_like[ipt]->SetTitle(mh1_pT_Title[ipt]);
      mh1NisgmaE_unlike_like[ipt]->GetXaxis()->SetTitle("nSigmaE");
      mh1NisgmaE_unlike_like[ipt]->GetYaxis()->SetTitle("Counts");

      mh1NisgmaE_unlike_like[ipt]->GetYaxis()->SetRangeUser(1,1.2*mh1NisgmaE_unlike[ipt]->GetMaximum());
      mh1NisgmaE_unlike_like[ipt]->GetXaxis()->SetRangeUser(-3,3);      


      mh1NisgmaE_unlike[ipt]->SetLineColor(1);
      mh1NisgmaE_like[ipt]->SetLineColor(3);
      mh1NisgmaE_unlike_like[ipt]->SetLineColor(4);


      mh1NisgmaE_unlike_like[ipt]->Fit(f1,"R","same",-3,3);
      mh1NisgmaE_unlike[ipt]->Draw("same");
      mh1NisgmaE_unlike_like[ipt]->Draw("same");
      mh1NisgmaE_like[ipt]->Draw("same");

      TLegend *legend = new TLegend(0.15,0.65,0.4,0.8);
      legend->AddEntry(mh1NisgmaE_unlike[ipt],"Unlike ","lpe");
      legend->AddEntry(mh1NisgmaE_like[ipt],"Like ","lpe");
      legend->AddEntry(mh1NisgmaE_unlike_like[ipt],"Unlike - Like ","lpe");
      legend->SetBorderSize(0);
      legend->SetFillStyle(0);
      legend->SetTextSize(0.035);
      legend->Draw("same");

      TVirtualFitter * fitter = TVirtualFitter::GetFitter();
      assert(fitter != 0);
      double * cov =fitter->GetCovarianceMatrix();
      
      cout<<cov[0]<<" "<<sqrt(cov[4])<<" "<<sqrt(cov[8])<<" "<<cov[7]<<" meanerr="<<f1->GetParError(1)<<"sigmaerr "<<f1->GetParError(2)<<endl;
      outdata << (pt_run12_MB[ipt]+pt_run12_MB[ipt+1])/2       << "  " << 0.5*(pt_run12_MB[ipt+1]-pt_run12_MB[ipt])    << "  "
	      << f1->GetParameter(1)     << "  " << cov[4]    << "  " 
	      << f1->GetParameter(2)     << "  " << cov[8]    << "  "<<cov[7]<< endl; 
      
      


    }



  c2->SaveAs("nsigmaE_c2_partner.pdf");
  c3->SaveAs("nsigmaE_c3_partner.pdf");

  c4->SaveAs("nsigmaE_c4_partner.pdf");
  c5->SaveAs("nsigmaE_c5_partner.pdf");

 
  
}
Exemplo n.º 7
0
//____________________________________________________________________
void ErrorIntegral() { 
   fitFunc = new TF1("f",f,0,1,NPAR); 
   TH1D * h1     = new TH1D("h1","h1",50,0,1); 

   double  par[NPAR] = { 3.14, 1.}; 
   fitFunc->SetParameters(par);

   h1->FillRandom("f",1000); // fill histogram sampling fitFunc
   fitFunc->SetParameter(0,3.);  // vary a little the parameters
   h1->Fit(fitFunc);             // fit the histogram 

   h1->Draw();

   // calculate the integral 
   double integral = fitFunc->Integral(0,1);

   TVirtualFitter * fitter = TVirtualFitter::GetFitter();
   assert(fitter != 0);
   double * covMatrix = fitter->GetCovarianceMatrix(); 

#ifdef HAVE_OLD_ROOT_VERSION

   // calculate now the error (needs the derivatives of the function 
   // w..r.t the parameters)
   TF1 * deriv_par0 = new TF1("dfdp0",df_dPar,0,1,1);
   deriv_par0->SetParameter(0,0);

   TF1 * deriv_par1 = new TF1("dfdp1",df_dPar,0,1,1);
   deriv_par1->SetParameter(0,1.);

   double c[2]; 

   c[0] = deriv_par0->Integral(0,1); 
   c[1] = deriv_par1->Integral(0,1); 

   double * epar = fitFunc->GetParErrors();

   // without correlations
   double sigma_integral_0 = IntegralError(2,c,epar);



   // with correlations
   double sigma_integral = IntegralError(2,c,epar,covMatrix);

#else 
   
   // using new function in TF1 (from 12/6/2007) 
   double sigma_integral = fitFunc->IntegralError(0,1);

#endif

   std::cout << "Integral = " << integral << " +/- " << sigma_integral 
             << std::endl;

   // estimated integral  and error analytically

   double * p = fitFunc->GetParameters();
   double ic  = p[1]* (1-std::cos(p[0]) )/p[0];
   double c0c = p[1] * (std::cos(p[0]) + p[0]*std::sin(p[0]) -1.)/p[0]/p[0];
   double c1c = (1-std::cos(p[0]) )/p[0];

   // estimated error with correlations
   double sic = std::sqrt( c0c*c0c * covMatrix[0] + c1c*c1c * covMatrix[3] 
      + 2.* c0c*c1c * covMatrix[1]); 

   if ( std::fabs(sigma_integral-sic) > 1.E-6*sic ) 
      std::cout << " ERROR: test failed : different analytical  integral : " 
                << ic << " +/- " << sic << std::endl;
}
Exemplo n.º 8
0
//***############## main fitting Fxn ################ *****//
void FitPlotAndSave( char *Ifile ){
 
/** Plot Options***/	
//gROOT->Reset();
// gROOT->Clear();
gROOT->SetStyle("Plain") ;
gROOT->SetBatch(kFALSE);
gStyle->SetOptTitle(1);
gStyle->SetOptStat(0);
gStyle->SetOptFit(1);
gStyle->SetStatX(.89);
gStyle->SetStatY(.89) ;
gStyle->SetStatBorderSize(0);
//gStyle->SetOptStat(1111111)
gStyle->SetCanvasColor(kWhite);   // background is no longer mouse-dropping white
gStyle->SetPalette(1);        // blue to red false color palette. Use 9 for b/w
gStyle->SetCanvasBorderMode(0);     // turn off canvas borders
gStyle->SetPadBorderMode(0);
gStyle->SetPaintTextFormat("5.2f");  // What precision to put numbers if plotted with "TEXT"

// For publishing:
gStyle->SetLineWidth(2);
gStyle->SetTextSize(1.1);
gStyle->SetLabelSize(0.06,"xy");
gStyle->SetTitleSize(0.08,"xy");
gStyle->SetTitleOffset(1.2,"x");
gStyle->SetTitleOffset(1.0,"y");
gStyle->SetPadTopMargin(0.1);
gStyle->SetPadRightMargin(0.1);
gStyle->SetPadBottomMargin(0.16);
gStyle->SetPadLeftMargin(0.12);
TGaxis::SetMaxDigits(1); // Set Axis to be of the form 0.11 10^N


       TFile *ifile  = new TFile(Ifile);
        
	TF1 *fitFcn  = new TF1("fitFcn", mygaus, FitLowRange, FitHighRange, 3 );
	fitFcn->SetNpx(500);
	fitFcn->SetLineWidth(4);
	fitFcn->SetLineStyle(5);
	fitFcn->SetLineColor(kBlue);
        cout <<" Calling Fitting Fxntion" << endl;
	TH1F*h_Seed_TimeEBEB = (TH1F*)ifile->Get("EBEB/seed time");
	if(h_Seed_TimeEBEB == 0){ std::cout  <<"!! Histogram Does not exist!!" << std::endl; throw 1;}
        
	h_Seed_TimeEBEB->SetTitle("Seed Time[ns]");   
        h_Seed_TimeEBEB->SetMarkerStyle(20);
        h_Seed_TimeEBEB->SetMarkerSize(0.8);
        h_Seed_TimeEBEB->SetStats(1);
        h_Seed_TimeEBEB->SetTitleSize(0.08, "x");   
        h_Seed_TimeEBEB->SetTitleOffset(1.0, "x");    
        h_Seed_TimeEBEB->SetTitleSize(0.06, "y"); 
        h_Seed_TimeEBEB->SetTitleOffset(0.95, "y");    
        h_Seed_TimeEBEB->SetYTitle("Number of Seeds/0.05ns"); 
        h_Seed_TimeEBEB->SetXTitle("t_{seed}[ns]"); 
        h_Seed_TimeEBEB->GetXaxis()->SetRangeUser(FitLowRange, FitHighRange);   

       /** Set parms as parms of Fit Fxn **/
	fitFcn->SetParameters(500, h_Seed_TimeEBEB->GetMean(), h_Seed_TimeEBEB->GetRMS() );
	fitFcn->SetParNames("CONST", "#mu(ns)", "#sigma(ns)");
	h_Seed_TimeEBEB->Fit("fitFcn", "LL"); /**Fit with improved LL**/
	std::cout << "Printing Fit Parameters for EBEB ......   " << std::endl;
        printf("Integral of function in EBEB = %g\n", fitFcn->Integral( FitLowRange, FitHighRange));

        //*** retrive fit results***//
        int npar = fitFcn->GetNpar();
        TVirtualFitter *fit = TVirtualFitter::GetFitter();
        fit->PrintResults(2,0.);
        TMatrixD *CovMatrix = new TMatrixD ( npar, npar, fit->GetCovarianceMatrix() );
	CovMatrix->Print();
        TCanvas *c1 = new TCanvas("c1","EB-EB",200,10,800,900);
     	c1->SetGridx();
     	c1->SetGridy();
	c1->GetFrame()->SetFillColor(21);
	c1->GetFrame()->SetBorderMode(-1);
	c1->GetFrame()->SetBorderSize(5);
        /* c1->Divide(2,1);  */
	c1->cd();
	h_Seed_TimeEBEB->Draw();
	fitFcn->Draw("sames");
        c1->SetLogy(0);
	//  draw the legend
    	TLegend *leg = new TLegend(0.15,0.72,0.3,0.85);
       	leg->SetTextFont(72);
        leg->SetTextSize(0.04);
        leg->AddEntry(h_Seed_TimeEBEB,"EB","lpe");
        leg->AddEntry(fitFcn,"GAUS","l");
        leg->Draw();
	c1->SaveAs("Seed_Time_DoubleElectron_Run2012A-EB-EB.png");
}       
int main (int argc, char **argv)
{
  // Get the tree

  TFile *f;

  if (argc >= 3)
    {
      f = new TFile(argv[1]);

      std::cout << ">> Opening file " << argv[1] << " ......" << std::endl;
      if (!f->IsOpen())
	{			// terminate if the file can't be opened
	  std::cerr << "!! File open error:" << argv[1] << std::endl;
	  return 1;
	}
    }
  else
    {				// terminate if there is no input file or more than 1 input file
      std::cerr << "!! No input file" << std::endl;
      return 1;
    }

  TTree *tree = (TTree*)f->Get("tree");

  // get the variables from the ntuple
  float t1gausroot = 0;
  float t2gausroot = 0;
  float t3gausroot = 0;
  float t4gausroot = 0;
  float t5gausroot = 0;
  float t6gausroot = 0;
  float t7gausroot = 0;
  float t8gausroot = 0;
  float ch1Amp = 0;
  float ch2Amp = 0;
  float ch3Amp = 0;
  float ch4Amp = 0;
  float ch5Amp = 0;
  float ch6Amp = 0;
  float ch7Amp = 0;
  float ch8Amp = 0;
  unsigned int ch1QualityBit = 0;
  unsigned int ch2QualityBit = 0;
  unsigned int ch3QualityBit = 0;
  unsigned int ch4QualityBit = 0;
  unsigned int ch5QualityBit = 0;
  unsigned int ch6QualityBit = 0;
  unsigned int ch7QualityBit = 0;
  unsigned int ch8QualityBit = 0;

  tree->SetBranchAddress("t1gausroot",&t1gausroot);
  tree->SetBranchAddress("t2gausroot",&t2gausroot);
  tree->SetBranchAddress("t3gausroot",&t3gausroot);
  tree->SetBranchAddress("t4gausroot",&t4gausroot);
  tree->SetBranchAddress("t5gausroot",&t5gausroot);
  tree->SetBranchAddress("t6gausroot",&t6gausroot);
  tree->SetBranchAddress("t7gausroot",&t7gausroot);
  tree->SetBranchAddress("t8gausroot",&t8gausroot);
  tree->SetBranchAddress("ch1Amp",&ch1Amp);
  tree->SetBranchAddress("ch2Amp",&ch2Amp);
  tree->SetBranchAddress("ch3Amp",&ch3Amp);
  tree->SetBranchAddress("ch4Amp",&ch4Amp);
  tree->SetBranchAddress("ch5Amp",&ch5Amp);
  tree->SetBranchAddress("ch6Amp",&ch6Amp);
  tree->SetBranchAddress("ch7Amp",&ch7Amp);
  tree->SetBranchAddress("ch8Amp",&ch8Amp);
  tree->SetBranchAddress("ch1QualityBit",&ch1QualityBit);
  tree->SetBranchAddress("ch2QualityBit",&ch2QualityBit);
  tree->SetBranchAddress("ch3QualityBit",&ch3QualityBit);
  tree->SetBranchAddress("ch4QualityBit",&ch4QualityBit);
  tree->SetBranchAddress("ch5QualityBit",&ch5QualityBit);
  tree->SetBranchAddress("ch6QualityBit",&ch6QualityBit);
  tree->SetBranchAddress("ch7QualityBit",&ch7QualityBit);
  tree->SetBranchAddress("ch8QualityBit",&ch8QualityBit);

  //create histograms
  TH1F *dt[6];
  TH1F *resolution[6];
  TH1F *dt_slopeCorrected[6];
  TH1F *dt_shower[6];
  TH1F *dt_shower_AmpCut[6];

  TH1F *amp_all[6];
  TH1F *amp_good[6];
  TProfile *hProfCorr[6];
  TH2F *h2DCorr[6];
  TH2F *h2DCorr_Fit[6];
  TH2F *h2DCorr_slopeCorrected[6];

  for(Int_t i = 0; i < 6; i++)
    {
      dt[i] = new TH1F(Form("dt_%d",i), Form("dt_%d",i), 1500,-3.0,3.0);
      dt_slopeCorrected[i] = new TH1F(Form("dt_slopeCorrected_%d",i), Form("dt_slopeCorrected_%d",i), 700,-3.0,3.0);
      dt_shower[i] = new TH1F(Form("dt_shower_%d",i), Form("dt_shower_%d",i), 3000,-3.0,3.0);
      dt_shower_AmpCut[i] = new TH1F(Form("dt_shower_AmpCut%d",i), Form("dt_shower_AmpCut%d",i), 3000,-3.0,3.0);
      amp_all[i] = new TH1F(Form("amp_all_%d",i), Form("amp_all_%d",i), 200,0,0.55);
      amp_good[i] = new TH1F(Form("amp_good_%d",i), Form("amp_good_%d",i), 200,0,0.55);

      h2DCorr_Fit[i] = new TH2F(Form("dt_vs_amp_2D_fit_%d",i), Form("dt_vs_amp_2D_fit_%d",i), 10, 0,0.5, 300, -3.0, 3.0);
      resolution[i] = new TH1F(Form("resolution_%d",i), Form("resolution_%d",i), 10, 0, 0.05);

      hProfCorr[i] = new TProfile(Form("dt_vs_amp_%d",i), Form("dt_vs_amp_%d",i), 100, 0,0.5, -3.0, 3.0);
      h2DCorr[i] = new TH2F(Form("dt_vs_amp_2D_%d",i), Form("dt_vs_amp_2D_%d",i), 100, 0,0.5, 300, -3.0, 3.0);
      h2DCorr_slopeCorrected[i] = new TH2F(Form("dt_vs_amp_corrected_%d",i), Form("dt_vs_amp_corrected_%d",i), 100, 0,0.5, 300, -3.0, 3.0);
    }

  std::string names[6] = {"CH1-CH2", "CH1-CH3", "CH2-CH3", "CH5-CH6", "CH5-CH7", "CH6-CH7"};
  std::string Amps[6] = {"ch2Amp", "ch3Amp", "ch3Amp", "ch6Amp", "ch7Amp", "ch7Amp"};

  std::string amps_xaxis[6] = {"CH1", "CH2", "CH3", "CH5", "CH6", "CH7"};

  //read all entries and fill the histograms
  Long64_t nentries = tree->GetEntries();

  std::cout<<"Number of events in Physics Sample: "<<nentries<<std::endl;
  
  for (Long64_t iEntry=0;iEntry<nentries;iEntry++) 
    {
      tree->GetEntry(iEntry);
      
      // any good pulses
      if( ch1QualityBit==0 && ch2QualityBit==0 )
	{
	  dt[0]->Fill(t1gausroot-t2gausroot);
	  hProfCorr[0]->Fill(ch2Amp,t1gausroot-t2gausroot);
	  h2DCorr[0]->Fill(ch2Amp,t1gausroot-t2gausroot);
	  h2DCorr_Fit[0]->Fill(ch2Amp,t1gausroot-t2gausroot);
	}

      if( ch1QualityBit==0 && ch3QualityBit==0 )
	{
	  dt[1]->Fill(t1gausroot-t3gausroot);
	  hProfCorr[1]->Fill(ch3Amp,t1gausroot-t3gausroot);
	  h2DCorr[1]->Fill(ch3Amp,t1gausroot-t3gausroot);
	  h2DCorr_Fit[1]->Fill(ch3Amp,t1gausroot-t3gausroot);
	}

      if( ch2QualityBit==0 && ch3QualityBit==0 )
	{
	  dt[2]->Fill(t2gausroot-t3gausroot);
	  hProfCorr[2]->Fill(ch3Amp,t2gausroot-t3gausroot);
	  h2DCorr[2]->Fill(ch3Amp,t2gausroot-t3gausroot);
	  h2DCorr_Fit[2]->Fill(ch3Amp,t2gausroot-t3gausroot);
	}

      if( ch5QualityBit==0 && ch6QualityBit==0 )
	{
	  dt[3]->Fill(t5gausroot-t6gausroot);
	  hProfCorr[3]->Fill(ch6Amp,t5gausroot-t6gausroot);
	  h2DCorr[3]->Fill(ch6Amp,t5gausroot-t6gausroot);
	  h2DCorr_Fit[3]->Fill(ch6Amp,t5gausroot-t6gausroot);
	}

      if( ch5QualityBit==0 && ch7QualityBit==0 )
	{
	  dt[4]->Fill(t5gausroot-t7gausroot);
	  hProfCorr[4]->Fill(ch7Amp,t5gausroot-t7gausroot);
	  h2DCorr[4]->Fill(ch7Amp,t5gausroot-t7gausroot);
	  h2DCorr_Fit[4]->Fill(ch7Amp,t5gausroot-t7gausroot);
	}

      if( ch6QualityBit==0 && ch7QualityBit==0 )
	{
	  dt[5]->Fill(t6gausroot-t7gausroot);
	  hProfCorr[5]->Fill(ch7Amp,t6gausroot-t7gausroot);
	  h2DCorr[5]->Fill(ch7Amp,t6gausroot-t7gausroot);
	  h2DCorr_Fit[5]->Fill(ch7Amp,t6gausroot-t7gausroot);
	}
      
      // amplitude plots
      amp_all[0]->Fill(ch1Amp);
      amp_all[1]->Fill(ch2Amp);
      amp_all[2]->Fill(ch3Amp);
      amp_all[3]->Fill(ch5Amp);
      amp_all[4]->Fill(ch6Amp);
      amp_all[5]->Fill(ch7Amp);

      if( ch1QualityBit==0 )
	amp_good[0]->Fill(ch1Amp);
      if( ch2QualityBit==0 )
      	amp_good[1]->Fill(ch2Amp);
      if( ch3QualityBit==0 )
      	amp_good[2]->Fill(ch3Amp);
      if( ch5QualityBit==0 )
      	amp_good[3]->Fill(ch5Amp);
      if( ch6QualityBit==0 )
      	amp_good[4]->Fill(ch6Amp);
      if( ch7QualityBit==0 )
      	amp_good[5]->Fill(ch7Amp);

      // good pulses with shower requirement
      if( ch1QualityBit==0 && ch3QualityBit==0 && ch6Amp>0.49)
	dt_shower[1]->Fill(t1gausroot-t3gausroot);

      if( ch1QualityBit==0 && ch2QualityBit==0 && ch6Amp>0.49) //cherenkov selection
	dt_shower[0]->Fill(t1gausroot-t2gausroot);

      if( ch5QualityBit==0 && ch6QualityBit==0 && ch6Amp>0.49)  //cherenkov selection
	dt_shower[3]->Fill(t5gausroot-t6gausroot);

      if( ch1QualityBit==0 && ch3QualityBit==0 && ch6Amp>0.49)
	if(ch3Amp>0.15)
	  dt_shower_AmpCut[1]->Fill(t1gausroot-t3gausroot);

    }
  
  // Touch up and save
  TCanvas * c = new TCanvas("c","c",600,600);
  for(Int_t i = 0; i < 6; i++)
    {
      c->cd();
      
      // TOFs
      gPad->SetLogy(0);
      dt[i]->SetAxisRange(dt[i]->GetMean()-0.5*fabs(dt[i]->GetMean()),dt[i]->GetMean()+0.5*fabs(dt[i]->GetMean()),"X");
      dt[i]->GetXaxis()->SetTitle(Form("%s [ns]",names[i].c_str()));
      dt[i]->SetTitle(names[i].c_str());
      dt[i]->GetYaxis()->SetTitle("Number of Events");
      dt[i]->Draw();
      dt[i]->Fit("gaus");
      TVirtualFitter * fitter = TVirtualFitter::GetFitter();
      TPaveText *pt = new TPaveText(.15,.75,.35,.85,"NDC");
      pt->AddText(Form("#sigma=%.2f psec",1000*fitter->GetParameter(2)));
      pt->SetFillColor(0);
      pt->Draw();

      c->SaveAs( Form("TOF_%s_Run%s.pdf", names[i].c_str(), argv[2]) );

      // amplitudes
      amp_good[i]->SetLineWidth(2);
      amp_good[i]->SetLineColor(1);
      amp_all[i]->SetLineWidth(3);
      amp_all[i]->SetLineColor(1);
      amp_all[i]->SetLineStyle(2);
      amp_all[i]->SetStats(0);
      amp_all[i]->Draw();
      amp_all[i]->GetXaxis()->SetTitle(Form("%s  Amp [mV]", amps_xaxis[i].c_str()));
      amp_all[i]->GetYaxis()->SetTitle("Number of Events");
      amp_all[i]->Draw();
      amp_good[i]->SetLineColor(1);
      amp_good[i]->Draw("same");
      TLegend *leg = new TLegend(0.5,0.8,0.8,0.9);
      leg->AddEntry(amp_all[i],"All pulses");
      leg->AddEntry(amp_good[i],"Pass all quality bits");
      leg->SetFillColor(0);
      leg->Draw();
      gPad->SetLogy();
  

      c->SaveAs( Form("Amplitudes_%s_Run%s.root", amps_xaxis[i].c_str(), argv[2]) );
    }
  
  gPad->SetLogy(0);
  // shower requirement
  for(Int_t i = 0; i < 4; i++)
    {
      c->cd();
      
      if(i==2) continue;

      dt_shower[i]->SetAxisRange(dt_shower[i]->GetMean()-0.2*fabs(dt_shower[i]->GetMean()),
				 dt_shower[i]->GetMean()+0.2*fabs(dt_shower[i]->GetMean()),"X");
      dt_shower[i]->GetXaxis()->SetTitle(Form("%s [ns]",names[i].c_str()));
      dt_shower[i]->SetTitle(names[i].c_str());
      dt_shower[i]->GetYaxis()->SetTitle("Number of Events");
      dt_shower[i]->Draw();
      dt_shower[i]->SetLineColor(1);
      dt_shower[i]->SetStats(0);
      dt_shower[i]->SetTitle("");
      dt_shower[i]->Draw();
      dt_shower[i]->Fit("gaus");
      dt_shower[i]->GetFunction("gaus")->SetLineColor(1);
      dt_shower[i]->GetFunction("gaus")->SetLineWidth(4);


      TVirtualFitter * fitter = TVirtualFitter::GetFitter();
      TPaveText *pt = new TPaveText(.15,.75,.35,.85,"NDC");
      pt->AddText(Form("#sigma=%.2f psec",1000*fitter->GetParameter(2)));
      pt->SetFillColor(0);
      pt->Draw();

      c->SaveAs( Form("TOF_Shower_%s_Run%s.root", names[i].c_str(), argv[2]) );
    }

  c->cd();
  dt_shower_AmpCut[1]->SetAxisRange(dt_shower_AmpCut[1]->GetMean()-0.5*fabs(dt_shower_AmpCut[1]->GetMean()),
				    dt_shower_AmpCut[1]->GetMean()+0.5*fabs(dt_shower_AmpCut[1]->GetMean()),"X");
  dt_shower_AmpCut[1]->GetXaxis()->SetTitle(Form("%s [ns]",names[1].c_str()));
  dt_shower_AmpCut[1]->SetTitle(names[1].c_str());
  dt_shower_AmpCut[1]->GetYaxis()->SetTitle("Number of Events");
  dt_shower_AmpCut[1]->Draw();
  dt_shower_AmpCut[1]->Fit("gaus");
  TVirtualFitter * fitter3 = TVirtualFitter::GetFitter();
  TPaveText *pt2 = new TPaveText(.15,.75,.35,.85,"NDC");
  pt2->AddText(Form("#sigma=%.2f psec",1000*fitter3->GetParameter(2)));
  pt2->SetFillColor(0);
  pt2->Draw();

  c->SaveAs( Form("TOF_Shower_AmpCut_%s_Run%s.pdf", names[1].c_str(), argv[2]) );

  // slopes
  TF1 * slopes[6];
  for(Int_t i = 0; i < 6; i++)
    {
      slopes[i] = new TF1(Form("slopes_%d",i),"pol1", 0, h2DCorr[i]->GetNbinsX());
      slopes[i]->SetLineColor(1);
      slopes[i]->SetLineWidth(3);
    }

  for(Int_t i = 0; i < 6; i++)
    {
      c->cd();

      hProfCorr[i]->Fit(slopes[i],"Q","", 0, h2DCorr[i]->GetNbinsX());

      UInt_t Number = 3;
      Double_t Red[3]   = { 0.15, 0.6, 0.9};
      Double_t Green[3] = { 0.15, 0.6, 0.9};
      Double_t Blue[3]  = { 0.15, 0.6, 0.9};
      Double_t Stops[3] = { 0.00, 0.25, 1.0};
      
      Int_t nb=50;
      TColor::CreateGradientColorTable(Number,Stops,Red,Green,Blue,nb);
      
      h2DCorr[i]->Draw("colz");
      h2DCorr[i]->SetLineColor(1);
      h2DCorr[i]->SetAxisRange(h2DCorr[i]->GetMean(2) - 0.3*fabs(h2DCorr[i]->GetMean(2)),
			       h2DCorr[i]->GetMean(2) + 0.3*fabs(h2DCorr[i]->GetMean(2)),"Y");
      h2DCorr[i]->SetAxisRange(0, GetLastXBin(h2DCorr[i]) + 0.05,"X");
      h2DCorr[i]->GetYaxis()->SetTitle(Form("Time Difference %s", names[i].c_str()));
      h2DCorr[i]->GetXaxis()->SetTitle(Form("%s", Amps[i].c_str()));
      h2DCorr[i]->SetTitle("");
      h2DCorr[i]->SetStats(0);
      hProfCorr[i]->SetLineColor(1);
      hProfCorr[i]->SetMarkerStyle(8);

      hProfCorr[i]->Draw("same");
      
      c->SaveAs( Form("TOF_vs_Amp_%s_%s_Run%s.pdf", names[i].c_str(), Amps[i].c_str(), argv[2]) );

      
      // resolution vs amplitude plots
      for(int j = 0; j < h2DCorr_Fit[i]->GetNbinsX(); j++)
	{
	  TH1D *py = h2DCorr_Fit[i]->ProjectionY("py", j, j + 1 ); 
	  py->Fit("gaus");
	  TVirtualFitter * fitter22 = TVirtualFitter::GetFitter();
	  resolution[i] -> SetBinContent(j, 1000*fitter22->GetParameter(2));
	  if (1000*fitter22->GetParameter(2) > 100. ) 
	    resolution[i] -> SetBinContent(j, 0.0);
	}
      resolution[i]->GetXaxis()->SetTitle(Form("%s", Amps[i].c_str()));
      resolution[i]->GetYaxis()->SetTitle(Form("Resolution in %s [psec]", names[i].c_str()));
      resolution[i]->Draw();
	    
      c->SaveAs( Form("Resolution_vs_Amp_%s_%s_Run%s.pdf", names[i].c_str(), Amps[i].c_str(), argv[2]) );
    }

  // correction for slopes
  std::cout<<"Second round: slope correction "<<nentries<<std::endl;
  
  for (Long64_t iEntry=0;iEntry<nentries;iEntry++) 
    {
      tree->GetEntry(iEntry);
      
      // any good pulses
      if( ch1QualityBit==0 && ch3QualityBit==0 && ch6Amp>0.49)
	{
	  float a = slopes[1]->GetParameter(0);
	  float b = slopes[1]->GetParameter(1);
	  dt_slopeCorrected[1]->Fill(t1gausroot-t3gausroot + (a+b*0.02) - (a+b*ch3Amp));
	  h2DCorr_slopeCorrected[1]->Fill(ch3Amp,t1gausroot-t3gausroot + (a+b*0.02) - (a+b*ch3Amp));
	}
    }
  
  c->cd();
  dt_slopeCorrected[1]->SetAxisRange(dt_slopeCorrected[1]->GetMean()-0.2*fabs(dt_slopeCorrected[1]->GetMean()),
				     dt_slopeCorrected[1]->GetMean()+0.2*fabs(dt_slopeCorrected[1]->GetMean()),"X");
  dt_slopeCorrected[1]->GetXaxis()->SetTitle(Form("%s [ns]",names[1].c_str()));
  dt_slopeCorrected[1]->SetTitle(names[1].c_str());
  dt_slopeCorrected[1]->GetYaxis()->SetTitle("Number of Events");
  dt_slopeCorrected[1]->SetLineColor(1);
  // dt_slopeCorrected[1]->SetStats(0);
  dt_slopeCorrected[1]->SetTitle("");
  dt_slopeCorrected[1]->Draw();
  dt_slopeCorrected[1]->Fit("gaus");
  dt_slopeCorrected[1]->GetFunction("gaus")->SetLineColor(1);
  dt_slopeCorrected[1]->GetFunction("gaus")->SetLineWidth(4);
  TVirtualFitter * fitter2 = TVirtualFitter::GetFitter();
  TPaveText *pt1 = new TPaveText(.15,.75,.35,.85,"NDC");
  pt1->AddText(Form("#sigma=%.2f psec",1000*fitter2->GetParameter(2)));
  pt1->SetFillColor(0);
  pt1->Draw();
  
  c->SaveAs( Form("TOF_SlopeCorrected_%s_Run%s.pdf", names[1].c_str(), argv[2]) );
  
  // 2D
  c->cd();
  
  h2DCorr_slopeCorrected[1]->Draw("colz");
  h2DCorr_slopeCorrected[1]->SetAxisRange(h2DCorr_slopeCorrected[1]->GetMean(2) - 0.7*fabs(h2DCorr_slopeCorrected[1]->GetMean(2)),
  			   h2DCorr_slopeCorrected[1]->GetMean(2) + 0.7*fabs(h2DCorr_slopeCorrected[1]->GetMean(2)),"Y");
  h2DCorr_slopeCorrected[1]->SetAxisRange(0, GetLastXBin(h2DCorr_slopeCorrected[1]) + 0.05,"X");
  h2DCorr_slopeCorrected[1]->GetYaxis()->SetTitle(Form("Time Difference %s", names[1].c_str()));
  h2DCorr_slopeCorrected[1]->GetXaxis()->SetTitle(Form("%s", Amps[1].c_str()));
  
  c->SaveAs( Form("TOF_vs_Amp_Corrected_%s_%s_Run%s.pdf", names[1].c_str(), Amps[1].c_str(), argv[2]) );
 
}
Exemplo n.º 10
0
void factorizeCorrs(){
	
	bool doSpillover = false;
	
	const double xTrkBinDouble[11] = {0.5,0.7,1.,2.,3.,4.,8.,12.,16.,20.,30.};
	const string xCentBins[5] = {"Cent0", "Cent10", "Cent30","Cent50", "Cent100"};
	const string xTrkBinStr[11] = {"TrkPt05","TrkPt07","TrkPt1","TrkPt2","TrkPt3","TrkPt4","TrkPt8","TrkPt12","TrkPt16","TrkPt20","TrkPt300"};
	
	TFile *fsum;
	//if(!doSpillover) fsum = new TFile("JFFcorrs_PythHydjet_sube0_finalJFFJEC_CymbalTune_finalCymbalCorrs_withFits.root");
	if(!doSpillover) fsum = new TFile("JFFcorrs_PythHydjet_pTweighted_sube0_finalJFFJEC_withFits.root");
	else fsum = new TFile("JFFcorrs_PythiaHydjet_subeNon0_finalJFFJEC_CymbalTune_finalCymbalCorrs_eta1p5_withFits.root");
	
	TFile *fq = new TFile("JFFcorrs_PythiaHydjet_sube0_QuarkJets_finalJFFJEC_withFits.root");
	TFile *fg = new TFile("JFFcorrs_PythiaHydjet_sube0_GluonJets_finalJFFJEC_withFits.root");
	TFile *fhal = new TFile("/Users/kjung/Downloads/Inclusive_Hydjet_JFFResiduals.root");
	TFile *fhalSpill = new TFile("/Users/kjung/Downloads/Inclusive_Hydjet_SpillOvers.root");
	
	//TFile *fout;
	//if(doSpillover){
	//	fout = new TFile("JFFcorrs_spilloverFromsube0_newJFFs.root","recreate");
	//	fout->cd();
	//}
	TH2D *hnum[10][4], *hden[10][4];
	TH1D *fp1[10][4];
	
	TH2D *hq[10][4];
	TH2D *hg[10][4];
	
	TH1D *fpq[10][4];
	TH1D *fpg[10][4];
	
	TH1D *fh[10][4];
	
	TLatex *labels[4];
	TCanvas *cc = new TCanvas("cc","",2000,1600);
	cc->Divide(4,8);
	TLatex *labels2[10][4];
	
	TH1D *ptClosure[4];
	TH1D *ptClosureFit[4];
	TH1D *gptClosure[4];
	TH1D *qptClosure[4];
	TH1D *hptClosure[4];
	
	TF1 *gausFit[10][4];
	TF1 *gausFitg[10][4];
	TF1 *gausFitq[10][4];
	
	double *covMatrix[10][4];
	double *qcovMatrix[10][4];
	double *gcovMatrix[10][4];
	
	for(int j=0; j<4; j++){
		
		ptClosureFit[j] = new TH1D(Form("ptClosureFit_%d",j),"",10,xTrkBinDouble); ptClosureFit[j]->Sumw2();
		ptClosure[j] = new TH1D(Form("ptClosure_%d",j),"",10,xTrkBinDouble); ptClosure[j]->Sumw2();
		gptClosure[j] = new TH1D(Form("gptClosureFit_%d",j),"",10,xTrkBinDouble); gptClosure[j]->Sumw2();
		qptClosure[j] = new TH1D(Form("qptClosure_%d",j),"",10,xTrkBinDouble); qptClosure[j]->Sumw2();
		
		hptClosure[j] = new TH1D(Form("hptClosure_%d",j),"",10,xTrkBinDouble); hptClosure[j]->Sumw2();
		if(doSpillover){
			TGraphErrors *f1temp = (TGraphErrors*)fhalSpill->Get(Form("Integrals_%s_%s",xCentBins[j].c_str(),xCentBins[j+1].c_str()));
			cout << "getting " << Form("Integrals_%s_%s",xCentBins[j].c_str(),xCentBins[j+1].c_str()) << endl;
			for(int ibin=0; ibin<9; ibin++){
				cout << "ibin " << ibin << endl;
				cout << " content: "<< f1temp->GetY()[ibin] << endl;
				cout << "error: "<< f1temp->GetEY()[ibin] << endl;
				hptClosure[j]->SetBinContent(ibin+2, f1temp->GetY()[ibin]);
				if(f1temp->GetEY()[ibin]) hptClosure[j]->SetBinError(ibin+2, f1temp->GetEY()[ibin]);
				else hptClosure[j]->SetBinError(ibin+1, 0.0001);
			}
		}
				
		for(int i=0; i<10; i++){
			
			hnum[i][j] = (TH2D*)fsum->Get(Form("JFFcorrs_cent%d_pt%d",j,i))->Clone(Form("den_cent%d_pt%d",j,i));
			
			hq[i][j] = (TH2D*)fq->Get(Form("JFFcorrs_cent%d_pt%d",j,i))->Clone(Form("hq_jffCorr_cent%d_pt%d",j,i));
			hg[i][j] = (TH2D*)fg->Get(Form("JFFcorrs_cent%d_pt%d",j,i))->Clone(Form("hg_jffCorr_cent%d_pt%d",j,i));
			
			//if(i>0) fh[i][j] = (TH1D*)fhal->Get(Form("JFF_Residual_Eta_%s_%s_Pt100_Pt300_%s_%s",xCentBins[j].c_str(),xCentBins[j+1].c_str(),xTrkBinStr[i].c_str(),xTrkBinStr[i+1].c_str()))->Clone(Form("fh_cent%d_pt%d",j,i));
			
			//if(doSpillover){
			//	hnum[i][j]->Add(hden[i][j],-1);
			//	hnum[i][j]->Write();
			//}
			//else hnum[i][j] = hden[i][j];
			//hnum[i][j] = hden[i][j];
			
			gausFit[i][j] = new TF1(Form("gausFit_%d_%d",i,j),"gaus+[3]",-1,1);
			gausFit[i][j]->SetParLimits(0,0,1);
			gausFit[i][j]->SetParLimits(2,9e-2,5e-1);
			gausFit[i][j]->FixParameter(1,0);
			if(i<4) gausFit[i][j]->FixParameter(3,0);
			
			gausFitq[i][j] = new TF1(Form("qgausFit_%d_%d",i,j),"gaus+[3]",-1,1);
			gausFitg[i][j] = new TF1(Form("ggausFit_%d_%d",i,j),"gaus+[3]",-1,1);
			gausFitq[i][j]->SetParLimits(0,0,1);
			gausFitq[i][j]->SetParLimits(2,9e-2,5e-1);
			gausFitq[i][j]->FixParameter(1,0);
			if(i<4) gausFitq[i][j]->FixParameter(3,0);
			gausFitg[i][j]->SetParLimits(0,0,1);
			gausFitg[i][j]->SetParLimits(2,9e-2,5e-1);
			gausFitg[i][j]->FixParameter(1,0);
			if(i<4) gausFitg[i][j]->FixParameter(3,0);

			if(i>0 && i<10){
				cc->cd(i*4+(3-j)+1-4);
				int lowbin = hnum[i][j]->GetYaxis()->FindBin(-2.5);
				int hibin = hnum[i][j]->GetYaxis()->FindBin(2.5);
				fp1[i][j] = (TH1D*)hnum[i][j]->ProjectionX(Form("ipfx_%d%d",i,j),lowbin,hibin,"e");
				fpq[i][j] = (TH1D*)hq[i][j]->ProjectionX(Form("qpfx_%d%d",i,j),0,-1,"e");
				fpg[i][j] = (TH1D*)hg[i][j]->ProjectionX(Form("gpfx_%d%d",i,j),0,-1,"e");
				
				fp1[i][j]->Rebin(5);
				fpq[i][j]->Rebin(5);
				fpg[i][j]->Rebin(5);
				
				/*fp1[i][j]->Scale(1./fp1[i][j]->GetBinWidth(2)/ptClosure[j]->GetBinWidth(i+1));
				fpq[i][j]->Scale(1./fpq[i][j]->GetBinWidth(2)/ptClosure[j]->GetBinWidth(i+1));
				fpg[i][j]->Scale(1./fpg[i][j]->GetBinWidth(2)/ptClosure[j]->GetBinWidth(i+1));*/
				
				if(doSpillover){
					fp1[i][j]->Fit(gausFit[i][j],"BqN0","",-1.5,1.5);
					TVirtualFitter *fitter = TVirtualFitter::GetFitter();
					assert(fitter!=0);
					covMatrix[i][j] = fitter->GetCovarianceMatrix();
					fpg[i][j]->Fit(gausFitg[i][j],"BqN0","",-1.5,1.5);				
					fpq[i][j]->Fit(gausFitq[i][j],"BqN0","",-1.5,1.5);
				}
				fp1[i][j]->SetLineColor(1);
				fpq[i][j]->SetLineColor(4);
				fpg[i][j]->SetLineColor(2);
				fp1[i][j]->GetXaxis()->SetRangeUser(-2.5,2.5);
				fp1[i][j]->GetYaxis()->SetNdivisions(505);
				fp1[i][j]->GetYaxis()->SetLabelSize(0.15);
				fp1[i][j]->GetXaxis()->SetLabelSize(0.15);
				fp1[i][j]->SetMaximum(fpg[i][j]->GetMaximum()*1.5);
				fp1[i][j]->SetMinimum(fpq[i][j]->GetMinimum()*1.5);
				
				//fh[i][j]->SetMarkerColor(kMagenta-2);
				
				if(!doSpillover){
					fp1[i][j]->Scale(1./fp1[i][j]->GetBinWidth(1)/ptClosure[j]->GetBinWidth(i+1));
					fpq[i][j]->Scale(1./fpq[i][j]->GetBinWidth(1)/ptClosure[j]->GetBinWidth(i+1));
					fpg[i][j]->Scale(1./fpg[i][j]->GetBinWidth(1)/ptClosure[j]->GetBinWidth(i+1));
				}
				
				fp1[i][j]->Draw();
				//fpq[i][j]->Divide(fp1[i][j]);
				//fpq[i][j]->Draw("same");
				//fpg[i][j]->Divide(fp1[i][j]);
				fpg[i][j]->Draw("same");
				//fh[i][j]->Draw("same");
								
				labels2[i][j] = new TLatex(-1,fp1[i][j]->GetMaximum()*0.65,Form("%f < pt < %f, %s-%s",xTrkBinDouble[i],xTrkBinDouble[i+1],xCentBins[j].c_str(),xCentBins[j+1].c_str()));
				labels2[i][j]->SetTextSize(0.15);
				labels2[i][j]->Draw("same");
			
				double integrErr =0.;
				int lowbin2 = fp1[i][j]->FindBin(-1.5);
				int highbin2 = fp1[i][j]->FindBin(1.5);
				double integr = fp1[i][j]->IntegralAndError(lowbin2, highbin2, integrErr, "width");
				double integr2, integrErr2;
				double gInteg, qInteg;
				if(doSpillover){
					integr = gausFit[i][j]->Integral(-1.5,1.5);// - gausFit[i][j]->GetParameter(3)*2.;
					integrErr = calcIntegralError(gausFit[i][j]);
					
					cout << "integral error: "<< integrErr << endl;
					
					gInteg = gausFitg[i][j]->Integral(-1.5,1.5);// - gausFitg[i][j]->GetParameter(3)*2.;
					qInteg = gausFitq[i][j]->Integral(-1.5,1.5);// - gausFitq[i][j]->GetParameter(3)*2.;
				}
				else{
					gInteg = fpg[i][j]->Integral(lowbin2, highbin2,"width");
					qInteg = fpq[i][j]->Integral(lowbin2, highbin2,"width");
				}				
				
				ptClosure[j]->SetBinContent(i+1, integr);///ptClosure[j]->GetBinWidth(i+1));
				cout << "eta Bin " << ptClosure[j]->GetBinCenter(i+1) << " content: "<< integr << endl;
				if(doSpillover) ptClosure[j]->SetBinContent(i+1, ptClosure[j]->GetBinContent(i+1)/fp1[i][j]->GetBinWidth(2)/ptClosure[j]->GetBinWidth(i+1));
				ptClosure[j]->SetBinError(i+1, integrErr);///ptClosure[j]->GetBinWidth(i+1));
				
				//ptClosureFit[j]->SetBinContent(i+1, integr2/ptClosureFit[j]->GetBinWidth(i+1)/fp1[i][j]->GetBinWidth(2));
				//ptClosureFit[j]->SetBinError(i+1, integrErr2/ptClosureFit[j]->GetBinWidth(i+1)/fp1[i][j]->GetBinWidth(2));
				
				gptClosure[j]->SetBinContent(i+1, gInteg);///ptClosure[j]->GetBinWidth(i+1));
				if(doSpillover) gptClosure[j]->SetBinContent(i+1, gptClosure[j]->GetBinContent(i+1)/fpg[i][j]->GetBinWidth(2)/ptClosure[j]->GetBinWidth(i+1));
				gptClosure[j]->SetBinError(i+1, ptClosure[j]->GetBinError(i+1));
				
				qptClosure[j]->SetBinContent(i+1, qInteg);///ptClosure[j]->GetBinWidth(i+1));
				if(doSpillover) qptClosure[j]->SetBinContent(i+1, qptClosure[j]->GetBinContent(i+1)/fpq[i][j]->GetBinWidth(2)/ptClosure[j]->GetBinWidth(i+1));
				qptClosure[j]->SetBinError(i+1, ptClosure[j]->GetBinError(i+1));
				
				int hbinlow = fh[i][j]->FindBin(-1.5);
				int hbinhi = fh[i][j]->FindBin(1.5);
							
				if(!doSpillover){	
					hptClosure[j]->SetBinContent(i+1, fp1[i][j]->IntegralAndError(hbinlow,hbinhi,integrErr,"width"));
					hptClosure[j]->SetBinError(i+1, integrErr);
				}
								
				cout << "cent bin " << j << " pt bin " << i << " integral: " << ptClosure[j]->GetBinContent(i+1) << " error: "<< ptClosure[j]->GetBinError(i+1) << endl;
				cout << "cent bin " << j << " pt bin " << i << " gluon integral: " << gInteg << endl;
				cout << "cent bin " << j << " pt bin " << i << " quark integral: " << qInteg << endl;
				cout << "cent bin " << j << " pt bin " << i << " hallie integral: " << hptClosure[j]->GetBinContent(i+1) << endl;
			}
		}
	}
	
	TCanvas *c2 = new TCanvas("c2","",2000,400);
	c2->Divide(4,1);
	for(int j=0; j<4; j++){
		c2->cd(4-j);
		//if(doSpillover) ptClosure[j] = ptClosureFit[j];
		ptClosure[j]->SetMaximum(0.7);
		if(doSpillover) ptClosure[j]->SetMaximum(2.8);
		ptClosure[j]->SetMinimum(-0.2-1*(!doSpillover));
		ptClosure[j]->SetXTitle("Track p_{T} (GeV/c)");
		if(!doSpillover) ptClosure[j]->SetYTitle("JFF Correction");
		else ptClosure[j]->SetYTitle("Spillover Correction");
		//ptClosure[j]->Divide(qptClosure[j]);
		ptClosure[j]->Draw();
		//ptClosureFit[j]->SetMarkerColor(2);
		//ptClosureFit[j]->SetLineColor(2);
		//if(doSpillover) ptClosureFit[j]->Draw("");
		gptClosure[j]->SetMarkerColor(2);
		//gptClosure[j]->SetYTitle("New/Old JFF Corrections");
		gptClosure[j]->SetXTitle("Track p_{T} (GeV/c)");
		//gptClosure[j]->Add(ptClosure[j],-1);
		//gptClosure[j]->SetMaximum(0.4);
		//gptClosure[j]->SetMinimum(-0.4);
		gptClosure[j]->Draw("same");
		qptClosure[j]->SetMarkerColor(4);
		//qptClosure[j]->Add(ptClosure[j],-1);
		qptClosure[j]->Draw("same");
		hptClosure[j]->SetMarkerStyle(20);
		hptClosure[j]->SetMarkerColor(kMagenta+2);
		//hptClosure[j]->Draw("Same");
		labels[j] = new TLatex(3,ptClosure[j]->GetMaximum()*0.75,Form("%s-%s",xCentBins[j].c_str(),xCentBins[j+1].c_str()));
		labels[j]->SetTextSize(0.06);
		labels[j]->Draw("same");
		if(j==0){
			cout << endl;
			for(int ibin=1; ibin<=qptClosure[j]->GetNbinsX(); ibin++){
				cout << qptClosure[j]->GetBinContent(ibin) << ", ";
			}
			cout << endl;
		}
	}
	
	/*TFile *fout = new TFile("Spillover_gausFits.root","recreate");
	fout->cd();
	for(int j=0; j<4; j++){
		for(int i=0; i<10; i++){
			gausFit[i][j]->Write();
		}
	}
	fout->Close();*/
			
}
void makeRisetimeDistributionT9(string filename, string plotname, string plotTitle,
			      double ampCutOnMCP, double ampCutOnLYSO, double ampCutOnTrigger,
			    double beamXMin, double beamXMax, double beamYMin, double beamYMax,
			    int nbins, double xmin, double xmax, double fitmin, double fitmax) {


  TFile *inputfile = TFile::Open(filename.c_str(),"READ");
  
  TTree *tree = (TTree*)inputfile->Get("t1065");

  // get the variables from the ntuple
  float amp[36];
  float risetime[36];
  float gauspeak[36];
  float linearTime30[36];
  float beamX;
  float beamY;

  tree->SetBranchStatus("*",0);
  tree->SetBranchStatus("gauspeak",1);
  tree->SetBranchStatus("amp",1);
  tree->SetBranchStatus("risetime",1);
  tree->SetBranchStatus("linearTime30",1);
  tree->SetBranchStatus("TDCx",1);
  tree->SetBranchStatus("TDCy",1);
  tree->SetBranchAddress("gauspeak",gauspeak);
  tree->SetBranchAddress("amp",amp);
  tree->SetBranchAddress("risetime",risetime);
  tree->SetBranchAddress("linearTime30",linearTime30);
  tree->SetBranchAddress("TDCx",&beamX);
  tree->SetBranchAddress("TDCy",&beamY);

  //create histograms
  TH1F *histRisetime;
  histRisetime = new TH1F("histRisetime","; Integrated Charge [pC];Number of Events", nbins, xmin, xmax);

  
  //read all entries and fill the histograms
  Long64_t nentries = tree->GetEntries();

  std::cout<<"Number of events in Sample: "<<nentries<<std::endl;  
  for (Long64_t iEntry=0;iEntry<nentries;iEntry++) {
    if (iEntry %1000 == 0) 
      cout << "Processing Event " << iEntry << "\n";
    tree->GetEntry(iEntry);    
    // cout << "here1\n";
    float MCPTimeGauss = gauspeak[0];
    float CdTeTime = linearTime30[1];
    float MCPAmp = amp[0];
    float LYSOAmp = amp[2];
    float TriggerAmp = amp[3];
    float CherenkovAmp = amp[7];
    float CdTeAmp = amp[1]*(1.0/63.0957);
    float CdTeRisetime = risetime[1];
    // cout << "here2\n";
       
    //use MCP amplitude cut for electron ID
    //cout << "test: " << MCPAmp << " " << siliconIntegral << "\n";
    if( !(MCPAmp > ampCutOnMCP)) continue;
    if( !(TriggerAmp > ampCutOnTrigger)) continue;
    if( !(LYSOAmp > ampCutOnLYSO)) continue;
    if(!(beamX > beamXMin && beamX < beamXMax)) continue;
    if(!(beamY > beamYMin && beamY < beamYMax)) continue;
     // cout << "here3\n";

    //don't fill overflow bins
    //if (1000* siliconIntegral * attenuationFactor / amplificationFactor > xmax) continue;
    
    histRisetime->Fill( CdTeRisetime );

    //cout << CdTeRisetime << " " << beamX << " " << beamY << " " << CdTeAmp << "\n";

    //cout << 1000* amp[21] << " : " << amplificationFactor << " : " << siliconIntegral * attenuationFactor / amplificationFactor << "\n";
 
  }


  TCanvas * c = 0;


  //Energy plot
  c = new TCanvas("c","c",600,600);  
  c->SetRightMargin(0.05);
  c->SetLeftMargin(0.17);
  histRisetime->SetAxisRange(xmin,xmax,"X");
  histRisetime->SetTitle("");
  histRisetime->GetXaxis()->SetTitle("Risetime [ns]");
  histRisetime->GetXaxis()->SetTitleSize(0.045);
  histRisetime->GetXaxis()->SetLabelSize(0.045);
  histRisetime->GetYaxis()->SetTitle("Number of Events");
  histRisetime->GetYaxis()->SetTitleOffset(1.3);
  histRisetime->GetYaxis()->SetTitleSize(0.05);
  histRisetime->GetYaxis()->SetLabelSize(0.045);
  histRisetime->GetYaxis()->SetLabelOffset(0.015);
  histRisetime->GetYaxis()->SetTitleOffset(1.7);
  histRisetime->SetMaximum(1.2*histRisetime->GetMaximum());
  histRisetime->Draw();
  histRisetime->SetStats(0);
  histRisetime->Fit("gaus","","",fitmin,fitmax);
  TVirtualFitter * fitter = TVirtualFitter::GetFitter();
  
  TLatex *tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSize(0.050);
  tex->SetTextFont(42);
  tex->SetTextColor(kBlack);
  tex->DrawLatex(0.45, 0.85, Form("Mean = %.2f %s",fitter->GetParameter(1),"ns"));
  tex->DrawLatex(0.45, 0.80, Form("#sigma = %.2f %s",fitter->GetParameter(2),"ns"));

  tex->DrawLatex(0.18, 0.93, Form("%s", plotTitle.c_str()));

  c->SaveAs( Form("%s_risetime.gif", plotname.c_str()) );
  c->SaveAs( Form("%s_risetime.pdf", plotname.c_str()) );
 

}
void makegraph_xyhits_mchamp1000(){

  //bool save_plots = false;
  bool save_plots = true;

  TCanvas* canvas = new TCanvas("c1","c1",10,10,700,550);
  //canvas_style(canvas);

  //TH2* h1=new TH2F("h1","",2000,0,2000,2000,-1000,1000);
  TH2* h1=new TH2F("h1","",1000,-1000,0,1000,0,1000);
  h1->SetStats(kFALSE);
  h1->SetTitle(";x [cm];y [cm]");
  //h2_style(h1,3,1,1,1001,50,-1111.,-1111.,510,510,20,1,1.4,0);

  const Int_t n_hits = 20;
  Float_t x[n_hits] = {-522.992,
		       -524.292,
		       -525.592,
		       -526.892,
		       -606.525,
		       -607.825,
		       -609.124,
		       -610.424,
		       -630.144,
		       -631.444,
		       -632.744,
		       -634.044,
		       -741.681,
		       -743.086,
		       -744.378,
		       -745.665,
		       -765.758,
		       -767.126,
		       -768.413,
		       -769.755};
  
  Float_t y[n_hits] = {82.024,
		       82.388,
		       82.661,
		       82.971,
		       101.400,
		       101.678,
		       101.929,
		       102.318,
		       106.826,
		       107.214,
		       107.421,
		       107.769,
		       132.755,
		       132.924,
		       133.286,
		       133.657,
		       138.406,
		       138.637,
		       139.007,
		       139.285};

  graph = new TGraph(n_hits, x, y);
  //gr_style(graph,1,1,1,1001,50,-1111,-1111,510,510,20,1,1.3,1);
  graph->SetMarkerStyle(20);
  graph->SetMarkerSize(1);
  graph->SetMarkerColor(1);
  graph->SetTitle(";x [cm];y [cm]");
  //graph->GetYaxis()->SetRangeUser(0,20);


  //Fit a circle to the graph points
  TVirtualFitter::SetDefaultFitter("Minuit");  //default is Minuit
  TVirtualFitter *fitter = TVirtualFitter::Fitter(0, 3);
  Int_t a,c;
  Double_t b,f,par;
  fitter->SetFCN(myfcn);

  fitter->SetParameter(0, "x0",   0,    0.1, -1000, 1000);
  fitter->SetParameter(1, "y0",   1000, 0.1, 0,     2000);
  fitter->SetParameter(2, "R",    1000, 0.1, 0,     1000);

  Double_t arglist[1] = {0};
  fitter->ExecuteCommand("MIGRAD", arglist, 0);

  //Draw the circle on top of the points
  TArc *arc = new TArc(fitter->GetParameter(0),
		       fitter->GetParameter(1),fitter->GetParameter(2));
  arc->SetLineColor(kRed);
  arc->SetLineWidth(4);



  Leg1 = new TLegend(0.45,0.75,0.75,0.85);
  //Leg1->AddEntry(graph_noChaCut,"Average Before TS","p");
  Leg1->AddEntry(graph,"After TS","p");
  //Leg1->AddEntry(graph_predicted,"Predicted After TS","p");
  Leg1->SetBorderSize(0);
  Leg1->SetTextSize(0.04);
  Leg1->SetFillColor(0);


  //TPaveLabel *text1 = new TPaveLabel(.17,.85,.37,.89,"CMS Preliminary    #sqrt{s}=8 TeV","NDC");
  //TPaveLabel *text1 = new TPaveLabel(.17,.85,.37,.89,"CMS Preliminary    #sqrt{s}=8 TeV    3.4 fb^{-1}","NDC");
  //TPaveLabel *text1 = new TPaveLabel(.17,.85,.37,.89,"CMS Preliminary    #sqrt{s}=8 TeV    4.4 fb^{-1}","NDC");
  TPaveLabel *text1 = new TPaveLabel(.17,.85,.37,.89,"CMS Preliminary    #sqrt{s}=8 TeV","NDC");
  text1->SetBorderSize(0);
  text1->SetTextSize(0.7);
  text1->SetFillColor(0);

  TPaveLabel *text2 = new TPaveLabel(.17,.85,.37,.89,"1000 GeV H++, Event 58654","NDC");
  text2->SetBorderSize(0);
  text2->SetTextSize(0.7);
  text2->SetFillColor(0);


  TPaveText* text1a = new TPaveText(-500,500,-300,700);
  text1a->SetBorderSize(0);
  text1a->SetTextSize(0.05);
  text1a->SetFillColor(0);
  double p0  = fitter->GetParameter(0);
  double p1  = fitter->GetParameter(1);
  double p2  = fitter->GetParameter(2);
  double e0  = fitter->GetParError(0);
  double e1  = fitter->GetParError(1);
  double e2  = fitter->GetParError(2);
  char p0name[50], p1name[50], p2name[50];
  sprintf(p0name,"x0 = %.2f #pm %.2f",p0,e0);
  sprintf(p1name,"y0 = %.2f #pm %.2f",p1,e1);
  sprintf(p2name,"R = %.2f #pm %.2f",p2,e2);
  text1a->AddText(p0name);
  text1a->AddText(p1name);
  text1a->AddText(p2name);


  canvas->cd();
  h1->Draw();
  arc->Draw("same");
  graph->Draw("Psame");
  //text1->Draw();
  text1a->Draw();
  text2->Draw();
  //Leg1->Draw();
  if(save_plots) canvas->SaveAs("../plots/hits_xy_mchamp1000.eps");

  //return 0;

}
Exemplo n.º 13
0
void ratioPlots_Zxx()
{

  // llbb_Mass_reco mfJetEta_450_600 mfJetEta_250_300 lljjMass_reco mjj_HighMass_reco drll_HighMass_reco

   TString Variable = "Zxx_Mass_reco";
//   TString Variable2 = "Zbb_Mass_reco";
   TString x_title = "M_{llxx}";
   Int_t N_Rebin = 10;

   Double_t yTopLimit = 3;

   TFile *f1 = TFile::Open("/home/fynu/amertens/storage/test/MG_PY6_/output/MG_PY6_/MG_PY6v9.root");
   TH1D *h1 = (TH1D*)f1->Get(Variable);
   h1->Sumw2();
//   h1->Add((TH1D*)f1->Get(Variable2));
   h1->SetDirectory(0);
   f1->Close();

   TFile *f2 = TFile::Open("/home/fynu/amertens/storage/test/aMCNLO_PY8_/output/aMCNLO_PY8_/aMCNLO_PY8v9.root");
   TH1D *h2 = (TH1D*)f2->Get(Variable);
   h2->Sumw2();
//   h2->Add((TH1D*)f2->Get(Variable2));
   h2->SetDirectory(0);
   f2->Close();

/*
   TFile *f3 = TFile::Open("/home/fynu/amertens/storage/test/MG_PY8_/output/MG_PY8_/MG_PY8.root");
   TH1D *h3 = (TH1D*)f3->Get(Variable);
   h3->SetDirectory(0);
   f3->Close();
*/
//   h1->Sumw2();
//   h2->Sumw2();
//   h3->Sumw2();

   cout << "MG_PY6      : " << h1->Integral() << endl;
   cout << "aMC@NLO_PY8 : " << h2->Integral() << endl;


   //h1->Scale(1.0/151456.0);
   //h2->Scale(1.0/1.45192e+09);
   //h2->Scale(1./12132.9);
   h1->Scale(1.0/h1->Integral());
   h2->Scale(1.0/h2->Integral());

   h1->Sumw2();
   h2->Sumw2();



//   h3->Scale(1.0/h3->Integral());

   h1->Rebin(N_Rebin);
   h2->Rebin(N_Rebin);
//   h3->Rebin(N_Rebin);

   TH1D *h1c = h1->Clone();
   h1c->Sumw2();
   TH1D *h2c = h2->Clone();
   h2c->Sumw2();

   TH1D *h1c2 = h1->Clone();
   h1c2->Sumw2();

   h2c->Add(h1c,-1);
   h2c->Divide(h1c);


   h1->SetTitle("");
   h2->SetTitle("");
//   h3->SetTitle("");


   h1->SetLineColor(kRed);
//   h3->SetLineColor(kGreen);

   TCanvas *c1 = new TCanvas("c1","example",600,700);
   TPad *pad1 = new TPad("pad1","pad1",0,0.5,1,1);
   pad1->SetBottomMargin(0);
   gStyle->SetOptStat(0);
   pad1->Draw();
   pad1->cd();
   h2->DrawCopy();
//   h3->DrawCopy("same");
   h1->GetYaxis()->SetLabelSize(0.1);
   h1->GetYaxis()->SetRangeUser(0, 0.2);// ,yTopLimit);
   h1->GetYaxis()->SetTitleSize(0.06);
   h1->GetYaxis()->SetTitleOffset(0.7);



   h1->Draw("same");

   TLegend *leg = new TLegend(0.6,0.7,0.89,0.89);
   leg->SetLineColor(0);
   leg->SetFillColor(0);
   //leg->AddEntry(h1,"t#bar{t} uncertainty","f");
   leg->AddEntry(h1,"MG5 + PY6","l");
   leg->AddEntry(h2,"aMC@NLO + PY8","l");
//   leg->AddEntry(h3,"MG5 + PY8","l");
   leg->Draw();

   
   c1->cd();

   TPad *pad2 = new TPad("pad2","pad2",0,0,1,0.5);
   pad2->SetTopMargin(0);
   pad2->SetBottomMargin(0.4);
   pad2->Draw();
   pad2->cd();
   pad2->SetGrid();
   h2->SetStats(0);
   h2->Divide(h1);
   //h2->SetMarkerStyle(21);
   h2->Draw("ep");
   h2->GetYaxis()->SetLabelSize(0.1);
   h2->GetYaxis()->SetRangeUser(-0.5, 2.5);// ,yTopLimit);
   h2->GetYaxis()->SetTitle("aMC@NLO+PY8 / MG5+PY6");
   h2->GetYaxis()->SetTitleSize(0.06);
   h2->GetYaxis()->SetTitleOffset(0.7);
   h2->GetXaxis()->SetLabelSize(0.1);
   h2->GetXaxis()->SetTitle(x_title);
   h2->GetXaxis()->SetTitleSize(0.16);
   h2->GetXaxis()->SetTitleOffset(0.9);
 //  Double_t matrix[4][4];
   h2->Fit("pol3","","",50.0,1200.0);
   TF1 *ratio = h2->GetFunction("pol3");
   TVirtualFitter *fitter = TVirtualFitter::GetFitter();
   TMatrixD matrix(4,4,fitter->GetCovarianceMatrix());
   Double_t errorPar00 = fitter->GetCovarianceMatrixElement(0,0);
   Double_t errorPar11 = fitter->GetCovarianceMatrixElement(1,1);
   Double_t errorPar22 = fitter->GetCovarianceMatrixElement(2,2);
   Double_t errorPar33 = fitter->GetCovarianceMatrixElement(3,3);
//   c1->cd();

   matrix.Print();

   //const TMatrixDSym m = matrix;
   const TMatrixDEigen eigen(matrix);
   const TMatrixD eigenVal = eigen.GetEigenValues();
   const TMatrixD V = eigen.GetEigenVectors(); 

   cout << "V" << endl;

   V.Print();

   cout << "eigenVal" << endl;

   eigenVal.Print();



   cout << "Recomputed diag" << endl;

   //const TMatrixD Vt(TMatrixD::kTransposed,V);
   //const TMatrixD Vinv = V.Invert();
   const TMatrixD Vt(TMatrixD::kTransposed,V);
   //cout << "V-1" << endl;
   //Vinv.Print();
   cout << "Vt" << endl;
   Vt.Print();

   const TMatrixD VAVt = Vt*matrix*V;
   VAVt.Print();


   const TVectorD FittedParam(4);
   FittedParam(0) = fitter->GetParameter(0);
   FittedParam(1) = fitter->GetParameter(1);
   FittedParam(2) = fitter->GetParameter(2);
   FittedParam(3) = fitter->GetParameter(3);
   FittedParam.Print();


   //const TVectorD FittedParamNB(4);
   const TVectorD PNb = V*FittedParam;
   cout << "Pnb" << endl;
   PNb.Print();
  

   cout << " Generating other parameters values " << endl;

   cout <<" V " << V(0,0) << endl;

   TRandom3 r;
   const TVectorD NewP(4);

   TH1D *hist100 = new TH1D("h100","h100",200,-5,5);
   TH1D *hist200 = new TH1D("h200","h200",200,-5,5);
   TH1D *hist400 = new TH1D("h400","h400",200,-5,5);
   TH1D *hist600 = new TH1D("h600","h600",100,-5,5);
   TH1D *hist800 = new TH1D("h800","h800",100,-5,5);
   TH1D *hist1000 = new TH1D("h1000","h1000",100,-5,5);

   TH1D *histp0 = new TH1D("p0","p0",100,-0.2,0.3);
   TH1D *histp1 = new TH1D("p1","p1",100,0.0,0.01);
   TH1D *histp2 = new TH1D("p2","p2",100,-0.00001,0);
   TH1D *histp3 = new TH1D("p3","p3",100,0,0.000000002);



   for (Int_t i = 0; i< 500; i++){
     NewP(0) = r.Gaus(PNb(0),sqrt(eigenVal(0,0)));
     NewP(1) = r.Gaus(PNb(1),sqrt(eigenVal(1,1)));
     NewP(2) = r.Gaus(PNb(2),sqrt(eigenVal(2,2)));
     NewP(3) = r.Gaus(PNb(3),sqrt(eigenVal(3,3)));
     //NewP.Print();

     //FittedParam.Print();

     const TVectorD NewP2 = Vt*NewP;
     //NewP2.Print();

     histp0->Fill(NewP2(0));
     histp1->Fill(NewP2(1));
     histp2->Fill(NewP2(2));
     histp3->Fill(NewP2(3));



     TF1 *newFit=new TF1("test","[0]+x*[1]+[2]*pow(x,2)+[3]*pow(x,3)",0,1400);
     newFit->SetParameters(NewP2(0),NewP2(1),NewP2(2),NewP2(3));
     newFit->SetLineColor(kBlue);

     Double_t area=0;
     for(Int_t it=1; it < 16; it++){
       //cout << "bin : " << it << " " << h1c2->GetBinContent(it) << endl;
       area += h1c2->GetBinContent(it)*newFit->Eval(100*it+50);
       }
   
     //newFit->Draw("same");
     //cout <<"val: " << newFit->Eval(200) << endl;
     hist100->Fill(newFit->Eval(100)/area);
     hist200->Fill(newFit->Eval(200)/area);
     hist400->Fill(newFit->Eval(400)/area);
     hist600->Fill(newFit->Eval(600)/area);
     hist800->Fill(newFit->Eval(800)/area);
     hist1000->Fill(newFit->Eval(1000)/area);
     }

   c1->cd();
   TCanvas *c2 = new TCanvas("c2","c2",1000,1000);
   c2->cd();
   c2->Divide(3,2);
   c2->cd(1);
   hist100->Draw();
   c2->cd(2);
   hist200->Draw();
   c2->cd(3);
   hist400->Draw();
   c2->cd(4);
   hist600->Draw();
   c2->cd(5);
   hist800->Draw();
   c2->cd(6);
   hist1000->Draw();



Double_t m_100,m_200,m_400,m_600,m_800,m_1000;
Double_t s_100,s_200,s_400,s_600,s_800,s_1000;

hist100->Fit("gaus","","",0.3,1.2);
TVirtualFitter *fitter = TVirtualFitter::GetFitter();
m_100 = fitter->GetParameter(1);
s_100 = fitter->GetParameter(2);

hist200->Fit("gaus","","",0.5,1.2);
TVirtualFitter *fitter = TVirtualFitter::GetFitter();
m_200 = fitter->GetParameter(1);
s_200 = fitter->GetParameter(2);

hist400->Fit("gaus","","",0.8,1.2);
TVirtualFitter *fitter = TVirtualFitter::GetFitter();
m_400 = fitter->GetParameter(1);
s_400 = fitter->GetParameter(2);

hist600->Fit("gaus","","",0.8,1.3);
TVirtualFitter *fitter = TVirtualFitter::GetFitter();
m_600 = fitter->GetParameter(1);
s_600 = fitter->GetParameter(2);

hist800->Fit("gaus","","",0.5,2);
TVirtualFitter *fitter = TVirtualFitter::GetFitter();
m_800 = fitter->GetParameter(1);
s_800 = fitter->GetParameter(2);

hist1000->Fit("gaus","","",0.5,2.5);
TVirtualFitter *fitter = TVirtualFitter::GetFitter();
m_1000 = fitter->GetParameter(1);
s_1000 = fitter->GetParameter(2);


Double_t x[6],y[6],ym[6],yup[6],ydown[6];
x[0]=100; x[1]=200; x[2]=400;x[3]=600; x[4]=800; x[5]=1000;
yup[0]=ratio->Eval(100)+s_100;
yup[1]=ratio->Eval(200)+s_200;
yup[2]=ratio->Eval(400)+s_400;
yup[3]=ratio->Eval(600)+s_600;
yup[4]=ratio->Eval(800)+s_800;
yup[5]=ratio->Eval(1000)+s_1000;
ydown[0]=ratio->Eval(100)-s_100;
ydown[1]=ratio->Eval(200)-s_200;
ydown[2]=ratio->Eval(400)-s_400;
ydown[3]=ratio->Eval(600)-s_600;
ydown[4]=ratio->Eval(800)-s_800;
ydown[5]=ratio->Eval(1000)-s_1000;

y[0]=1+s_100/ratio->Eval(100);
y[1]=1+s_200/ratio->Eval(200);
y[2]=1+s_400/ratio->Eval(400);
y[3]=1+s_600/ratio->Eval(600);
y[4]=1+s_800/ratio->Eval(800);
y[5]=1+s_1000/ratio->Eval(1000);

ym[0]=-s_100/m_100;
ym[1]=-s_200/m_200;
ym[2]=-s_400/m_400;
ym[3]=-s_600/m_600;
ym[4]=-s_800/m_800;
ym[5]=-s_1000/m_1000;


TGraph* g = new TGraph(6,x,y);
TGraph* gm = new TGraph(6,x,ym);
TGraph* gup = new TGraph(6,x,yup);
TGraph* gdown = new TGraph(6,x,ydown);


TCanvas *c3 = new TCanvas("c3","c3",1000,1000);
c3->cd();

//gup->Draw("AC*");
//gdown->Draw("C*");
g->Draw("AC*");

gPad->SetBottomMargin(0.2);
gPad->SetLeftMargin(0.2);
gStyle->SetOptStat(0);

g->GetXaxis()->SetTitle("M_{Zbb}");
g->GetXaxis()->SetRangeUser(50,1100);
g->GetYaxis()->SetLabelSize(0.06);
g->GetYaxis()->SetTitle("Uncertainty");
g->GetYaxis()->SetTitleSize(0.06);
g->GetYaxis()->SetTitleOffset(1.4);
g->GetXaxis()->SetLabelSize(0.06);
g->GetXaxis()->SetTitleSize(0.06);
g->GetXaxis()->SetTitleOffset(1);
g->GetYaxis()->SetNdivisions(5);

TFile f("syst_zxx.root","recreate");
g->Write();
f.Close();


//gm->Draw("C*");
//g->SetMaximum(1);
//g->SetMinimum(-1);
//h2c->Draw("same");


TH1D *h22=h2->Clone();

TCanvas *c5 =  new TCanvas("c5","c5",1000,1000);

gPad->SetBottomMargin(0.2);
gPad->SetLeftMargin(0.2);
gStyle->SetOptStat(0);

h22->Draw();
h22->GetXaxis()->SetRangeUser(50,1100);
h22->GetYaxis()->SetLabelSize(0.06);
h22->GetYaxis()->SetTitleSize(0.06);
h22->GetYaxis()->SetTitleOffset(1.4);
h22->GetXaxis()->SetLabelSize(0.06);
h22->GetXaxis()->SetTitleSize(0.06);
h22->GetXaxis()->SetTitleOffset(1);

ratio->SetLineColor(kRed);
ratio->Draw("same");

gup->Draw("C");
gdown->Draw("C");


TLegend *leg = new TLegend(0.6,0.7,0.89,0.89);
leg->SetLineColor(0);
leg->SetFillColor(0);
leg->AddEntry(h22,"aMC@NLO / MG5","lep");
leg->AddEntry(ratio,"best fit","l");
leg->AddEntry(gup,"Syst Error (#pm 1 #sigma)","l");
leg->Draw();



TCanvas *c4 = new TCanvas("c4","c4",1000,1000);
c4->Divide(2,2);
c4->cd(1);
histp0->Draw();
c4->cd(2);
histp1->Draw();
c4->cd(3);
histp2->Draw();
c4->cd(4);
histp3->Draw();


}
void Demo_TryExtrapolationInXT_Exp0_LogLogFits(Bool_t xt=kTRUE, Float_t expo=0.)
{
        SetStyle();
        gStyle->SetOptFile(0);
        gStyle->SetOptStat(0);
        gStyle->SetOptFit(0);
 
        xt=kTRUE;

	//define dummy histogram and some style parameters
	TH1F *dum;
 	dum = new TH1F("dum","",160,5e-4,0.3); 
	dum->SetMinimum(1e-14);
	dum->SetMaximum(1);
	dum->SetTitle(Form(";x_{T};#sqrt{s}^{%0.1f}  E d^{3}#sigma/dp^{3}",expo));
	dum->SetLineWidth(0);
	dum->SetStats(0);
	dum->GetXaxis()->CenterTitle();
	dum->GetYaxis()->CenterTitle();
	dum->GetXaxis()->SetTitleSize(0.05);
	dum->GetYaxis()->SetTitleSize(0.05);
	dum->GetXaxis()->SetTitleOffset(1.17);
	dum->GetYaxis()->SetTitleOffset(1.3);

	gROOT->LoadMacro("/net/hidsk0001/d00/scratch/krajczar/ppRefForpPb_PilotRun/interpolation_HIN10005_kk/data_table_to_graph.C");

	//get 7 TeV points
	TGraphErrors *cms_7000_g = data_table_to_graph("cms",7000,xt,expo);
	cms_7000_g->SetMarkerColor(kBlack);
	
	TF1 *cms_7000_fit = new TF1("cms_7000_fit","[0]*pow(1.0+(x/[1]),[2])",10.*2./7000.,0.1);//Fit from 10 GeV/c
	cms_7000_fit->SetLineWidth(1);
	cms_7000_fit->SetParameters(3e22,2.5e-4,-7);
	cms_7000_g->Fit(cms_7000_fit,"REMW0");
	
	//get 2.36 TeV points
//	TGraphErrors *cms_2360_g = data_table_to_graph("cms",2360,xt,expo);
//	cms_2360_g->SetMarkerColor(kMagenta+3);
	
//	TF1 *cms_2360_fit = new TF1("cms_2360_fit","[0]*pow(1.0+(x/[1]),[2])",2e-3,0.1);
//	cms_2360_fit->SetLineWidth(1);
//	cms_2360_fit->SetParameters(3e22,2.5e-4,-7);
//	cms_2360_g->Fit(cms_2360_fit,"REMW0");

	//get 2.76 TeV points (KK using existing txt files)
	TGraphErrors *cms_2760_g = data_table_to_graph("cms",2760,xt,expo);
	cms_2760_g->SetMarkerColor(kMagenta+3);
	TF1 *cms_2760_fit = new TF1("cms_2760_fit","[0]*pow(1.0+(x/[1]),[2])",10.*2./2760.,0.1);//Fit from 10 GeV/c
	cms_2760_fit->SetLineColor(kMagenta+3);
	cms_2760_fit->SetLineWidth(1);
	cms_2760_fit->SetParameters(3e22,2.5e-4,-7);
	cms_2760_g->Fit(cms_2760_fit,"REMW0");
	
	//get 1.96 TeV points
	TGraphErrors *cdf_1960_g = data_table_to_graph("cdf",1960,xt,expo);
	cdf_1960_g->SetMarkerColor(kOrange-3);
	cdf_1960_g->SetMarkerStyle(30);
	
	//TGraphErrors *cdfold_1960_g = data_table_to_graph("cdfold",1960,xt);
	//cdfold_1960_g->SetMarkerColor(kBlue);
	//cdfold_1960_g->SetMarkerStyle(30);
	
	TF1 *cdf_1960_fit = new TF1("cdf_1960_fit","[0]*pow(1.0+(x/[1]),[2])",2.*10./1960.,0.1);//Fit from 10 GeV/c
	cdf_1960_fit->SetLineColor(kOrange-3);
	cdf_1960_fit->SetLineWidth(1);
	cdf_1960_fit->SetParameters(3e22,2.5e-4,-7);
	cdf_1960_g->Fit(cdf_1960_fit,"REMW0");
	
	//get 1.8 TeV points
	TGraphErrors *cdf_1800_g = data_table_to_graph("cdf",1800,xt,expo);
	cdf_1800_g->SetMarkerColor(kGreen+3);
	cdf_1800_g->SetMarkerStyle(28);

	TF1 *cdf_1800_fit = new TF1("cdf_1800_fit","[0]*pow(1.0+(x/[1]),[2])",2.*10./1800.,0.1);//Fit from 10 GeV/c
	cdf_1800_fit->SetLineColor(kGreen+3);
	cdf_1800_fit->SetLineWidth(1);
	cdf_1800_fit->SetParameters(3e22,2.5e-4,-7.2);
	cdf_1800_fit->FixParameter(2,-7.2);
	cdf_1800_g->Fit(cdf_1800_fit,"REMW0");
	
	//get 0.9 TeV points
	TGraphErrors *cms_900_g = data_table_to_graph("cms",900,xt,expo);
	cms_900_g->SetMarkerColor(kRed);
	
	TF1 *cms_900_fit = new TF1("cms_900_fit","[0]*pow(1.0+(x/[1]),[2])",2.*10./900.,0.01);//Fit from 10 GeV/c
	cms_900_fit->SetLineColor(kRed);
	cms_900_fit->SetLineWidth(1);
	cms_900_fit->SetParameters(3e22,2.5e-4,-7);
	cms_900_g->Fit(cms_900_fit,"REMW0");
	
//	TGraphErrors *ua1_900_g = data_table_to_graph("ua1",900,xt,expo);
//	ua1_900_g->SetMarkerColor(kCyan+1);
//	ua1_900_g->SetMarkerStyle(26);

	// get 0.63 TeV points
	TGraphErrors *cdf_630_g = data_table_to_graph("cdf",630,xt,expo);
	cdf_630_g->SetMarkerColor(kOrange+3);
	cdf_630_g->SetMarkerStyle(27);

	//draw graphs to canvas
	TCanvas *c1 = new TCanvas("c1","spectra interpolation",600,600);
	dum->Draw();
        //Fits are already drawn, no draw the points on top of the fits
	cdf_1960_g->Draw("pz");
	//cdfold_1960_g->Draw("pz");
//	cdf_1800_g->Draw("pz");
//	if(!xt) ua1_900_g->Draw("pz"); // abs(eta) within 2.5 changes high xt behavior
//	cdf_630_g->Draw("pz");
	cms_900_g->Draw("pz");         // draw the CMS points on top
//	cms_2360_g->Draw("pz");
	cms_2760_g->Draw("pz"); //KK
	cms_7000_g->Draw("pz");

	//make legend
	TLegend *leg1 = new TLegend(0.2,0.21,0.50,0.51,"p+p(#bar{p})");
	leg1->SetBorderSize(0);
	leg1->SetFillStyle(1);
	leg1->SetFillColor(0);
	leg1->AddEntry(cms_7000_g,"7 TeV  (CMS)","lp");
	leg1->AddEntry(cms_2760_g,"2.76 TeV (CMS)","lp");
//	leg1->AddEntry(cms_2360_g,"2.36 TeV (CMS)","lp");
	leg1->AddEntry(cdf_1960_g,"1.96 TeV  (CDF)","lp");
//	leg1->AddEntry(cdf_1800_g,"1.8 TeV  (CDF)","lp");
	leg1->AddEntry(cms_900_g,"0.9 TeV  (CMS)","lp");
//	if(!xt) leg1->AddEntry(ua1_900_g,"0.9 TeV  (UA1)  |#eta|<2.5","lp");
//	leg1->AddEntry(cdf_630_g,"0.63 TeV  (CDF)","lp");
	leg1->Draw();
	
	gPad->SetLogy();
	//if(xt) gPad->SetLogx();
	gPad->SetLogx();
	
	cms_7000_fit->Draw("same");
	cms_2760_fit->Draw("same");
	cdf_1960_fit->Draw("same");
//	cdf_1800_fit->Draw("same");
	cms_900_fit->Draw("same");

	TCanvas *c3 = new TCanvas("c3","Individual xT fits, residuals",600,500);
	TH1F *hratio = new TH1F("hratio",";x_{T};ratio",160,0.0003,0.07); //was 0.003-0.04
	hratio->SetMaximum(2.0);
	hratio->SetMinimum(0.0);
	hratio->SetStats(0);
	hratio->Draw();
		
	TGraphErrors* ratio_cdf_1960_g = divide_graph_by_function(cdf_1960_g,cdf_1960_fit);
	ratio_cdf_1960_g->SetName("ratio_cdf_1960_g");
	ratio_cdf_1960_g->SetLineColor(kOrange-9);
	ratio_cdf_1960_g->SetMarkerSize(0.9);
	ratio_cdf_1960_g->Draw("samepz");
		
	TF1 *fit1960 = new TF1("fit1960","[0]+[1]*log(x)+[2]/x/x",0.001,0.035);
	fit1960->SetLineWidth(2);
	fit1960->SetLineColor(kOrange-3);
	ratio_cdf_1960_g->Fit(fit1960,"REMW");
	fit1960->Draw("same");
		
//	TGraphErrors* ratio_cdf_1800_g = divide_graph_by_function(cdf_1800_g,cdf_1800_fit);
//	ratio_cdf_1800_g->Draw("samepz");
		
//	TGraphErrors* ratio_cdf_630_g = divide_graph_by_function(cdf_630_g,merge_fit);
	//ratio_cdf_630_g->Draw("pz");
	
	TGraphErrors* ratio_cms_7000_g = divide_graph_by_function(cms_7000_g,cms_7000_fit);
	ratio_cms_7000_g->SetName("ratio_cms_7000_g");
	ratio_cms_7000_g->Draw("samepz");
		
	TF1 *fit7000 = new TF1("fit7000","[0]+[1]*x+[2]*x*x+[3]*x*x*x",0.001,0.1);
	fit7000->SetLineWidth(2);
	ratio_cms_7000_g->Fit(fit7000,"REMW");

	TGraphErrors* ratio_cms_2760_g = divide_graph_by_function(cms_2760_g,cms_2760_fit);
	ratio_cms_2760_g->SetName("ratio_cms_2760_g");
	ratio_cms_2760_g->SetLineColor(kMagenta+3);
	ratio_cms_2760_g->Draw("samepz");
		
        TF1 *fit2760 = new TF1("fit2760","[0]+[1]*x+[2]*x*x+[3]*x*x*x",0.001,0.1);
	fit2760->SetLineWidth(2);
	fit2760->SetLineColor(kMagenta+3);
	ratio_cms_2760_g->Fit(fit2760,"REM");//REMW
		
	TGraphErrors* ratio_cms_900_g = divide_graph_by_function(cms_900_g,cms_900_fit);
	ratio_cms_900_g->SetName("ratio_cms_900_g");
	ratio_cms_900_g->Draw("samepz");
		
        TF1 *fit900 = new TF1("fit900","[0]+[1]*x+[2]*x*x+[3]*x*x*x",0.007,0.1);
        fit900->SetParameters(5.61766e-01,5.24904e+01,-2.27817e+03,3.43955e+04);
	fit900->SetLineWidth(2);
	fit900->SetLineColor(2);
	ratio_cms_900_g->Fit(fit900,"REM");//REMW
	ratio_cms_900_g->SetLineColor(kRed);
		
	TGaxis *A1 = new TGaxis(0.0003,7.0,0.07,7.0,2510*0.0003,2510*0.07,410,"-");
	A1->SetTitle("p_{T} for #sqrt{s}=5.02 TeV");
	A1->Draw();

        //Real fit should be the fit*resid
	TH1D *h900 = new TH1D("h900","900 GeV fitted spectra;x_{T}",30400,0.005,0.05);
	h900->SetLineColor(kRed);
	TH1D *h1960 = new TH1D("h1960","1.96 TeV fitted spectra;x_{T}",30400,0.005,0.05);
	h1960->SetLineColor(kOrange-3);
	TH1D *h7000 = new TH1D("h7000","7 TeV fitted spectra;x_{T}",30400,0.005,0.05);
	TH1D *h1800 = new TH1D("h1800","1.8 TeV fitted spectra;x_{T}",30400,0.005,0.05);
	h1800->SetLineColor(kGreen+3);
	TH1D *h630 = new TH1D("h630","0.63 TeV fitted spectra;x_{T}",30400,0.005,0.05);
	h630->SetLineColor(kOrange+3);
	TH1D *h2760_EdTxt = new TH1D("h2760_EdTxt","2.76 TeV fitted spectra;x_{T}",30400,0.005,0.05);
	h2760_EdTxt->SetLineColor(kMagenta+3);

	for(int hbin=1; hbin<=30400; hbin++) {
		float xtbin = h900->GetBinCenter(hbin);
		h900->SetBinContent(hbin,cms_900_fit->Eval(xtbin)*fit900->Eval(xtbin));
		h1960->SetBinContent(hbin,cdf_1960_fit->Eval(xtbin)*fit1960->Eval(xtbin));
		h7000->SetBinContent(hbin,cms_7000_fit->Eval(xtbin)*fit7000->Eval(xtbin));
		h2760_EdTxt->SetBinContent(hbin,cms_2760_fit->Eval(xtbin)*fit2760->Eval(xtbin));
	}

	TCanvas *c5 = new TCanvas("c5","final x_{T} fits",600,500);
	TH1D* dumDirectInt = new TH1D("dumDirectInt","Final fits; x_{T} (GeV/c)",120,5e-4,0.3);
	dumDirectInt->SetMaximum(1);
	dumDirectInt->SetMinimum(1e-14);
	dumDirectInt->GetXaxis()->SetRangeUser(0.5,120.);
	dumDirectInt->SetStats(0);
	dumDirectInt->GetYaxis()->SetTitle("Ed^{3}#sigma/dp^{3}");
	dumDirectInt->Draw();
	h900->Draw("same");
	h1960->Draw("same");
	h7000->Draw("same");
	h2760_EdTxt->Draw("same");
	gPad->SetLogy();
	gPad->SetLogx();

	// inspect direct interpolations
	TCanvas *c6 = new TCanvas("c6","interpolations",600,500);
	c6->Divide(3,4);
	float s[6]; float xs[6]; float es[6]={0.0,0.0,0.0,0.0,0.0,0.0}; float exs[6];   TGraphErrors *gXS[12];
        float s_log[6]; float xs_log[6]; float es_log[6]={0.0,0.0,0.0,0.0,0.0,0.0}; float exs_log[6];
        TGraphErrors *gXS_log[12]; //KK test
        TGraphErrors *gXS_log_lemma[12]; //KK test
	float s1[1]={2.76}; float xs1[1]; float ex1[1]={0.0}; float ey1[1]; 		TGraphErrors *gXS1[12];
	float s1_5020[1]={5.02}; float xs1_5020[1]; float ex1_5020[1]={0.0}; float ey1_5020[1]; TGraphErrors *gXS1_5020[12];
	float s2[1]={2.76}; float xs2[1]; float ex2[1]={0.0}; float ey2[1]; 		TGraphErrors *gXS2[12];
	float s2_5020[1]={5.02}; float xs2_5020[1]; float ex2_5020[1]={0.0}; float ey2_5020[1]; TGraphErrors *gXS2_5020[12];
	float s900[1]={0.9}; float xs900[1]; float ex900[1]={0.0}; float ey900[1]; TGraphErrors *gXS900[12];
	float s1960[1]={1.96}; float xs1960[1]; float ex1960[1]={0.0}; float ey1960[1]; TGraphErrors *gXS1960[12];
	float s2760[1]={2.76}; float xs2760[1]; float ex2760[1]={0.0}; float ey2760[1]; TGraphErrors *gXS2760[12];
	float s7000[1]={7.0}; float xs7000[1]; float ex7000[1]={0.0}; float ey7000[1]; TGraphErrors *gXS7000[12];

	TF1 *fitXS[12];  TH1F *dumXS[12];
        TF1 *fitXS_log[12];
	float xtbins[12]={0.0051,0.007,0.01,0.015,0.02,0.025,0.03,0.035,0.04,0.042,0.045,0.049};
        //2pT/sqrt(s) = xT ==>> xT=0.0051 -> pT=12.8 GeV/c; xT=0.049 -> pT=123 GeV/c

        //errors        
        TMVA::TSpline1 *err_cms_900_xt = errors_from_graph(cms_900_g,0.115);
        TMVA::TSpline1 *err_cms_2760_xt = errors_from_graph(cms_2760_g,0.11);
        TMVA::TSpline1 *err_cms_7000_xt = errors_from_graph(cms_7000_g,0.04);	
        TMVA::TSpline1 *err_cdf_1960_xt = errors_from_graph(cdf_1960_g,0.06);

	for(Int_t ipt=0; ipt<=11; ipt++) {
						
		c6->cd(ipt+1);
		int npoints=0;

		xs[npoints]=h900->GetBinContent(h900->FindBin(xtbins[ipt])); s[npoints]=0.9; exs[npoints]=err_cms_900_xt->Eval(xtbins[ipt])*xs[npoints]; xs900[0]=xs[npoints]; ey900[0]=exs[npoints];
		xs_log[npoints]=log10(xs[npoints]); s_log[npoints]=log10(s[npoints]); exs_log[npoints]=TMath::Max(fabs(log10(xs[npoints]-exs[npoints])-log10(xs[npoints])),fabs(log10(xs[npoints]+exs[npoints])-log10(xs[npoints])));
                npoints++;

		xs[npoints]=h1960->GetBinContent(h1960->FindBin(xtbins[ipt])); s[npoints]=1.96; exs[npoints]=err_cdf_1960_xt->Eval(xtbins[ipt])*xs[npoints]; xs1960[0]=xs[npoints]; ey1960[0]=exs[npoints];
		xs_log[npoints]=log10(xs[npoints]); s_log[npoints]=log10(s[npoints]); exs_log[npoints]=TMath::Max(fabs(log10(xs[npoints]-exs[npoints])-log10(xs[npoints])),fabs(log10(xs[npoints]+exs[npoints])-log10(xs[npoints])));
                npoints++;
 
		xs[npoints]=h2760_EdTxt->GetBinContent(h2760_EdTxt->FindBin(xtbins[ipt])); s[npoints]=2.76; exs[npoints]=err_cms_2760_xt->Eval(xtbins[ipt])*xs[npoints]; xs2760[0]=xs[npoints]; ey2760[0]=exs[npoints];
		xs_log[npoints]=log10(xs[npoints]); s_log[npoints]=log10(s[npoints]); exs_log[npoints]=TMath::Max(fabs(log10(xs[npoints]-exs[npoints])-log10(xs[npoints])),fabs(log10(xs[npoints]+exs[npoints])-log10(xs[npoints])));
                npoints++;

		xs[npoints]=h7000->GetBinContent(h7000->FindBin(xtbins[ipt])); s[npoints]=7.0; exs[npoints]=err_cms_7000_xt->Eval(xtbins[ipt])*xs[npoints]; xs7000[0]=xs[npoints]; ey7000[0]=exs[npoints];
		xs_log[npoints]=log10(xs[npoints]); s_log[npoints]=log10(s[npoints]); exs_log[npoints]=TMath::Max(fabs(log10(xs[npoints]-exs[npoints])-log10(xs[npoints])),fabs(log10(xs[npoints]+exs[npoints])-log10(xs[npoints])));
                npoints++;
			
		dumXS[ipt] = new TH1F(Form("dumXS%d",ipt),Form("p_{T} = %0.0f GeV/c;#sqrt{s} [TeV]",xtbins[ipt]),100,0,20);
		dumXS[ipt]->SetMinimum(0.25*xs[npoints-1]);
		dumXS[ipt]->SetMaximum(4.0*xs[0]);
		dumXS[ipt]->SetStats(0);
		dumXS[ipt]->GetXaxis()->SetRangeUser(0.5,10.0);
              	dumXS[ipt]->GetXaxis()->CenterTitle();
               	dumXS[ipt]->GetYaxis()->CenterTitle();
               	dumXS[ipt]->GetYaxis()->SetTitle("Ed#sigma^{3}/dp^{3}");
               	dumXS[ipt]->GetXaxis()->SetTitleSize(0.10);
               	dumXS[ipt]->GetYaxis()->SetTitleSize(0.10);
               	dumXS[ipt]->GetYaxis()->SetLabelSize(0.10);
               	dumXS[ipt]->GetXaxis()->SetLabelSize(0.10);
               	dumXS[ipt]->GetXaxis()->SetTitleOffset(0.6);
               	dumXS[ipt]->GetYaxis()->SetTitleOffset(0.8);
		dumXS[ipt]->Draw();
		gPad->SetLogy();  
                gPad->SetLogx();

                std::cerr<< "npoints: " << npoints << std::endl;

		gXS[ipt] = new TGraphErrors(npoints,s,xs,es,exs);  gXS[ipt]->SetName(Form("gXS%d",ipt));
		gXS[ipt]->SetMarkerStyle(20);
		gXS_log[ipt] = new TGraphErrors(npoints,s_log,xs_log,es_log,exs_log); gXS_log[ipt]->SetName(Form("gXS_log%d",ipt));

		gXS900[ipt] = new TGraphErrors(1,s900,xs900,ex900,ey900); gXS900[ipt]->SetName(Form("gXS900_%d",ipt)); 
		gXS900[ipt]->SetMarkerStyle(20);  gXS900[ipt]->SetMarkerColor(kRed); gXS900[ipt]->Draw("pz");

		gXS1960[ipt] = new TGraphErrors(1,s1960,xs1960,ex1960,ey1960); gXS1960[ipt]->SetName(Form("gXS1960_%d",ipt)); 
		gXS1960[ipt]->SetMarkerStyle(30);  gXS1960[ipt]->SetMarkerColor(kOrange-3); gXS1960[ipt]->Draw("pz");

		gXS2760[ipt] = new TGraphErrors(1,s2760,xs2760,ex2760,ey2760); gXS2760[ipt]->SetName(Form("gXS2760_%d",ipt)); 
		gXS2760[ipt]->SetMarkerStyle(20);  gXS2760[ipt]->SetMarkerColor(kMagenta+3); gXS2760[ipt]->Draw("pz");	

		gXS7000[ipt] = new TGraphErrors(1,s7000,xs7000,ex7000,ey7000); gXS7000[ipt]->SetName(Form("gXS7000_%d",ipt)); 
		gXS7000[ipt]->SetMarkerStyle(20);  gXS7000[ipt]->SetMarkerColor(kBlack); gXS7000[ipt]->Draw("pz");	
			
		fitXS_log[ipt] = new TF1(Form("fitXS_log%d",ipt),"pol2",-0.52288,0.85733);
		gXS_log[ipt]->Fit(fitXS_log[ipt], "REM0"); //"REMW");

		// full covariance errors on fit
		TVirtualFitter *fitter = TVirtualFitter::GetFitter();
		TMatrixD matrix(3,3,fitter->GetCovarianceMatrix());
		Double_t e00 = fitter->GetCovarianceMatrixElement(0,0);
		Double_t e11 = fitter->GetCovarianceMatrixElement(1,1);
		Double_t e22 = fitter->GetCovarianceMatrixElement(2,2);
		Double_t e01 = fitter->GetCovarianceMatrixElement(0,1);
		Double_t e02 = fitter->GetCovarianceMatrixElement(0,2);
		Double_t e12 = fitter->GetCovarianceMatrixElement(1,2);

                //Due to properties of the covariance matrix:
                Double_t e10 = e01;
                Double_t e20 = e02;
                Double_t e21 = e12;

                gXS_log_lemma[ipt] = new TGraphErrors(); gXS_log_lemma[ipt]->SetName(Form("gXS_log_lemma%d",ipt));
                int kkk = 0;
                for(int kk = log10(0.8*s[0])*10000.; kk <= log10(1.3*s[npoints-1])*10000.; kk++) {
                      float kk_lemma = kk/10000.;
                      float value = fitXS_log[ipt]->Eval(kk_lemma);
                      gXS_log_lemma[ipt]->SetPoint(kkk,TMath::Power(10,kk_lemma),TMath::Power(10,value));
                      kkk++;
                }
                gXS_log_lemma[ipt]->SetLineColor(2);
                gXS_log_lemma[ipt]->Draw("same");
			
		cout << "cov(0,0) = " << e00 
		<< "\ncov(1,1) = " << e11 
		<< "\ncov(2,2) = " << e22 
		<< "\ncov(0,1) = " << e01 
		<< "\ncov(0,2) = " << e02 
		<< "\ncov(1,2) = " << e12 
		<< endl;
			
                //0.7007 = log10(5.02)
		Double_t fullerr2 = e00 + e11*0.7007*0.7007 + e22*0.7007*0.7007*0.7007*0.7007 + 2*e01*0.7007 + 2*e02*0.7007*0.7007 + 2*e12*0.7007*0.7007*0.7007;
                //Plan (1.,0.7007,0.7007^2)(COV)(1.,0.7007,0.7007^2):
                Double_t where = 0.7007;
                Double_t fullerr2_alternative = e00 + 2.*e01*where + 2.*e02*where*where + 2.*e12*where*where*where + e11*where*where + e22*where*where*where*where;
			
		cout << "full covariance error = " << TMath::Sqrt(fullerr2) << endl;
		cout << "full covariance error alternative: = " << TMath::Sqrt(fullerr2_alternative) << endl;
                float error_in_percentage = 100.*(TMath::Power(10,TMath::Sqrt(fullerr2))-1.);
                cout << "   on " << fitXS_log[ipt]->Eval(0.7007) << std::endl;
                cout << "   error in percentage: " << error_in_percentage << std::endl;

                //5020
		xs2_5020[0] = TMath::Power(10,fitXS_log[ipt]->Eval(0.7007));
		ey2_5020[0] = error_in_percentage*0.01*xs2_5020[0];
		gXS2_5020[ipt] = new TGraphErrors(1,s2_5020,xs2_5020,ex2_5020,ey2_5020); gXS2_5020[ipt]->SetName(Form("gXS2_5020_%d",ipt));
		gXS2_5020[ipt]->SetMarkerColor(7);
		gXS2_5020[ipt]->SetLineColor(7);
		gXS2_5020[ipt]->SetMarkerStyle(kOpenSquare);
		gXS2_5020[ipt]->Draw("pz");
	}
}