Ejemplo n.º 1
0
void MgCommandLine::insertText(const QString & newText)
{

	QString myText(text());
	int pos(cursorPosition()-m_prefix.size());
	myText.remove(pos,m_prefix.size());
	myText.insert(pos,newText);
	setText(myText);
	m_prefix.clear();
}
Ejemplo n.º 2
0
/*
 * Read the text from a file. The text must start with a Unicode Byte
 * Order Mark (BOM) so that we know what order to read the bytes in.
 */
const UChar *ThaiWordbreakTest::readFile(char *fileName, int32_t &charCount)
{
    FILE *f;
    int32_t fileSize;
    
    UChar *buffer;
    char *bufferChars;
    
    f = fopen(fileName, "rb");
    
    if( f == NULL ) {
        fprintf(stderr,"Couldn't open %s reason: %s \n", fileName, strerror(errno));
        return 0;
    }
    
    fseek(f, 0, SEEK_END);
    fileSize = ftell(f);
    
    fseek(f, 0, SEEK_SET);
    bufferChars = new char[fileSize];
    
    if(bufferChars == 0) {
        fprintf(stderr,"Couldn't get memory for reading %s reason: %s \n", fileName, strerror(errno));
        fclose(f);
        return 0;
    }
    
    fread(bufferChars, sizeof(char), fileSize, f);
    if( ferror(f) ) {
        fprintf(stderr,"Couldn't read %s reason: %s \n", fileName, strerror(errno));
        fclose(f);
        delete[] bufferChars;
        return 0;
    }
    fclose(f);
    
    UnicodeString myText(bufferChars, fileSize, "UTF-8");

    delete[] bufferChars;
    
    charCount = myText.length();
    buffer = new UChar[charCount];
    if(buffer == 0) {
        fprintf(stderr,"Couldn't get memory for reading %s reason: %s \n", fileName, strerror(errno));
        return 0;
    }
    
    myText.extract(1, myText.length(), buffer);
    charCount--;  // skip the BOM
    buffer[charCount] = 0;    // NULL terminate for easier reading in the debugger
    
    return buffer;
}
Ejemplo n.º 3
0
// inline functions
static inline void addTextNode(ticpp::Element& parent, const char* title, const char* value)
{
	if (!value) {
		return;
	}

	ticpp::Text myText(value);
	if (!title) {
		parent.SetText(myText);
	} else {
		ticpp::Element myTitle(title);
		myTitle.LinkEndChild(&myText);
		parent.LinkEndChild(&myTitle);
	}
}
Ejemplo n.º 4
0
int game(void* data)
{
    //StringData loading...
    StringData myText("Common");

    //Create a SDL screen.
    const int SCREEN_WIDTH = 640;
    const int SCREEN_HEIGHT = 480;
    const Uint32 SCREEN_FLAGS = 0; //SDL_FULLSCREEN | SDL_DOUBLEBUF | SDL_HWSURFACE
    const std::string WINDOW_NAME = "The Keys To Your Heart";
    ScreenSurface screen(SCREEN_WIDTH, SCREEN_HEIGHT, WINDOW_NAME, 0, SCREEN_FLAGS);

    //bg loading
    PictureSurface bg("./images/h3_bg.png", screen);

    //music loading
    MusicSound mus("./sounds/bgMusic.mid");
    mus.play();

    //UVi Logo
    UVi_begin(screen);

    //main loop
    bool gameOver = false;
    while ( gameOver == false ) {
        //Title loop
        gameOver = title_loop_quit(screen);

        //pages show and get result
        std::vector<char> result;
        if ( gameOver != true ) {
            gameOver = get_result_quit(result, bg, screen);
        }

        //show result;
        if ( gameOver != true ) {
            gameOver = show_result_quit(result, screen);
        }
    }

    //end show
    end_show(screen);

    //end music
    mus.stop();

    return 0;
}
Ejemplo n.º 5
0
void Builder::addText( const DL_TextData &data )
{
  if ( convertText )
  {
    DL_TextData myText(
      data.ipx + currentBlockX, data.ipy + currentBlockY, data.ipz,
      data.apx, data.apy, data.apz,
      data.height, data.xScaleFactor, data.textGenerationFlags,
      data.hJustification, data.vJustification,
      data.text, data.style, data.angle
    );

    textObjects.push_back( myText );

    QgsDebugMsg( QString( "text: %1" ).arg( data.text.c_str() ) );
    fetchedtexts++;
  }
}
Ejemplo n.º 6
0
void MyGame::CreateText(){
    ResourceCache* cache = GetSubsystem<ResourceCache>();
    
    // Construct the text object
    SharedPtr<Text> myText(new Text(context_));
    
    // Set text to display
    myText->SetText("Hello Wolrd from " + getGameName());

    // Set font and text color
    myText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 30);
    myText->SetColor(Color(0.0f, 1.0f, 0.0f));

    // Align Text center-screen
    myText->SetHorizontalAlignment(HA_CENTER);
    myText->SetVerticalAlignment(VA_CENTER);

    // Add Text instance to the UI root element
    GetSubsystem<UI>()->GetRoot()->AddChild(myText);
}
Ejemplo n.º 7
0
void Plot_McollRatio(TString file, TString fakefile, TString sample, TString SR, bool subtractFakes)
{

	SetAtlasStyle();
	#ifdef __CINT__
	  gROOT->LoadMacro("AtlasUtils.C");
	#endif

  	double xmin = 50;
  	double xmax = 400;


  	TFile* f = new TFile(file);
  	TFile* fakef = new TFile(fakefile);

  	TH1D* hME;
  	TH1D* hEM;

  	//if (isScaled){
//  		hME =(TH1D*)f->Get("ME_scaled");//nom/ME_McollHiggs_Unblind");
//  		hEM =(TH1D*)f->Get("EM");//nom/EM_McollHiggs_Unblind");
//  		hME_orig = (TH1D*)f->Get("ME_original");
//  		hEM_orig = (TH1D*)f->Get("EM_original");
  	//}
  	//else{
  		hME =(TH1D*)f->Get("nom/ME_McollHiggs_Unblind");
  		hEM =(TH1D*)f->Get("nom/EM_McollHiggs_Unblind");
  	//}

  	if (subtractFakes){
  		TH1D* hME_fake = (TH1D*)fakef->Get("nom/ME_McollHiggs_Unblind");
  		TH1D* hEM_fake = (TH1D*)fakef->Get("nom/EM_McollHiggs_Unblind");

  		hME->Add(hME_fake,-1);
  		hEM->Add(hEM_fake,-1);
 	}
  	hEM->SetMarkerStyle(8); hEM->SetMarkerSize(0.7);
  	hEM->SetLineColor(kPink + 8);hEM->SetOption("e1");
  	hEM->SetMarkerColor(kPink + 8);
  	hME->SetMarkerStyle(8); hME->SetMarkerSize(0.7);
  	hME->SetLineColor(kTeal - 6);hME->SetOption("e1");
  	hME->SetMarkerColor(kTeal - 6);
  	hME->GetXaxis()->SetLabelOffset(0); hME->GetXaxis()->SetLabelSize(0);
  	hEM->GetXaxis()->SetLabelOffset(0); hEM->GetXaxis()->SetLabelSize(0);
  	hEM->GetXaxis()->SetRangeUser(xmin,xmax);   hME->GetXaxis()->SetRangeUser(xmin,xmax);
  	hEM->GetYaxis()->SetTitleOffset(1.0);
  	hME->GetYaxis()->SetTitleOffset(1.0);

//  	hEM_orig->SetMarkerStyle(8); hEM_orig->SetMarkerSize(0.7);
//  	hEM_orig->SetLineColor(kPink + 8);hEM_orig->SetOption("e1");
//  	hEM_orig->SetMarkerColor(kPink + 8);
//  	hME_orig->SetMarkerStyle(8); hME_orig->SetMarkerSize(0.7);
//  	hME_orig->SetLineColor(kTeal - 6);hME_orig->SetOption("e1");
//  	hME_orig->SetMarkerColor(kTeal - 6);
//  	hME_orig->GetXaxis()->SetLabelOffset(0); hME_orig->GetXaxis()->SetLabelSize(0);
//  	hEM_orig->GetXaxis()->SetLabelOffset(0); hEM_orig->GetXaxis()->SetLabelSize(0);
//  	hEM_orig->GetXaxis()->SetRangeUser(xmin,xmax);   hME_orig->GetXaxis()->SetRangeUser(xmin,xmax);
//  	hEM_orig->GetYaxis()->SetTitleOffset(1.0);
//  	hME_orig->GetYaxis()->SetTitleOffset(1.0);

  	double numEM = hEM->Integral();
  	double numME = hME->Integral();

  	cout<<"# entries EM = " << numEM << endl;
  	cout<<"# entries ME = " << numME << endl;

//  	TH1D* ratio2 = GetRatio(hEM_orig,hME_orig,xmin,xmax);
//  	TH1D* diff2 = GetDiff(hEM_orig,hME_orig,xmin,xmax);

  	TH1D* ratio = GetRatio(hEM,hME,xmin,xmax);
  	TH1D* diff = GetDiff(hEM,hME,xmin,xmax);

  	TLegend* leg = new TLegend(0.6,0.45,0.75,0.55);
  	leg->SetFillColor(kWhite); leg->SetBorderSize(1); leg->SetLineColor(0); leg->SetTextFont(42);
  	leg->SetTextSize(.05);

  	TLine* line1 = new TLine(xmin,1,xmax,1); line1->SetLineColor(kRed); line1->SetLineStyle(2);
  	TLine* line14 = new TLine(xmin,1.5,xmax,1.5); line14->SetLineStyle(9);
  	line14->SetLineColor(kBlack);
  	TLine* line13 = new TLine(xmin,2./3,xmax,2./3); line13->SetLineStyle(2);
  	line13->SetLineColor(kRed);
  	TLine* line12 = new TLine(xmin,2,xmax,2); line12->SetLineStyle(9);
  	line12->SetLineColor(kBlack);
  	TLine* line15 = new TLine(xmin,0.5,xmax,0.5); line15->SetLineStyle(9);
  	line15->SetLineColor(kBlack);
  	TLine* line2 = new TLine(xmin,0,xmax,0); line2->SetLineColor(kBlack); line2->SetLineStyle(9);

  	TLine* vline1 = new TLine(100,0,100,3000); vline1->SetLineStyle(2);
  	TLine* vline2 = new TLine(150,0,150,3000); vline2->SetLineStyle(2);

  	TCanvas* c0 = new TCanvas("mcoll ","mcoll ",600,600); c0=c0;
  	TPad *pad1 =  new TPad("pad1", "12<L1<15",0.0,0.2,1,1.0,21); pad1->SetMargin(0.1,0.1,0.02,0.2);
  	TPad *pad2 =  new TPad("pad2", "ratio",   0.0,0,1,0.2,21); pad2->SetMargin(0.1,0.1,0.3,0.02);
//  	TPad *pad3 =  new TPad("pad3", "diff",    0.0,0,1,0.2,21); pad3->SetMargin(0.1,0.1,0.3,0.02);

  	pad1->SetFillColor(0);pad2->SetFillColor(0);//pad3->SetFillColor(0);
  	pad1->Draw(); pad2->Draw();//pad3->Draw();


  	pad1->cd();

	#ifdef __CINT__
  		gROOT->LoadMacro("AtlasLabels.C");
	#endif

  	leg->AddEntry(hME,"#mue","le");
  	leg->AddEntry(hEM,"e#mu","le");


  	hEM->Draw("e1"); hME->Draw("e1 sames");
  	vline1->Draw(); vline2->Draw();


  	pad2->cd();
  	ratio->Draw();
  	line14->Draw();line15->Draw();line1->Draw();

//  	pad3->cd();
//  	diff->Draw();
//  	line2->Draw();

  	pad1->cd();
  	myText(0.5,0.65,1,"#int L dt = 20.3 fb^{-1}  #sqrt{s} = 8 TeV");
  	myText(0.6,0.35,1,sample);
  	myText(0.6,0.25,1,SR);

  	ATLASLabel(0.62,0.75,"Internal");

  	leg->Draw();


  	c0->Update();

//  	TCanvas* c1 = new TCanvas("mcoll original","mcoll original",600,600); c0=c0;
//  	TPad *pad1_2 =  new TPad("pad1", "12<L1<15",0.0,0.4,1,1.0,21); pad1_2->SetMargin(0.1,0.1,0.02,0.2);
//  	TPad *pad2_2 =  new TPad("pad2", "ratio",   0.0,0.2,1,0.4,21); pad2_2->SetMargin(0.1,0.1,0.02,0.02);
//  	TPad *pad3_2 =  new TPad("pad3", "diff",    0.0,0,1,0.2,21); pad3_2->SetMargin(0.1,0.1,0.3,0.02);
//
//  	pad1_2->SetFillColor(0);pad2_2->SetFillColor(0);pad3_2->SetFillColor(0);
//  	pad1_2->Draw(); pad2_2->Draw();pad3_2->Draw();
//
//
//  	pad1_2->cd();

//  	hEM_orig->Draw("e1"); hME_orig->Draw("e1 sames");
//  	vline1->Draw(); vline2->Draw();


//  	pad2_2->cd();
//  	ratio2->Draw();
//  	line14->Draw();line15->Draw();line1->Draw();

//  	pad3_2->cd();
//  	diff2->Draw();
//  	line2->Draw();

//  	pad1_2->cd();
//  	myText(0.5,0.65,1,"#int L dt = 20.3 fb^{-1}  #sqrt{s} = 8 TeV");
//  	myText(0.6,0.35,1,sample);
//
//  	ATLASLabel(0.62,0.75,"Internal");
//
//  	leg->Draw();
//
//
//  	c1->Update();



  return;
}
Ejemplo n.º 8
0
// filname : output file name 
// pmode : pedestal mode 
// mode :  
void SPEFit_UXC_Ana_V2(int run=254743, TString filname="test", bool pmode=false, int mode=1)
{

    /*mode 1: TH1F * HistoSum[2][72][13];             // integral of TS 2-5
      mode 2: TH1F * HistoFullSum[2][72][13];         // integral of TS 0-9
      mode 3: TH1F * HistoEachTS[2][72][13];          // no sum but each TS 
      mode 4: TH1F * HistoEachTSsub[2][72][13];       // no sum but ecah TS(2-5)
      mode5-15 TH1F * HistoSeparateTS[2][72][13][mode-5] // draw only TS = mode-5
     */
    TString fLEDname = Form("Run_%i.root",run);
    TString fPEDname = fLEDname;
    TString rootname = filname+"_mode_";
    rootname+=mode;
    rootname+=".root";
    pedmode=pmode;
    int LED_amp=40;
    _hstFile = new TFile(rootname,"recreate");
    BookHistograms();
    GetHFPMap();
    //set plotting styles
    gStyle->SetCanvasColor(0);
    gStyle->SetPadColor(0);
    gStyle->SetCanvasBorderMode(0);
    gStyle->SetFrameBorderMode(0);
    gStyle->SetStatColor(0);
    gStyle->SetPadTickX(1);
    gStyle->SetPadTickY(1);


    //set file names
    stringstream out_fname;
    stringstream out_fname1;
    out_fname<<"SPEconstants_Run_"<<run<<"_"<<filname<<"_mode_"<<mode<<".txt";
    out_fname1<<"SPEspec_Run_"<<run<<"_"<<filname<<".txt";

    ofstream  constants_file(out_fname.str().c_str(),ios_base::trunc); 
    //ofstream  constants_file1(out_fname1.str().c_str(),ios_base::trunc); 
    constants_file<<"#Run "<<run<<endl;
    constants_file<<"#type SPE"<<endl;
    constants_file<<"#LED_amplitude "<<LED_amp<<endl;
    constants_file<<"#Robox Column iDepth iPhi iEta Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err"<<endl;

    out_fname.str("");
    out_fname<<"SPEdistributions_Run_"<<run<<".txt";

    out_fname.str("");
    out_fname<<"SPEextra_Run_"<<run<<".txt";
    //ofstream  extra_file(out_fname.str().c_str(),ios_base::trunc); 


    double scale = 1.0;
    scale = 2.6; //Need to scale up HF charge
    double fC2electrons = 6240.; //convert fC to #electrons

    char spename[128], pedname[128], spehistname[128], numname[128];

    TFile *tfLED = new TFile(fLEDname);
    TFile *tfPED = new TFile(fPEDname);


    //const int NnewBins = 106;
    //double binsX[NnewBins] = {0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};

    //const int NnewBins = 80;//75
    //double binsX[NnewBins] = {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84,87,90,93,96,99,102,105,108,111,114,117,120,123,126,129,132,135,138,141,144,147,150,153,156,159,162,165,168,171,174,177,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};	  

    const int NnewBins = 101;//75
    double binsX[NnewBins] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100};
    
    const int NnewBins_single = 57;
    double binsX_single[NnewBins] = {0,3,6,9,12,15,18,21,24,27,30,33,36,39,45,51,57,63,69,75,81,87,93,99,105,111,117,123,129,135,141,147,153,159,165,171,177,183,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};	  

    //default: 
    const int NnewBins_ped = 46;//75
    double binsX_ped[NnewBins] = {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84,87,90,93,96,99,102,120,138,156,174,200,230,266,316,378,456,500};
    double binsX_ped_single[NnewBins] = {0,3,6,9,12,15,18,21,24,27,30,33,36,39,45,51,57,63,69,75,81,87,93,99,120,138,156,174,200,230,266,316,378,456,500};
    const int NnewBins_ped_single = 31;
    //var1
    //  const int NnewBins_ped = 37;//75
    // double binsX_ped[NnewBins_ped] = {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84,87,90,93,96,99,200,350,500};

    //double binsX[NnewBins] = {0,6,12,18,24,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84,87,90,93,96,99,102,105,108,111,114,117,120,123,126,129,132,135,138,141,144,147,150,153,156,159,162,165,168,171,174,177,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};	 
    TH1F *hspe[8], *resid[8];
    if(!pedmode) {
        if(mode<3){ 
            for(int i=0; i<8; i++) hspe[i] = new TH1F(Form("hspe_pmt%i",i+1),Form("hspe_pmt%i",i+1),NnewBins-1,binsX);
            for(int i=0; i<8; i++) resid[i] = new TH1F(Form("resid_pmt%i",i+1),Form("resid_pmt%i",i+1),NnewBins-1,binsX);
        }
        else{
            for(int i=0; i<8; i++) hspe[i] = new TH1F(Form("hspe_pmt%i",i+1),Form("hspe_pmt%i",i+1),NnewBins_single-1,binsX_single);
            for(int i=0; i<8; i++) resid[i] = new TH1F(Form("resid_pmt%i",i+1),Form("resid_pmt%i",i+1),NnewBins_single-1,binsX_single);
        }
    }
    else if(pedmode) {
        if(mode<3){ 
            for(int i=0; i<8; i++) hspe[i] = new TH1F(Form("hspe_pmt%i",i+1),Form("hspe_pmt%i",i+1),NnewBins_ped-1,binsX);
            for(int i=0; i<8; i++) resid[i] = new TH1F(Form("resid_pmt%i",i+1),Form("resid_pmt%i",i+1),NnewBins_ped-1,binsX);
        }
        else{
            for(int i=0; i<8; i++) hspe[i] = new TH1F(Form("hspe_pmt%i",i+1),Form("hspe_pmt%i",i+1),NnewBins_ped_single-1,binsX_single);
            for(int i=0; i<8; i++) resid[i] = new TH1F(Form("resid_pmt%i",i+1),Form("resid_pmt%i",i+1),NnewBins_ped_single-1,binsX_single);
        }
    }
    for(int i=0; i<8; i++) hspe[i]->Sumw2();
    for(int i=0; i<8; i++) resid[i]->Sumw2();




    /* // int NDepth = 2; //number of depths
       int MinDepth = 1;
       int MaxDepth = 2;
       int MinEta = 29; 
       int MaxEta = 33; //41
    //int MinPhi = 41;
    //int MaxPhi = 53;
    int MinPhi = 1;
    int MaxPhi = 5; //71
    int NEta = 1+MaxEta-MinEta;
    int NPhi = 1+MaxPhi-MinPhi;*/

    //TCanvas *Carray[NDepth+1][MaxPhi+1];
    TCanvas *Carray[37][4];
    bool drawflag[37][4];  
    bool badfit[37][4][9];
    TH1F *LED[NDepth+1][MaxEta+1][MaxPhi+1];
    TH1F *PED[NDepth+1][MaxEta+1][MaxPhi+1];
//    TH1F *NumAbove[NDepth+1][MaxEta+1][MaxPhi+1];




    for(int iDepth = MinDepth; iDepth <= MaxDepth; iDepth++){
        for(int iPhi = MinPhi; iPhi <= MaxPhi; iPhi++){

            bool nonNull = false;

            for(int iEta = MinEta; iEta <= MaxEta; iEta++){

                if(mode==1) sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
                if(mode==2) sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d_FullSum",iDepth,iEta,iPhi);
                if(mode==3) sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d_eachTS",iDepth,iEta,iPhi);
                if(mode==4) sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d_eachTSsub",iDepth,iEta,iPhi);
                if(mode>4) sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d_TS_%i",iDepth,iEta,iPhi,mode-5);


                LED[iDepth][iEta][iPhi]=(TH1F *)tfLED->Get(spename);
                if(LED[iDepth][iEta][iPhi]) nonNull = true;
                //else cout<<"failed reg"<<endl;

                //sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
                PED[iDepth][iEta][iPhi]=(TH1F *)tfPED->Get(spename);

                sprintf(numname,"Analyzer/CommonDir/ResPlotDir/Num_Above_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
                //	cout<<"Getting numAbove"<<endl;
//                NumAbove[iDepth][iEta][iPhi]=(TH1F *)tfLED->Get(numname);
                //	if(!NumAbove[iDepth][iEta][iPhi]) cout<<"Failed"<<endl;

            }



            if(nonNull){ //only create canvas if distributions exist

            }

        }
    }



    int HV=0;
    int iEta, iPhi,iDepth;
    /*for(int iDepth = MinDepth; iDepth <= MaxDepth; iDepth++){
      for(int iPhi = MinPhi; iPhi <= MaxPhi; iPhi++){
      for(int iEta = MinEta; iEta <= MaxEta; iEta++){*/
    for(int irbx = 1; irbx<37; irbx++){
        for(int ibb= 1; ibb<4;ibb++){
            
            //if(irbx!=9 || ibb!=3) continue; // FIXME
            
            drawflag[irbx][ibb] = false;
            char canvname[16];
            sprintf(canvname, "c_%d_%d", irbx,ibb);
            Carray[irbx][ibb] = new TCanvas(canvname,canvname,1800,800);
            Carray[irbx][ibb]->Divide(4,2);
            for(int ipmt=1; ipmt<9;ipmt++){
                badfit[irbx][ibb][ipmt] = false;
                iEta = eta[irbx][ibb][ipmt];
                iPhi = phi[irbx][ibb][ipmt];
                iDepth = dep[irbx][ibb][ipmt];
                //cout<<iDepth<<" "<<iPhi<<" "<<iEta<<endl;
                // if(iEta!=38 || iPhi !=33 || iDepth !=1) continue;
                if(!LED[iDepth][iEta][iPhi]) {cout<<"Fail depth eta phi "<<iDepth<<" "<<iEta<<" "<<iPhi<<endl; continue;}

                sprintf(spehistname,"led %d %d %d",iDepth,iEta,iPhi);
                TH1F *hspe_temp = (TH1F *)LED[iDepth][iEta][iPhi]->Clone(spehistname);
                //	cout<<"post clone depth eta phi pmt int "<<iDepth<<" "<<iEta<<" "<<iPhi<<" "<<ipmt<<" "<<hspe_temp->Integral()<<endl;
                sprintf(spehistname,"ped %d %d %d",iDepth,iEta,iPhi);
                TH1F *hped = (TH1F *)PED[iDepth][iEta][iPhi]->Clone(spehistname);
                hspe[ipmt-1]->Reset();
                resid[ipmt-1]->Reset();
                sprintf (spehistname, "SumLED_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
                hspe[ipmt-1]->SetTitle(spehistname);
                sprintf(spehistname,"cp_Num_Above_Depth_%i_Eta_%i_Phi_%i",iDepth,iEta,iPhi);
//                TH1F *chg_share = new TH1F(spehistname,spehistname,10,0,10);

//                for(int ix=2;ix<=10;ix++){
//                    chg_share->SetBinContent(ix,NumAbove[iDepth][iEta][iPhi]->GetBinContent(ix));
//                } 
//                chg_share->SetBinContent(1,0);
//                float chg_frac = chg_share->Integral(3,10)/chg_share->Integral();

                //cout<<"preloop check"<<ipmt<<" integral "<<hspe_temp->Integral()<<endl;
                //combine bins of original SPE histogram
                for(int ib=1; ib<=hspe_temp->GetNbinsX(); ib++) {
                    double bin_center = hspe_temp->GetBinCenter(ib);

                    if(bin_center>hspe[ipmt-1]->GetXaxis()->GetXmax()) continue;
                    int newbin = hspe[ipmt-1]->FindBin(bin_center);
                    double new_content = hspe[ipmt-1]->GetBinContent(newbin) + hspe_temp->GetBinContent(ib);
                    double new_error = sqrt(pow(hspe[ipmt-1]->GetBinError(newbin),2)+pow(hspe_temp->GetBinError(ib),2));
                    hspe[ipmt-1]->SetBinContent(newbin,new_content);
                    hspe[ipmt-1]->SetBinError(newbin,new_error);
                }
                TH1F* hspe_unscaled = (TH1F*)hspe[ipmt-1]->Clone("hspe_unscaled");
                //renormalize bins of new SPE histogram
                for(int ib=1; ib<=hspe[ipmt-1]->GetNbinsX(); ib++) {
                    double new_content = hspe[ipmt-1]->GetBinContent(ib)/hspe[ipmt-1]->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
                    double new_error = hspe[ipmt-1]->GetBinError(ib)/hspe[ipmt-1]->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
                    hspe[ipmt-1]->SetBinContent(ib,new_content);
                    hspe[ipmt-1]->SetBinError(ib,new_error);
                }
                //	cout<<"pre temp check "<<ipmu<<" integral "<<hspe_temp->Integral()<<endl; 

                // ------------------------------
                // FIT 
                // ------------------------------
                if(hspe_temp->Integral()==0) continue;
                else drawflag[irbx][ibb] = true;	  
                Nev = hspe_temp->Integral()*hspe_temp->GetXaxis()->GetBinWidth(1);  

                //
                // Pedestal fit 
                //
                //TF1 *fped = new TF1("fped","gaus",0, 80);
                TF1 *fped;
                if(mode<3) fped= new TF1("fped","gaus",0, 20);
                else fped= new TF1("fped","gaus",0,15);
                hped->Fit(fped,"NQR");
                double pploc = fped->GetParameter(1), ppwidth = fped->GetParameter(2);
                // DEBUG	
                //cout<<"depth "<<iDepth<<" ieta "<<iEta<<" iphi "<<iPhi <<" pploc "<<pploc<<" ppwidth "<<ppwidth<<endl;
                //hspe->Fit(fped, "NQ", "", pploc - 3*ppwidth, pploc + ppwidth);  
                hspe[ipmt-1]->Fit(fped, "NQ", "", pploc - 2*ppwidth, pploc + 2*ppwidth);  

                // 
                //estimate SPE peak location
                // 
                int max_SPE_bin, maxbin, Nbins;
                double max_SPE_height=0, minheight, max_SPE_location;
                bool minflag = false;
                maxbin=hspe[ipmt-1]->FindBin(fped->GetParameter(1)); //location of pedestal peak
                minheight=hspe[ipmt-1]->GetBinContent(maxbin); //initialize minheight
                Nbins = hspe[ipmt-1]->GetNbinsX();
                for(int j=maxbin+1; j<Nbins-1; j++) { //start from pedestal peak and loop through bins
                    if(hspe[ipmt-1]->GetBinContent(j) > minheight && !minflag) minflag=true; //only look for SPE peak when minflag=true
                    if(hspe[ipmt-1]->GetBinContent(j) < minheight )  minheight = hspe[ipmt-1]->GetBinContent(j);
                    if(minflag && hspe[ipmt-1]->GetBinContent(j) > max_SPE_height){
                        max_SPE_bin = j;
                        max_SPE_location = hspe[ipmt-1]->GetBinCenter(max_SPE_bin);
                        max_SPE_height = hspe[ipmt-1]->GetBinContent(j);
                    }
                } //start from pedestal peak and loop through bins
                //find minimum bin between pedestal and SPE peaks
                hspe[ipmt-1]->GetXaxis()->SetRange(maxbin,max_SPE_bin);
                int minbin = hspe[ipmt-1]->GetMinimumBin(); 
                double minbin_location = hspe[ipmt-1]->GetBinCenter(minbin);
                hspe[ipmt-1]->GetXaxis()->SetRange(1,Nbins);	    

                TF1 *fit = new TF1("fit", FitFun, 0, 50, 5);

                double mu = - log(fped->Integral(0,100)/Nev); // f(0)  = exp(-par[0])
                if(mu<0 && pedmode ) mu=0.00001;
                if( mu<0 && !pedmode) mu=0.01;
                double gain_est = max_SPE_location-1.0*fped->GetParameter(1);
                //if(max_SPE_bin > (minbin+1)) fit->SetParameters(mu, 20, 1, gain_est, gain_est*0.5);
                if(max_SPE_bin > (minbin+1)) fit->SetParameters(mu, fped->GetParameter(1), fped->GetParameter(2), gain_est, gain_est*0.5);
                else fit->SetParameters(mu, fped->GetParameter(1), fped->GetParameter(2), 2.1*fped->GetParameter(2), 10); //case of no clear minimum; start looking for SPE peak at 2sigma away from pedestal peak
                if(pedmode && (mode==1 || mode==4)) fit->SetParLimits(0, 0, 0.000316);
                if(pedmode && mode!=1 && mode!=4) fit->SetParLimits(0, 0, 0.00005);
                else fit->SetParLimits(0, 0, 10);
                //fit->FixParameter(1, fped->GetParameter(1)); // FIXME
                //fit->FixParameter(2, fped->GetParameter(2)); // FIXME
                fit->SetParLimits(3, fped->GetParameter(2)*2, 350);
                fit->SetParLimits(4, fped->GetParameter(2)*1.01, 250);

                fit->SetParLimits(5, 1.0, 4.0);

                double maxfitrange = 100.;    
                double minfitrange = 0.;
                hspe[ipmt-1]->Fit(fit, "MNQLB", "", minfitrange, maxfitrange);
                //cout<<"initial p: "<<fped->GetParameter(1)<<" "<<fped->GetParError(1)<<" "<<fped->GetParameter(2)<<" "<<fped->GetParError(2)<<" "<<fit->GetParameter(4)<<" "<<fit->GetParError(4)<<" "<<fit->GetParameter(3)<<" "<<fit->GetParError(3)<<endl;
                maxfitrange = fped->GetParameter(1)+4*fit->GetParameter(3)+fit->GetParameter(4)+30;
                //if(maxfitrange<100) maxfitrange=100;
                // cout<<"new min ="<<minfitrange<<endl;
                // cout<<"new max ="<<maxfitrange<<endl;
                if(100<maxfitrange) maxfitrange = 100;
                hspe[ipmt-1]->Fit(fit, "MNQLB", "", minfitrange, maxfitrange);
                //cout<<"chi2 = "<<fit->GetChisquare()<<endl;
                //calculate NDOF of fit excluding bins with 0 entries
                int myNDOF=-5; //three free parameters // FIXME
                for(int j=hspe[ipmt-1]->FindBin(minfitrange); j<=hspe[ipmt-1]->FindBin(maxfitrange); j++) { //loop through fitted spe bins
                    if(hspe[ipmt-1]->GetBinContent(j)) myNDOF++;
                } //loop through fitted spe bins

                //cout<<"ndf= "<<myNDOF<<endl;
                //calculate means and integrals of the fit and data
                double fint, fint_error, hint, favg, havg;
                int temp_lowbin, temp_highbin;
                temp_lowbin = hspe[ipmt-1]->FindBin(minfitrange);
                temp_highbin = hspe[ipmt-1]->FindBin(maxfitrange);
                hspe_unscaled->GetXaxis()->SetRangeUser(minfitrange, maxfitrange);
                havg = hspe_unscaled->GetMean();
                hint = hspe[ipmt-1]->Integral(temp_lowbin,temp_highbin,"width");
                double min_frange = hspe[ipmt-1]->GetBinLowEdge(temp_lowbin);
                favg = fit->Mean(min_frange, maxfitrange);
                fint = fit->Integral(min_frange, maxfitrange);
                //fint_error = fit->IntegralError(min_frange, maxfitrange);

                double PE5int = 0; //integral of events with >=5 PE
                double PE5loc =  fped->GetParameter(1)+ 5*fit->GetParameter(3);
                if(PE5loc>500) PE5int = 0;
                else {
                    int PE5bin =  hspe_temp->FindBin(PE5loc);
                    temp_highbin = hspe_temp->FindBin(maxfitrange)-1;
                    PE5int =  hspe_temp->Integral(PE5bin,temp_highbin,"width");
                }
                int PE5flag = 0;
                if(PE5int/hint>0.05) PE5flag = 1; //set flag if more than 5% of events in the fit correspond to >=5PE
                //=========================================    
                //for(int i1=1;i1<hspe->GetNbinsX();i1++){
                //constants_file1<<HV<<"\t"<<iDepth<<"\t"<<iEta<<"\t"<<iPhi<<"\t"<<2.6*hspe->GetBinCenter(i1)<<"\t"<<hspe->GetBinContent(i1)<<"\t"<<fit->Eval(hspe->GetBinCenter(i1))<<"\n";
                //}
                //=========================================    

                //printf("%d\n",myNDOF);
                //output calibrations constants
                //constants_file<<endl<<"LED_amplitude HV Spigot Channel Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;
                //constants_file<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF/*fit->GetNDF()*/<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;


                /* Ped_mean[iDepth]->Fill(iEta,iPhi,fped->GetParameter(1));
                   Ped_mean_err[iDepth]->Fill(iEta,iPhi,fped->GetParError(1));
                   Ped_RMS[iDepth]->Fill(iEta,iPhi,fped->GetParameter(2));
                   Ped_RMS_err[iDepth]->Fill(iEta,iPhi,fped->GetParError(2));
                   Gain[iDepth]->Fill(iEta,iPhi,fit->GetParameter(3));
                   Gain_err[iDepth]->Fill(iEta,iPhi,fit->GetParError(3));
                   SPEPeak_RMS[iDepth]->Fill(iEta,iPhi,fit->GetParameter(4));
                   SPEPeak_RMS_err[iDepth]->Fill(iEta,iPhi,fit->GetParError(4));
                   Normalized_Chi2[iDepth]->Fill(iEta,iPhi,fit->GetChisquare()/myNDOF);
                   MeanPE_fit[iDepth]->Fill(iEta,iPhi,fit->GetParameter(0));
                   MeanPE_fit_err[iDepth]->Fill(iEta,iPhi,fit->GetParError(0));
                   MeanPE_estimate[iDepth]->Fill(iEta,iPhi,mu);
                //constants_file<<fit->GetParameter(3)<<" "<<fit->GetParError(3)<<endl;
                 */
                /*
                   if(iDepth==2 && iPhi==53 && iEta==36){
                   cout<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<gain_est<<" "<<fit->GetParameter(3)<<endl;
                   cout<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;
                   }
                 */
                int col = column[iPhi][iEta][iDepth];
                int rbx = robox[iPhi][iEta][iDepth];


                //orig	constants_file<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<fped->GetParameter(1)<<" "<<fped->GetParError(1)<<" "<<fped->GetParameter(2)<<" "<<fped->GetParError(2)<<" "<<fit->GetParameter(4)<<" "<<fit->GetParError(4)<<" "<<fit->GetParameter(3)<<" "<<fit->GetParError(3)<<" "<<fit->GetChisquare()/myNDOF/*fit->GetNDF()*/<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;
                //orig from RH : using fped for pedestal peak info
                //constants_file<<rbx<<" "<<col<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<fped->GetParameter(1)<<" "<<fped->GetParError(1)<<" "<<fped->GetParameter(2)<<" "<<fped->GetParError(2)<<" "<<fit->GetParameter(4)<<" "<<fit->GetParError(4)<<" "<<fit->GetParameter(3)<<" "<<fit->GetParError(3)<<" "<<fit->GetChisquare()/myNDOF/*fit->GetNDF()*/<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<endl;
                constants_file<<rbx<<" "<<col<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<fit->GetParameter(1)<<" "<<fit->GetParError(1)<<" "<<fit->GetParameter(2)<<" "<<fit->GetParError(2)<<" "<<fit->GetParameter(4)<<" "<<fit->GetParError(4)<<" "<<fit->GetParameter(3)<<" "<<fit->GetParError(3)<<" "<<fit->GetChisquare()/myNDOF/*fit->GetNDF()*/<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<endl;

                //cout<<"irbx ibb ipmt"<<irbx<<" "<<ibb<<" "<<ipmt<<endl;
                //cout<<"iPhi iEta iDepth "<<iPhi<<" "<<iEta<<" "<<iDepth<<" col RBX "<<col<<" "<<rbx<<endl;
                Ped_mean[0]->Fill(col,rbx,fit->GetParameter(1));
                Ped_mean_err[0]->Fill(col,rbx,fit->GetParError(1));
                Ped_RMS[0]->Fill(col,rbx,fit->GetParameter(2));
                Ped_RMS_err[0]->Fill(col,rbx,fit->GetParError(2));
                Gain[0]->Fill(col,rbx,fit->GetParameter(3));
                Gain_err[0]->Fill(col,rbx,fit->GetParError(3));
                SPEPeak_RMS[0]->Fill(col,rbx,fit->GetParameter(4));
                SPEPeak_RMS_err[0]->Fill(col,rbx,fit->GetParError(4));
                Normalized_Chi2[0]->Fill(col,rbx,fit->GetChisquare()/myNDOF);
                MeanPE_fit[0]->Fill(col,rbx,fit->GetParameter(0));
                MeanPE_fit_err[0]->Fill(col,rbx,fit->GetParError(0));
                MeanPE_estimate[0]->Fill(col,rbx,mu);
                //ShareMap[0]->Fill(col,rbx,chg_frac);


                proj_Ped_mean[0]->Fill(fit->GetParameter(1));
                proj_Ped_mean_err[0]->Fill(fit->GetParError(1));
                proj_Ped_RMS[0]->Fill(fit->GetParameter(2));
                proj_Ped_RMS_err[0]->Fill(fit->GetParError(2));
                proj_Gain[0]->Fill(fit->GetParameter(3));
                proj_Gain_err[0]->Fill(fit->GetParError(3));
                proj_SPEPeak_RMS[0]->Fill(fit->GetParameter(4));
                proj_SPEPeak_RMS_err[0]->Fill(fit->GetParError(4));
                proj_Normalized_Chi2[0]->Fill(TMath::Log10(fit->GetChisquare()/myNDOF));
                proj_MeanPE_fit[0]->Fill(TMath::Log10(fit->GetParameter(0)));
                proj_MeanPE_fit_err[0]->Fill(TMath::Log10(fit->GetParError(0)));
                proj_MeanPE_estimate[0]->Fill(TMath::Log10(mu));
                //proj_ShareMap[0]->Fill(chg_frac);
                /*float frac = ROOT::Math::gaussian_cdf_c(100.,sqrt(pow(fit->GetParameter(4),2)+pow(fped->GetParameter(2),2)) , fit->GetParameter(3)+fped->GetParameter(1));
                  float trig = frac*fit->GetParameter(0)*pow(10,9)/(25.);*/
                float frac = hspe[ipmt-1]->Integral(hspe[ipmt-1]->FindBin(100),hspe[ipmt-1]->FindBin(499),"width")/ hspe[ipmt-1]->Integral(hspe[ipmt-1]->FindBin(0),hspe[ipmt-1]->FindBin(499),"width");
                float trig = frac*pow(10,9)/(100.);
                Selftrigger_estimate[0]->Fill(col,rbx,trig);
                proj_Selftrigger_estimate[0]->Fill(trig);

                frac = fit->Integral(100,499)/fit->Integral(0,499);
                trig = frac*pow(10,9)/(100.);
                Selftrigger_integral[0]->Fill(col,rbx,trig);
                proj_Selftrigger_integral[0]->Fill(trig);



                if(!pedmode){
                    if(fit->GetChisquare()/myNDOF > 20 || fit->GetParError(3) > 0.6){
                        badfit[irbx][ibb][ipmt] = true;
                    }
                }
                else if(pedmode){
                    if(fit->GetChisquare()/myNDOF > 400 || fit->GetParError(3) > 20){
                        badfit[irbx][ibb][ipmt] = true;
                    }
                }
                //cout<<"eta phi depth pmt "<<iEta<<" "<<iPhi<<" "<<iDepth<<" "<<ipmt<<endl;
                Carray[irbx][ibb]->cd(ipmt);
                // TCanvas *c1 = new TCanvas("c1","c1",800,800);
                TPad *pad1 = new TPad("pad1","pad1",0,0.33,1,1);
                TPad *pad2 = new TPad("pad2","pad2",0,0.05,1,0.33);
                pad1->SetBottomMargin(0.00001);
                pad1->SetBorderMode(0);
                pad1->SetLogy();
                pad2->SetTopMargin(0.00001);
                pad2->SetBottomMargin(0.3);
                pad2->SetBorderMode(0);
                pad1->Draw();
                pad2->Draw();
                pad1->cd();
                /*gPad->SetBorderMode(0);
                  gPad->SetBorderSize(0);
                  gPad->SetRightMargin(0.01);
                  gPad->SetBottomMargin(0.1);
                  gPad->SetLogy(true);*/
                hspe[ipmt-1]->GetXaxis()->SetRangeUser(0, 100 /*200*/ /*300*//*508*/);
                hspe[ipmt-1]->SetLineColor(kBlue);
                //hspe[ipmt-1]->SetLineColor(kBlack);
                hspe[ipmt-1]->SetMarkerColor(kBlack);
                hspe[ipmt-1]->SetMarkerSize(1);
                hspe[ipmt-1]->SetMarkerStyle(20);
                hspe[ipmt-1]->SetStats(false);

                hspe[ipmt-1]->Draw("HIST");

                fit->SetLineWidth(1);
                fit->SetLineColor(kRed);
                fit->SetRange(minfitrange,maxfitrange);
                fit->Draw("same");
                myText(0.5,0.83,Form("Gain = %.2f +/- %.2f",fit->GetParameter(3),fit->GetParError(3)),1,0.05);
                myText(0.5,0.76,Form("SPE RMS = %.2f +/- %.2f",fit->GetParameter(4),fit->GetParError(4)),1,0.05);
                if(pedmode) myText(0.5,0.69,Form("Log(Mean PE) = %.2f",TMath::Log10(fit->GetParameter(0))),1,0.05);
                else myText(0.5,0.69,Form("Mean PE = %.2f",fit->GetParameter(0)),1,0.06);
                myText(0.5,0.62,Form("Chi^{2}/ndf =  %.2f",fit->GetChisquare()/myNDOF/*fit->GetNDF()*/),1,0.05);
                myText(0.5,0.55,Form("Ped = %.2f +/- %.2f",fit->GetParameter(1),fit->GetParError(1)),1,0.05);
                myText(0.5,0.48,Form("Ped RMS = %.2f +/- %.2f",fit->GetParameter(2),fit->GetParError(2)),1,0.05);
                /*	TArrow first = TArrow(maxfitrange,2,maxfitrange,0.1,0.04,"");
                    first.DrawLine(maxfitrange,2,maxfitrange,0.1);*/
                
                // Draw SPE peak 
                TF1 *spefunc = new TF1("spefunc",SPEFunc,0,50,5); 
                spefunc->SetParameters(fit->GetParameter(0),fit->GetParameter(1),fit->GetParameter(2),fit->GetParameter(3),fit->GetParameter(4));
                spefunc->SetLineColor(kGreen);
                spefunc->SetLineWidth(1);
                spefunc->Draw("same");
                
                // Draw PED peak 
                TF1 *pedfunc = new TF1("pedfunc",PEDFunc,0,50,3); 
                pedfunc->SetParameters(fit->GetParameter(0),fit->GetParameter(1),fit->GetParameter(2));
                pedfunc->SetLineColor(kBlack);
                pedfunc->SetLineWidth(1);
                pedfunc->Draw("same");
                
                pad2->cd();

                for(int k=0;k<=hspe[ipmt-1]->FindBin(maxfitrange);k++){
                    Double_t diff = hspe[ipmt-1]->GetBinContent(k)/fit->Eval(hspe[ipmt-1]->GetBinCenter(k));
                    Double_t error = hspe[ipmt-1]->GetBinError(k)/fit->Eval(hspe[ipmt-1]->GetBinCenter(k));
                    resid[ipmt-1]->SetBinContent(k,diff);
                    resid[ipmt-1]->SetBinError(k,error);
                    //if(hspe[ipmt-1]->GetBinContent(k)) resid[ipmt-1]->SetBinContent(k,(hspe[ipmt-1]->GetBinContent(k)-fit->Eval(hspe[ipmt-1]->GetBinCenter(k)))/hspe[ipmt-1]->GetBinError(k));
                }

                resid[ipmt-1]->GetXaxis()->SetRangeUser(0, 100 /*200*/);
                resid[ipmt-1]->SetMaximum(3);
                //resid[ipmt-1]->SetMinimum(-2);
                resid[ipmt-1]->SetLineColor(kBlack);
                resid[ipmt-1]->SetMarkerStyle(20);
                resid[ipmt-1]->SetMarkerSize(1);
                resid[ipmt-1]->SetLabelSize(0.15);
                resid[ipmt-1]->SetLabelSize(0.15,"Y");
                resid[ipmt-1]->SetStats(false);
                resid[ipmt-1]->SetTitle("");
                resid[ipmt-1]->SetXTitle("LADC counts");
                resid[ipmt-1]->GetXaxis()->SetTitleSize(0.15);
                resid[ipmt-1]->Draw("PE");
                //resid[ipmt-1]->Delete();
            }

            if(drawflag[irbx][ibb]) { //draw plots of fit if data for the HV is present
                stringstream plot_name;
                plot_name<<"Plots/SPEFits_Run_"<<run<<"_mode_"<<mode<<"_Robox"<<irbx<<"_BB"<<ibb<<"_"<<filname<<".pdf";
                Carray[irbx][ibb]->SaveAs(plot_name.str().c_str());
                plot_name.str( std::string() );
            }

        }


    }

/*
    for(int irbx = 1; irbx<37; irbx++){
        for(int ibb= 1; ibb<4;ibb++){
            for(int ipmt=1; ipmt<9;ipmt++){
            }
        }
    }
*/
    _hstFile->Write();
    _hstFile->Close();
    constants_file.close();
    //constants_file1.close();

}
Ejemplo n.º 9
0
const UChar *UnicodeReader::readFile(const char *fileName, GUISupport *guiSupport, int32_t &charCount)
{
    FILE *f;
    int32_t fileSize;
    
    UChar *charBuffer;
    char *byteBuffer;
    char startBytes[4] = {'\xA5', '\xA5', '\xA5', '\xA5'};
    char errorMessage[128];
    const char *cp = "";
    int32_t signatureLength = 0;
    
    f = fopen(fileName, "rb");
    
    if( f == NULL ) {
        sprintf(errorMessage,"Couldn't open %s: %s \n", fileName, strerror(errno));
        guiSupport->postErrorMessage(errorMessage, "Text File Error");
        return 0;
    }
    
    fseek(f, 0, SEEK_END);
    fileSize = ftell(f);

    fseek(f, 0, SEEK_SET);
    fread(startBytes, sizeof(char), 4, f);

    if (startBytes[0] == '\xFE' && startBytes[1] == '\xFF') {
        cp = "UTF-16BE";
        signatureLength = 2;
    } else if (startBytes[0] == '\xFF' && startBytes[1] == '\xFE') {
        if (startBytes[2] == '\x00' && startBytes[3] == '\x00') {
            cp = "UTF-32LE";
            signatureLength = 4;
        } else {
            cp = "UTF-16LE";
            signatureLength = 2;
        }
    } else if (startBytes[0] == '\xEF' && startBytes[1] == '\xBB' && startBytes[2] == '\xBF') {
        cp = "UTF-8";
        signatureLength = 3;
    } else if (startBytes[0] == '\x0E' && startBytes[1] == '\xFE' && startBytes[2] == '\xFF') {
        cp = "SCSU";
        signatureLength = 3;
    } else if (startBytes[0] == '\x00' && startBytes[1] == '\x00' &&
        startBytes[2] == '\xFE' && startBytes[3] == '\xFF') {
        cp = "UTF-32BE";
        signatureLength = 4;
    } else {
        sprintf(errorMessage, "Couldn't detect the encoding of %s: (%2.2X, %2.2X, %2.2X, %2.2X)\n", fileName,
                    BYTE(startBytes[0]), BYTE(startBytes[1]), BYTE(startBytes[2]), BYTE(startBytes[3]));
        guiSupport->postErrorMessage(errorMessage, "Text File Error");
        fclose(f);
        return 0;
    }
        
    fileSize -= signatureLength;
    fseek(f, signatureLength, SEEK_SET);
    byteBuffer = new char[fileSize];
    
    if(byteBuffer == 0) {
        sprintf(errorMessage,"Couldn't get memory for reading %s: %s \n", fileName, strerror(errno));
        guiSupport->postErrorMessage(errorMessage, "Text File Error");
        fclose(f);
        return 0;
    }
    
    fread(byteBuffer, sizeof(char), fileSize, f);
    if( ferror(f) ) {
        sprintf(errorMessage,"Couldn't read %s: %s \n", fileName, strerror(errno));
        guiSupport->postErrorMessage(errorMessage, "Text File Error");
        fclose(f);
        delete[] byteBuffer;
        return 0;
    }
    fclose(f);
    
    UnicodeString myText(byteBuffer, fileSize, cp);

    delete[] byteBuffer;
    
    charCount = myText.length();
    charBuffer = LE_NEW_ARRAY(UChar, charCount + 1);
    if(charBuffer == 0) {
        sprintf(errorMessage,"Couldn't get memory for reading %s: %s \n", fileName, strerror(errno));
        guiSupport->postErrorMessage(errorMessage, "Text File Error");
        return 0;
    }
    
    myText.extract(0, myText.length(), charBuffer);
    charBuffer[charCount] = 0;    // NULL terminate for easier reading in the debugger
    
    return charBuffer;
}
Ejemplo n.º 10
0
// *************************************** //
// this is a function that takes a set of  //
// histograms and draws them on a canvas   //
// in a stack, returning the canvas        //
// just for MC- no ratio and no data.      //
// This one includes syst and stat or just //
// stat errors                             //
// *************************************** //
TCanvas* drawPlots::plot_MC_noRatio_wError(std::vector<TH1D*> histos, std::vector<std::string> names, std::string axisName, TH1D* signal, TH1D* errDown, TH1D* errUp){

   const unsigned int MAINPLOT_WIDTH  = 800;
   const unsigned int MAINPLOT_HEIGHT = 600;
   
   
   TCanvas* canvas = new TCanvas("canvas","canvas",0,0,MAINPLOT_WIDTH,MAINPLOT_HEIGHT);
   
   canvas->SetMargin(0.,0.,0.,0.);
   canvas->cd();
   
   double main_y_max = -99;
   double main_y_min = -99;
   double main_x_max = -99;
   double main_x_min = -99;
   for(int a=0; a<histos.size(); a++){
      GetAxisLimits(histos[a], main_x_min, main_x_max, main_y_min, main_y_max);
   }
   
   // create main pad
   TPad* mainPad = new TPad("main","main",0.,0.,1.,1.);
   mainPad->SetMargin(0.15,0.05,0.15,.05); // left, right, bottom, top
   mainPad->Draw();
   mainPad->cd();
   
   SetAtlasStyle();

   THStack* Stack = new THStack();
   std::string title = std::string(";") + axisName + ";Events";
   Stack->SetTitle(title.c_str());
   
   for(int b=0; b<histos.size(); b++){
      histos[b]->SetLineColor(1);
      histos[b]->SetFillColor(tools::setColor(names[b]));
      Stack->Add(histos[b]);
   }
   
   main_y_max = main_y_max*1.5;
   Stack->SetMaximum(main_y_max);
   Stack->Draw("hist");
   
   errDown->Draw("E2same");
   errUp->Draw("E2Same");
   
   signal->SetLineStyle(2);
   signal->SetLineColor(kRed);
   signal->Draw("hist same");
   
   TLegend* leg = new TLegend(0.7,0.7,0.93,0.9);
   leg->SetFillStyle(0);
   leg->SetBorderSize(0);
   leg->AddEntry(signal, "Signal", "f");
   for(int q=0; q<histos.size(); q++){
      leg->AddEntry(histos[q], names[q].c_str(), "f");
   }
   leg->Draw("lpe");
   
   ATLAS_LABEL(0.2,0.85,1);
   char text[]="#sqrt{s}=8 TeV";
   myText(0.2,0.7,1,text);
   
   return canvas;
}
Ejemplo n.º 11
0
// *************************************** //
// this is a function that takes a set of  //
// histograms and draws them on a canvas   //
// in a stack, returning the canvas.       //
// It also plots the signal as a dashed    //
// line and the data with a ratio at the   //
// the bottom of data/allBackgrounds       //
//                                         //
// This one is supposed to make plots for  //
// the paper draft                         //
// *************************************** //
TCanvas* drawPlots::plotAll_VLQ_paperStyle(std::vector<TH1D*> histos, std::vector<std::string> names, std::string axisName, std::vector<TH1D*> signal, TH1D* data, TGraphAsymmErrors* err, bool doLogAxis, std::string extraTag){

   const unsigned int CANVAS_WIDTH  = 720;
   const unsigned int CANVAS_HEIGHT = 750;
   const double RATIOPLOT_YAXIS_TITLE_OFFSET = 0.75;
   const double RATIOPLOT_YAXIS_TITLE_SIZE   = 0.11;
   const double RATIOPLOT_YAXIS_LABEL_SIZE   = 0.09;  
   const double RATIOPLOT_XAXIS_TITLE_OFFSET = 1.6;
   const double RATIOPLOT_XAXIS_TITLE_SIZE   = 0.11;
   const double RATIOPLOT_XAXIS_LABEL_SIZE   = 0.09;
   
   TCanvas* canvas = new TCanvas("canvas","canvas",0,0,CANVAS_WIDTH,CANVAS_HEIGHT);
   
   canvas->SetMargin(0.,0.,0.,0.);
   canvas->Clear();
   //canvas->cd();
   
   SetAtlasStyle();
   gStyle->SetHistLineWidth(1.);
   gStyle->SetErrorX(0);

   err->SetLineColor(kWhite);
   err->SetLineWidth(0);

   // create histogram to store all backgrounds
   TH1D* allBackgrounds;
   bool gotSomething=false;
   for(int c=0; c<signal.size(); c++){
     if(signal[c]){
       allBackgrounds = (TH1D*)signal[c]->Clone("all_backgrounds");
       gotSomething=true;
     }
   }

   if(!gotSomething && data){
     allBackgrounds = (TH1D*)data->Clone("all_backgrounds");
     gotSomething=true;
   }
   if(!gotSomething){
     for(int b=0; b<histos.size(); b++){
       if(histos[b] && !gotSomething){
	 allBackgrounds = (TH1D*)histos[b]->Clone("all_backgrounds");
	 gotSomething=true;
       }
     }
   }

   if(!gotSomething){
     std::cout << "Error: could not find any background, data, or signal for this plot" << std::endl;
     return canvas;
   }
   
   // set all bins to zero
   for(int i=0; i<=allBackgrounds->GetNbinsX()+1; i++)
     allBackgrounds->SetBinContent(i,0);

   // go through histos and combine the histograms that need to be combined
   // WZ stays separate, ttV stays separate, all others become "Other bkg"
   TH1D* otherBkgs=0; TH1D* ttbarX=0; TH1D* WZ_Sherpa=0;
   for(int cc=0; cc<histos.size(); cc++){
     if(histos[cc]){
       for(int j=0; j<=allBackgrounds->GetNbinsX()+1; j++){
	 double binContent=allBackgrounds->GetBinContent(j)+histos[cc]->GetBinContent(j);
	 allBackgrounds->SetBinContent(j,binContent);
       }
       
       if(names[cc]=="ttbarX")
	 ttbarX=(TH1D*)histos[cc]->Clone("ttbarX_new");
       else if(names[cc]=="WZ_Sherpa")
	 WZ_Sherpa=(TH1D*)histos[cc]->Clone("WZ_new");
       else{

	 if(!otherBkgs)
	   otherBkgs=(TH1D*)histos[cc]->Clone("other_bkg_new");
	 else
	   otherBkgs->Add(histos[cc]);
       }
     }
   }

   // make stack of backgrounds, fill backgrounds histogram
   THStack* Stack = new THStack();
   if(ttbarX){
     ttbarX->SetLineColor(kGray);
     ttbarX->SetFillColor(kGray);
     Stack->Add(ttbarX);
   }
   if(WZ_Sherpa){
     WZ_Sherpa->SetLineColor(kBlue-9);
     WZ_Sherpa->SetFillColor(kBlue-9);
     Stack->Add(WZ_Sherpa);
   }
   if(otherBkgs){
     otherBkgs->SetLineColor(kOrange-2);
     otherBkgs->SetFillColor(kOrange-2);
     Stack->Add(otherBkgs);
   }

   TH1D* backgroundsForRatio = (TH1D*)allBackgrounds->Clone("bkgds_for_ratio");

   // create main pad
   const double mainPad_ylow  = 0.3;
   const double mainPad_yhigh = 0.95;
   const double mainPad_xlow = 0.;
   const double mainPad_xhigh = 0.95;
   const double pad_margin_left = 0.2;
   const double pad_margin_right  = 0.02;
   double main_y_max = -99;
   double main_y_min = -99;

   TPad* mainPad = new TPad("main","main",mainPad_xlow,mainPad_ylow,mainPad_xhigh,mainPad_yhigh);
   mainPad->SetMargin(pad_margin_left,pad_margin_right,0.,.05); // left, right, bottom, top
   mainPad->Draw();
   mainPad->cd();

   // find max y
   if(allBackgrounds){
     int maxBinBkg = allBackgrounds->GetMaximumBin();
     double bkgYmax = allBackgrounds->GetBinContent(maxBinBkg);
     main_y_max = bkgYmax;
   }
   if(data){
     int maxBinData = data->GetMaximumBin();
     double dataYmax = data->GetBinContent(maxBinData);
     if(dataYmax > main_y_max) main_y_max = dataYmax;
   }
   if(main_y_max < .002) main_y_max = .1;

   if(doLogAxis){
     mainPad->SetLogy();
     main_y_min = 0.07;
     main_y_max*=60;
   }else{
     main_y_min = 0.001;
     main_y_max*=1.6;
   }

   // draw axis
   allBackgrounds->SetMaximum(main_y_max);
   allBackgrounds->SetMinimum(main_y_min);
   std::string title = std::string(";") + axisName + ";Events";
   std::stringstream binw; 
   
   binw<<allBackgrounds->GetBinWidth(1);
   std::string width = binw.str();
   if (axisName.find("GeV") != std::string::npos){
     width += " GeV";
     title += " / "+width;
   }
   allBackgrounds->SetTitle(title.c_str());   
   allBackgrounds->GetYaxis()->SetTitleOffset(1.4);
   allBackgrounds->GetYaxis()->SetTitleSize(0.06);
   allBackgrounds->GetXaxis()->SetTitleOffset(1.2);
   allBackgrounds->GetYaxis()->SetLabelSize(0.04);
   allBackgrounds->GetXaxis()->SetLabelSize(0.04);
   allBackgrounds->Draw("hist");

   // draw stack with error
   Stack->Draw("hist same");
   if(err){
     err->Draw("E2 same");
   }

   // make error histograms for the ratio plot
   TGraphAsymmErrors* ratioErr = tools::getRatio(err, backgroundsForRatio);

   // draw data
   if(data)
      data->Draw("e same");

   // draw signal
   if(signal[0]){
     signal[0]->SetLineStyle(2);
     signal[0]->SetLineColor(kRed+2);//kGreen+3 before
     signal[0]->SetLineWidth(5);
     signal[0]->Draw("hist same");
   }
   if(signal.size() > 1){
     if(signal[1]){
       //signal[1]->SetLineStyle(2);
       signal[1]->SetLineColor(kRed+2);
       signal[1]->SetLineWidth(4);
       signal[1]->Draw("hist same");
     }
     if(signal.size() > 2){
       if(signal[2]){
	 //signal[2]->SetLineStyle(2);
	 signal[2]->SetLineColor(kBlue+2);
	 signal[2]->SetLineWidth(4);
	 signal[2]->Draw("hist same");
       }
     }
   }
   allBackgrounds->Draw("axis same");

   // draw legend
   float leg_height = 0.3;
   float leg_width = 0.2;
   float leg_xoffset = 0.74;
   float leg_yoffset = 0.77;
   
   TLegend* leg = new TLegend(leg_xoffset,leg_yoffset-leg_height/2,leg_xoffset+leg_width,leg_yoffset+leg_height/2);
   leg->SetFillColor(0);
   leg->SetFillStyle(0);
   leg->SetBorderSize(0);
   leg->SetTextFont(52);
   leg->SetTextSize(0.033);
   
   // currently assuming first signal is Tbq (single T production), second is TTS, third is BBS
   leg->AddEntry(data, "data 2012");
   leg->AddEntry(otherBkgs, "Other bkg.", "f");
   leg->AddEntry(WZ_Sherpa, "WZ", "f");
   leg->AddEntry(ttbarX, "t#bar{t}+X", "f");
   if(signal.size()>1){
     if(signal[2])
       leg->AddEntry(signal[2], "B#bar{B} (650 GeV)", "l");
     if(signal[1])
       leg->AddEntry(signal[1], "T#bar{T} (650 GeV)", "l");
   }   
   if(signal[0])
     leg->AddEntry(signal[0], "T#bar{b}q (650 GeV)", "l");
   
   
   leg->AddEntry( err, "Uncertainty", "f");


   leg->Draw("lpe");
   
   ATLAS_LABEL(0.24,0.86,1);
   myText(0.36, 0.86, 1, .05, "Internal");
   char text[]="#sqrt{s}=8 TeV";
   myText(0.55,0.77,1,.04, text);
   char text_L[]="#int L dt = 20.3 fb^{-1}";
   myText(0.5, 0.84,1, .04, text_L);
   if(extraTag!=""){
     char tag_txt[extraTag.size()];
     strcpy(tag_txt, extraTag.c_str());
     if(extraTag.size()>15)
       myText(0.7, 0.56, 1, .04, tag_txt);
     else
       myText(0.75, 0.56, 1, .04, tag_txt);
   }
   char text_tri[]="Trilepton";
   myText(0.55, 0.70, 1, .04, text_tri);

   /*
   double back_int = allBackgrounds->Integral(0,allBackgrounds->GetNbinsX()+1);
   int t;
   char inText[100];
   if(back_int > 10000.)
     t=sprintf(inText, "N_{B} = %.3e", back_int);
   else
     t=sprintf(inText, "N_{B} = %.1f", back_int);
   myText(0.24, 0.6, 1, .04, inText);
   if(data)
     t=sprintf(inText, "N_{D} = %.0f", data->Integral(0,data->GetNbinsX()+1));
   else
     t=sprintf(inText, "N_{D} = %.0f", 0.);
   myText(0.24, 0.7, 1, .04, inText);
   */
   canvas->cd();
   
   // Draw Ratio plot
   // 1.6 and .4 are the normal ones
   double ratio_max = 3.2;
   double ratio_min = -.9;
  
   double pad_xlow = 0.;
   double pad_xhigh = 0.95;
   double pad_ylow = 0.0;
   double pad_yhigh = 0.3;
   
   const char* pad_name = "pad";
   TPad* pad4ratio = new TPad(pad_name,pad_name,pad_xlow,pad_ylow,pad_xhigh,pad_yhigh);

   pad4ratio->SetMargin(pad_margin_left,pad_margin_right,0.46,0.);
   pad4ratio->Draw();
   pad4ratio->cd();

   TH1D* ratioPlot;
   if(data)
     ratioPlot = (TH1D*)data->Clone("ratio");
   else if (signal[0]) 
     ratioPlot = (TH1D*)signal[0]->Clone("ratio"); // just for getting the axis
   else if (signal[1])
     ratioPlot = (TH1D*)signal[1]->Clone("ratio");
   else
     return canvas;

   ratioPlot->SetTitle("");
   ratioPlot->Divide(allBackgrounds);
   ratioPlot->GetYaxis()->SetTitle("Data / bkg");
   ratioPlot->GetXaxis()->SetTitle(axisName.c_str());

   if (data){
     
     // here change ratio_min and ratio_max if the ratio plot is quite flat
     double maxDeviation=0;
     double minDeviation=10.;
     double tempDev=0;
     for(int ibin=1; ibin<=allBackgrounds->GetNbinsX(); ibin++){
       double binContent = ratioPlot->GetBinContent(ibin);
       tempDev=0;
       if(binContent>0 && binContent < 10) tempDev = std::abs(binContent-1.);
       if(tempDev > maxDeviation) maxDeviation = tempDev;
       if(tempDev < minDeviation) minDeviation = tempDev;
     }
     if(maxDeviation < 0.6){
       ratio_max = 1.6;
       ratio_min = 0.4;
     }
     else if(maxDeviation < 0.1){
       ratio_max = 1.12;
       ratio_min = 0.88;
     }
     else if(maxDeviation < 0.2){
       ratio_max = 1.25;
       ratio_min = .75;
     }
     if(minDeviation > 1.5){
       if(minDeviation > 2.)
	 ratio_max = 2.7;
       else
	 ratio_max = 2.2;
     }
     ratioPlot->SetMinimum(ratio_min);
     ratioPlot->SetMaximum(ratio_max);
   }     

   if(ratioPlot->GetXaxis()->GetNdivisions() > ratioPlot->GetNbinsX())
     ratioPlot->GetXaxis()->SetNdivisions(ratioPlot->GetNbinsX());
   if(ratioPlot->GetXaxis()->GetNdivisions() > 11)
     ratioPlot->GetXaxis()->SetNdivisions(11);
   ratioPlot->GetXaxis()->SetLabelSize(RATIOPLOT_XAXIS_LABEL_SIZE);
   ratioPlot->GetYaxis()->SetLabelSize(RATIOPLOT_YAXIS_LABEL_SIZE);
   ratioPlot->GetYaxis()->SetNdivisions(3);
   ratioPlot->GetYaxis()->SetTitleSize(RATIOPLOT_YAXIS_TITLE_SIZE);
   ratioPlot->GetYaxis()->SetTitleOffset(RATIOPLOT_YAXIS_TITLE_OFFSET);
   ratioPlot->GetXaxis()->SetTitleSize(RATIOPLOT_XAXIS_TITLE_SIZE);
   ratioPlot->GetXaxis()->SetTitleOffset(RATIOPLOT_XAXIS_TITLE_OFFSET);
   
   if(data){
     ratioPlot->Draw();
     // plot horizontal line at y=1
     TF1* horizontal = new TF1("horizontal","pol1",-10000,10000);
     horizontal->SetParameter(0,1.);
     horizontal->SetParameter(1,0.);
     horizontal->SetLineColor(kBlack);
     horizontal->SetLineStyle(2);
     horizontal->SetLineWidth(1);
     horizontal->Draw("same");
     ratioErr->Draw("E2 same");
   }else{ // there is no data
     ratioPlot->Draw("axis");
     char text[]="NO DATA";
     myText(0.4,0.6,1,.15,text);
   }
   
   return canvas;
}
Ejemplo n.º 12
0
// *************************************** //
// this is a function that takes a set of  //
// histograms and draws them on a canvas   //
// in a stack, returning the canvas.       //
// It also plots the signal as a dashed    //
// line and the data with a ratio at the   //
// the bottom of data/allBackgrounds       //
//                                         //
// This one is supposed to match the plots //
// make by JP                              //
// *************************************** //
TCanvas* drawPlots::plotAll_VLQ(std::vector<TH1D*> histos, std::vector<std::string> names, std::string axisName, std::vector<TH1D*> signal, TH1D* data, TGraphAsymmErrors* err, bool isSignalRegion, bool doLogAxis, std::string channel){

   const unsigned int CANVAS_WIDTH  = 720;
   const unsigned int CANVAS_HEIGHT = 750;
   const double RATIOPLOT_YAXIS_TITLE_OFFSET = 0.75;
   const double RATIOPLOT_YAXIS_TITLE_SIZE   = 0.11;
   const double RATIOPLOT_YAXIS_LABEL_SIZE   = 0.09;  
   const double RATIOPLOT_XAXIS_TITLE_OFFSET = 1.6;
   const double RATIOPLOT_XAXIS_TITLE_SIZE   = 0.11;
   const double RATIOPLOT_XAXIS_LABEL_SIZE   = 0.09;
   
   TCanvas* canvas = new TCanvas("canvas","canvas",0,0,CANVAS_WIDTH,CANVAS_HEIGHT);
   
   canvas->SetMargin(0.,0.,0.,0.);
   canvas->Clear();
   canvas->cd();
   
   SetAtlasStyle();
   gStyle->SetHistLineWidth(1.);
   
   // create histogram to store all backgrounds
   TH1D* allBackgrounds;
   bool gotSomething=false;
   for(int c=0; c<signal.size(); c++){
     if(signal[c]){
       allBackgrounds = (TH1D*)signal[c]->Clone("all_backgrounds");
       gotSomething=true;
     }
   }
   if(!gotSomething && data)
     allBackgrounds = (TH1D*)data->Clone("all_backgrounds");
   if(!gotSomething){
     for(int b=0; b<histos.size(); b++){
       if(histos[b] && !gotSomething){
	 allBackgrounds = (TH1D*)histos[b]->Clone("all_backgrounds");
	 gotSomething=true;
       }
     }
   }

   if(!gotSomething){
     std::cout << "Error: could not find any background, data, or signal for this plot" << std::endl;
     return canvas;
   }
   
   // set all bins to zero
   for(int i=0; i<=allBackgrounds->GetNbinsX()+1; i++)
     allBackgrounds->SetBinContent(i,0);
   
   // make stack of backgrounds, fill backgrounds histogram
   THStack* Stack = new THStack();
   for(int b=0; b<histos.size(); b++){
     if(histos[b]){
       if(histos[b]->GetEntries() > 0.){
	 histos[b]->SetLineColor(1);
	 histos[b]->SetFillColor(tools::setColor(names[b]));
	 Stack->Add(histos[b]);
	 for(int j=0; j<=allBackgrounds->GetNbinsX()+1; j++){
	   double binContent=allBackgrounds->GetBinContent(j)+histos[b]->GetBinContent(j);
	   allBackgrounds->SetBinContent(j,binContent);
	 }
       }
     }
   } 
   TH1D* backgroundsForRatio = (TH1D*)allBackgrounds->Clone("bkgds_for_ratio");

   // create main pad
   const double mainPad_ylow  = 0.3;
   const double mainPad_yhigh = 0.95;
   const double mainPad_xlow = 0.;
   const double mainPad_xhigh = 0.95;
   const double pad_margin_left = 0.2;
   const double pad_margin_right  = 0.02;
   double main_y_max = -99;
   double main_y_min = -99;

   TPad* mainPad = new TPad("main","main",mainPad_xlow,mainPad_ylow,mainPad_xhigh,mainPad_yhigh);
   mainPad->SetMargin(pad_margin_left,pad_margin_right,0.,.05); // left, right, bottom, top
   mainPad->Draw();
   mainPad->cd();

   // find max y
   if(allBackgrounds){
     int maxBinBkg = allBackgrounds->GetMaximumBin();
     double bkgYmax = allBackgrounds->GetBinContent(maxBinBkg);
     main_y_max = bkgYmax;
   }
   if(data){
     int maxBinData = data->GetMaximumBin();
     double dataYmax = data->GetBinContent(maxBinData);
     if(dataYmax > main_y_max) main_y_max = dataYmax;
   }
   if(main_y_max < .002) main_y_max = .1;

   if(doLogAxis){
     mainPad->SetLogy();
     main_y_min = 0.007;
     main_y_max*=600;
   }else{
     main_y_min = 0.001;
     main_y_max*=1.6;
   }

   // draw axis
   allBackgrounds->SetMaximum(main_y_max);
   allBackgrounds->SetMinimum(main_y_min);
   std::string title = std::string(";") + axisName + ";events/bin";
   allBackgrounds->SetTitle(title.c_str());   
   allBackgrounds->GetYaxis()->SetTitleOffset(1.4);
   allBackgrounds->GetYaxis()->SetTitleSize(0.06);
   allBackgrounds->GetXaxis()->SetTitleOffset(1.2);
   allBackgrounds->GetYaxis()->SetLabelSize(0.04);
   allBackgrounds->GetXaxis()->SetLabelSize(0.04);
   allBackgrounds->Draw("hist");

   // draw stack with error
   Stack->Draw("hist same");
   if(err){
     err->Draw("E2 same");
   }

   // make error histograms for the ratio plot
   TGraphAsymmErrors* ratioErr = tools::getRatio(err, backgroundsForRatio);

   // draw data
   if(!isSignalRegion && data)
      data->Draw("e same");

   // draw signal
   if(signal[0]){
     signal[0]->SetLineStyle(2);
     signal[0]->SetLineColor(kRed);
     signal[0]->SetLineWidth(5);
     signal[0]->Draw("hist same");
   }
   if(signal.size() > 1){
     if(signal[1]){
       signal[1]->SetLineStyle(2);
       signal[1]->SetLineColor(kOrange+7);
       signal[1]->SetLineWidth(4);
       signal[1]->Draw("hist same");
     }
     if(signal.size() > 2){
       if(signal[2]){
	 signal[2]->SetLineStyle(2);
	 signal[2]->SetLineColor(kPink-6);
	 signal[2]->SetLineWidth(4);
	 signal[2]->Draw("hist same");
       }
     }
   }
   allBackgrounds->Draw("axis same");

   // draw legend
   float leg_height = 0.45;
   float leg_width = 0.2;
   float leg_xoffset = 0.74;
   float leg_yoffset = 0.7;
   
   TLegend* leg = new TLegend(leg_xoffset,leg_yoffset-leg_height/2,leg_xoffset+leg_width,leg_yoffset+leg_height/2);
   leg->SetFillColor(0);
   leg->SetFillStyle(0);
   leg->SetBorderSize(0);
   leg->SetTextFont(52);
   leg->SetTextSize(0.033);
   
   // currently assuming first signal is Tbq (single T production), second is TTS, third is BBS
   if(signal[0])
     leg->AddEntry(signal[0], "Tbq (650 GeV)", "l");
   if(signal.size()>1){
     if(signal[1])
       leg->AddEntry(signal[1], "TT_{S} (650 GeV)", "l");
     if(signal[2])
       leg->AddEntry(signal[2], "BB_{S} (650 GeV)", "l");
   }
   if(!isSignalRegion)
     leg->AddEntry(data, "data 2012");
   for(int q=0; q<histos.size(); q++){
     if(histos[q]){
       if(histos[q]->GetEntries() > 0.)
	 leg->AddEntry(histos[q], plotLists::GetLegendName(names[q]).c_str(), "f");
     }
   }
   leg->Draw("lpe");
   
   ATLAS_LABEL(0.24,0.86,1);
   myText(0.36, 0.86, 1, .05, "Internal");
   char text[]="#sqrt{s}=8 TeV";
   myText(0.55,0.77,1,.04, text);
   char text_L[]="#int L dt = 20.3 fb^{-1}";
   myText(0.5, 0.84,1, .04, text_L);
   if(channel!=""){
     char chan_txt[channel.size()-1];
     strcpy(chan_txt, (channel.substr(1)).c_str());
     myText(0.5, 0.7, 1, .06, chan_txt);
   }
   char inText[100];
   int t;
   if(signal[0])
     t=sprintf(inText, "N_{Tbq} = %.1f", signal[0]->Integral(0,signal[0]->GetNbinsX()+1));
   else
     t=sprintf(inText, "N_{Tbq} = %.1f", 0.);
   myText(0.24, 0.7, 1, .04, inText);
   if(signal.size()>1){
     if(signal[1])
       t=sprintf(inText, "N_{TTS} = %.1f", signal[1]->Integral(0,signal[1]->GetNbinsX()+1));
     else
       t=sprintf(inText, "N_{TTS} = %.1f", 0.);
     myText(0.24, 0.65, 1, .04, inText);
     if(signal.size()>2){
       if(signal[2])
	 t=sprintf(inText, "N_{BBS} = %.1f", signal[2]->Integral(0,signal[2]->GetNbinsX()+1));
       else
	 t=sprintf(inText, "N_{BBS} = %.1f", 0.);
       myText(0.24, 0.6, 1, .04, inText);
     }
   }

   double back_int = allBackgrounds->Integral(0,allBackgrounds->GetNbinsX()+1);
   if(back_int > 10000.)
     t=sprintf(inText, "N_{B} = %.3e", back_int);
   else
     t=sprintf(inText, "N_{B} = %.1f", back_int);
   myText(0.24, 0.75, 1, .04, inText);
   if(!isSignalRegion){
     if(data)
       t=sprintf(inText, "N_{D} = %.0f", data->Integral(0,data->GetNbinsX()+1));
     else
       t=sprintf(inText, "N_{D} = %.0f", 0.);
     myText(0.24, 0.8, 1, .04, inText);
   }
   
   canvas->cd();
   
   // Draw Ratio plot
   double ratio_max = 1.6;
   double ratio_min = 0.4;
  
   double pad_xlow = 0.;
   double pad_xhigh = 0.95;
   double pad_ylow = 0.0;
   double pad_yhigh = 0.3;
   
   const char* pad_name = "pad";
   TPad* pad4ratio = new TPad(pad_name,pad_name,pad_xlow,pad_ylow,pad_xhigh,pad_yhigh);

   pad4ratio->SetMargin(pad_margin_left,pad_margin_right,0.46,0.);
   pad4ratio->Draw();
   pad4ratio->cd();

   TH1D* ratioPlot;
   if(data)
     ratioPlot = (TH1D*)data->Clone("ratio");
   else if (signal[0]) 
     ratioPlot = (TH1D*)signal[0]->Clone("ratio"); // just for getting the axis

   ratioPlot->SetTitle("");
   ratioPlot->Divide(allBackgrounds);
   ratioPlot->GetYaxis()->SetTitle("Data/MC");
   ratioPlot->GetXaxis()->SetTitle(axisName.c_str());

   if (data){
     // here change ratio_min and ratio_max if the ratio plot is quite flat
     double maxDeviation=0;
     double tempDev=0;
     for(int ibin=1; ibin<=allBackgrounds->GetNbinsX(); ibin++){
       tempDev = std::abs(ratioPlot->GetBinContent(ibin)-1.);
       if(tempDev > maxDeviation) maxDeviation = tempDev;
     }
     if(maxDeviation < 0.1){
       ratio_max = 1.12;
       ratio_min = 0.88;
     }
     else if(maxDeviation < 0.2){
       ratio_max = 1.25;
       ratio_min = .75;
     }
     ratioPlot->SetMinimum(ratio_min);
     ratioPlot->SetMaximum(ratio_max);
   }     

   if(ratioPlot->GetXaxis()->GetNdivisions() > ratioPlot->GetNbinsX())
     ratioPlot->GetXaxis()->SetNdivisions(ratioPlot->GetNbinsX());
   if(ratioPlot->GetXaxis()->GetNdivisions() > 11)
     ratioPlot->GetXaxis()->SetNdivisions(11);
   ratioPlot->GetXaxis()->SetLabelSize(RATIOPLOT_XAXIS_LABEL_SIZE);
   ratioPlot->GetYaxis()->SetLabelSize(RATIOPLOT_YAXIS_LABEL_SIZE);
   ratioPlot->GetYaxis()->SetNdivisions(3);
   ratioPlot->GetYaxis()->SetTitleSize(RATIOPLOT_YAXIS_TITLE_SIZE);
   ratioPlot->GetYaxis()->SetTitleOffset(RATIOPLOT_YAXIS_TITLE_OFFSET);
   ratioPlot->GetXaxis()->SetTitleSize(RATIOPLOT_XAXIS_TITLE_SIZE);
   ratioPlot->GetXaxis()->SetTitleOffset(RATIOPLOT_XAXIS_TITLE_OFFSET);
   
   if(!isSignalRegion && data){
     ratioPlot->Draw();
     // plot horizontal line at y=1
     TF1* horizontal = new TF1("horizontal","pol1",-10000,10000);
     horizontal->SetParameter(0,1.);
     horizontal->SetParameter(1,0.);
     horizontal->SetLineColor(kBlack);
     horizontal->SetLineStyle(2);
     horizontal->SetLineWidth(1);
     horizontal->Draw("same");
     ratioErr->Draw("E2 same");
   }else if(isSignalRegion){
     ratioPlot->Draw("axis");
     char text[]="DATA IS BLIND HERE";
     myText(0.4,0.6,1,.15,text);
   }else{ // in this case it is not the signal region but there is no data
     ratioPlot->Draw("axis");
     char text[]="NO DATA";
     myText(0.4,0.6,1,.15,text);
   }
   
   return canvas;
}
Ejemplo n.º 13
0
// *************************************** //
// this is a function that takes a set of  //
// histograms and draws them on a canvas   //
// in a stack, returning the canvas.       //
// It also plots the signal as a dashed    //
// line and the data with a ratio at the   //
// the bottom of data/allBackgrounds       //
// *************************************** //
TCanvas* drawPlots::plotAll(std::vector<TH1D*> histos, std::vector<std::string> names, std::string axisName, TH1D* signal, TH1D* data, TH1D* errDown, TH1D* errUp, bool isSignalRegion, bool doLogAxis){
         
   const unsigned int MAINPLOT_WIDTH  = 800;
   const unsigned int MAINPLOT_HEIGHT = 500;
   const unsigned int RATIOPLOT_HEIGHT = 125;
   const unsigned int OFFSET = 10;
   
  //LUKE: Title offset and title size are proportional in 
  //root, so you have to change them together, 
  //this makes me a sad panda 
   const double RATIOPLOT_YAXIS_TITLE_OFFSET = 0.4;
   const double RATIOPLOT_YAXIS_TITLE_SIZE   = 0.14;
   const double RATIOPLOT_YAXIS_TICK_LENGTH  = 0.01;
   const double RATIOPLOT_YAXIS_LABEL_SIZE   = 0.15;
  
   const double RATIOPLOT_XAXIS_TITLE_OFFSET = 0.9;
   const double RATIOPLOT_XAXIS_TITLE_SIZE   = 0.2;
   const double RATIOPLOT_XAXIS_TICK_LENGTH  = 0.05;
   const double RATIOPLOT_XAXIS_LABEL_SIZE   = 0.2;
   
   const double CANVAS_HEIGHT = MAINPLOT_HEIGHT+RATIOPLOT_HEIGHT+OFFSET;
   
   TCanvas* canvas = new TCanvas("canvas","canvas",0,0,MAINPLOT_WIDTH,CANVAS_HEIGHT);
   
   canvas->SetMargin(0.,0.,0.,0.);
   canvas->Clear();
   canvas->cd();
   
   // create main pad
   const double mainPad_ylow  = (CANVAS_HEIGHT - MAINPLOT_HEIGHT)/CANVAS_HEIGHT;
   const double mainPad_yhigh = 1.;
  
   const double pad_margin_left = 0.15;
   const double pad_margin_right  = 0.05;
   
   double main_y_max = -99;
   double main_y_min = -99;
   double main_x_max = -99;
   double main_x_min = -99;
   for(int a=0; a<histos.size(); a++){
     if(histos[a]){
       if(histos[a]->GetEntries()> 0.){
	 GetAxisLimits(histos[a], main_x_min, main_x_max, main_y_min, main_y_max);
       }
     }
   }
   
   if(data){
     int maxBinData = data->GetMaximumBin();
     double dataYmax = data->GetBinContent(maxBinData);
     if(dataYmax > main_y_max) main_y_max = dataYmax;
   }

   // create main pad
   TPad* mainPad = new TPad("main","main",0.,mainPad_ylow,1.,mainPad_yhigh);
   mainPad->SetMargin(pad_margin_left,pad_margin_right,0.,.05); // left, right, bottom, top
   mainPad->Draw();
   mainPad->cd();

   SetAtlasStyle();

   if(doLogAxis)mainPad->SetLogy();

   // clone signal or data because one should exist for each plot
   TH1D* allBackgrounds;
   bool gotSomething=false;
   if(signal)
     allBackgrounds = (TH1D*)signal->Clone("all_backgrounds");
   else if(data)
     allBackgrounds = (TH1D*)data->Clone("all_backgrounds");
   else{
     for(int b=0; b<histos.size(); b++){
       if(histos[b] && !gotSomething){
	 allBackgrounds = (TH1D*)histos[b]->Clone("all_backgrounds");
	 gotSomething=true;
       }
     }  
   }

   // set all bins to zero so that you can add all histograms to it
   for(int i=0; i<=allBackgrounds->GetNbinsX()+1; i++)
      allBackgrounds->SetBinContent(i,0);
   
   THStack* Stack = new THStack();
   std::string title = std::string(";") + axisName + ";Events";
   Stack->SetTitle(title.c_str());
   
   for(int b=0; b<histos.size(); b++){
     if(histos[b]){
       if(histos[b]->GetEntries() > 0.){
	 histos[b]->SetLineColor(1);
	 histos[b]->SetFillColor(tools::setColor(names[b]));
	 Stack->Add(histos[b]);
	 for(int j=0; j<=allBackgrounds->GetNbinsX()+1; j++){
	   double binContent=allBackgrounds->GetBinContent(j)+histos[b]->GetBinContent(j);
	   allBackgrounds->SetBinContent(j,binContent);
	 }
       }
     }
   }

   TH1D* backgroundsForRatio = (TH1D*)allBackgrounds->Clone("bkgds_for_ratio");
   
   if(doLogAxis){ 
     main_y_max = main_y_max*10;
     if(Stack->GetMinimum()>.1) Stack->SetMinimum(.1);
   }
   else main_y_max = main_y_max*1.4;
   Stack->SetMaximum(main_y_max);
   Stack->Draw("hist");
   errDown->Draw("E2same");
   errUp->Draw("E2Same");
   
   // make error histograms for the ratio plot
   TH1D* ratioErrDown = (TH1D*) errDown->Clone("ratio_error_down");
   TH1D* ratioErrUp = (TH1D*) errUp->Clone("ratio_error_up");

   ratioErrDown->Divide(backgroundsForRatio);
   ratioErrUp->Divide(backgroundsForRatio);

   if(!isSignalRegion && data)
      data->Draw("e same");

   if(signal){
     signal->SetLineStyle(2);
     signal->SetLineColor(kRed);
     signal->SetLineWidth(5);
     signal->Draw("hist same");
   }

   TLegend* leg = new TLegend(0.8,0.65,0.95,0.9);
   leg->SetFillStyle(0);
   leg->SetBorderSize(0);
   
   if(signal)
     leg->AddEntry(signal, "Signal", "l");
   if(!isSignalRegion)
     leg->AddEntry(data, "Data");
   for(int q=0; q<histos.size(); q++){
     if(histos[q]){
       if(histos[q]->GetEntries() > 0.)
	 leg->AddEntry(histos[q], names[q].c_str(), "f");
     }
   }
   leg->Draw("lpe");
   
   ATLAS_LABEL(0.2,0.85,1);
   char text[]="#sqrt{s}=8 TeV";
   myText(0.6,0.75,1,.04, text);
   char text_L[]="#int L dt = 20.3 fb^{-1}";
   myText(0.6, 0.85,1, .04, text_L);
   char inText[100];
   int t;
   if(signal)
     t=sprintf(inText, "N_{Signal} = %.1f", signal->Integral(0,signal->GetNbinsX()+1));
   else
     t=sprintf(inText, "N_{Signal} = %.1f", 0.);
   myText(0.2, 0.75, 1, .04, inText);
   double back_int = allBackgrounds->Integral(0,allBackgrounds->GetNbinsX()+1);
   if(back_int > 10000.)
     t=sprintf(inText, "N_{Bkgd} = %.3e", back_int);
   else
     t=sprintf(inText, "N_{Bkgd} = %.1f", back_int);
   myText(0.2, 0.7, 1, .04, inText);
   if(!isSignalRegion){
     if(data)
       t=sprintf(inText, "N_{Data} = %.0f", data->Integral(0,data->GetNbinsX()+1));
     else
       t=sprintf(inText, "N_{Data} = %.0f", 0.);
     myText(0.2, 0.65, 1, .04, inText);
   }
   
   canvas->cd();
   
   // Draw Ratio plot
   double ratio_max = 1.6;
   double ratio_min = 0.4;
  
   const double x_axis_size = 0.4;
   const double ratio_pad_height = RATIOPLOT_HEIGHT/CANVAS_HEIGHT;
   
   double pad_xlow = 0.,pad_xhigh = 1.;
   double pad_ylow = OFFSET/CANVAS_HEIGHT,pad_yhigh = ratio_pad_height;
   
   const char* pad_name = "pad";
   TPad* pad4ratio = new TPad(pad_name,pad_name,pad_xlow,pad_ylow,pad_xhigh,pad_yhigh);
   
   pad4ratio->SetMargin(pad_margin_left,pad_margin_right,x_axis_size,0.);
   pad4ratio->Draw();
   pad4ratio->cd();

   TH1D* ratioPlot;
   if(data) ratioPlot = (TH1D*)data->Clone("ratio");
   else if(signal) ratioPlot = (TH1D*)signal->Clone("ratio"); // if there is no data then use signal for axis 
   ratioPlot->SetTitle("");
   ratioPlot->GetYaxis()->SetTitle("Data/MC");
   ratioPlot->GetXaxis()->SetTitle(axisName.c_str());
   if(data){
     ratioPlot->Divide(allBackgrounds);
     // here change ratio_min and ratio_max if the ratio plot is quite flat
     double maxDeviation=0;
     double tempDev=0;
     for(int ibin=1; ibin<=allBackgrounds->GetNbinsX(); ibin++){
       tempDev = std::abs(ratioPlot->GetBinContent(ibin)-1.);
       if(tempDev > maxDeviation) maxDeviation = tempDev;
     }
     if(maxDeviation < 0.1){
       ratio_max = 1.12;
       ratio_min = 0.88;
     }
     else if(maxDeviation < 0.2){
       ratio_max = 1.25;
       ratio_min = .75;
     }
     ratioPlot->SetMinimum(ratio_min);
     ratioPlot->SetMaximum(ratio_max);
   }
   ratioPlot->GetXaxis()->SetLabelSize(RATIOPLOT_XAXIS_LABEL_SIZE);
   ratioPlot->GetXaxis()->SetTickLength(RATIOPLOT_XAXIS_TICK_LENGTH);
   ratioPlot->GetYaxis()->SetLabelSize(RATIOPLOT_YAXIS_LABEL_SIZE);
   ratioPlot->GetYaxis()->SetTickLength(RATIOPLOT_YAXIS_TICK_LENGTH);
   ratioPlot->GetYaxis()->SetNdivisions(3);
   ratioPlot->GetYaxis()->SetTitleSize(RATIOPLOT_YAXIS_TITLE_SIZE);
   ratioPlot->GetYaxis()->SetTitleOffset(RATIOPLOT_YAXIS_TITLE_OFFSET);
   ratioPlot->GetXaxis()->SetTitleSize(RATIOPLOT_XAXIS_TITLE_SIZE);
   ratioPlot->GetXaxis()->SetTitleOffset(RATIOPLOT_XAXIS_TITLE_OFFSET);
   
   if(!isSignalRegion && data){
     ratioPlot->Draw();
     // plot horizontal line at y=1
     TF1* horizontal = new TF1("horizontal","pol1",-10000,10000);
     horizontal->SetParameter(0,1.);
     horizontal->SetParameter(1,0.);
     horizontal->SetLineColor(kBlack);
     horizontal->SetLineStyle(2);
     horizontal->SetLineWidth(1);
     horizontal->Draw("same");
     ratioErrDown->Draw("E2same");
     ratioErrUp->Draw("E2same");
   }else if(isSignalRegion){
     ratioPlot->Draw("axis");
     char text[]="DATA IS BLINDED HERE";
     myText(0.4,0.6,1,.2,text);
   }else{ // in this case it is not the signal region but there is no data
     ratioPlot->Draw("axis");
     char text[]="NO DATA";
     myText(0.4,0.6,1,.2,text);
     }
   
   return canvas;
}
Ejemplo n.º 14
0
// *************************************** //
// this is a function that draws all       //
// backrounds as a grey area, and compares //
// the shape of the backgrounds to that of //
// the signal                              //
// This one is supposed to match the plots //
// make by JP (Fig 3 of CONF note)         //
// *************************************** //
TCanvas* drawPlots::plotShape_VLQ(TH1D* bkgd, std::string axisName, std::vector<TH1D*> signal, bool doLogAxis, std::string channel){

  // only drawing shapes so normalize histograms
  std::cout << "background integral: " << bkgd->Integral() << std::endl;
  bkgd->Scale(1./bkgd->Integral());
  for(int ahist=0; ahist<signal.size(); ahist++){
    if(signal[ahist]){
      std::cout << "scaling signal: " << ahist << " with integral: " << signal[ahist]->Integral() << std::endl;
      signal[ahist]->Scale(1./signal[ahist]->Integral());
    }
  }

   const unsigned int CANVAS_WIDTH  = 720;
   const unsigned int CANVAS_HEIGHT = 750;
   TCanvas* canvas = new TCanvas("canvas","canvas",0,0,CANVAS_WIDTH,CANVAS_HEIGHT);
   
   canvas->SetMargin(0.,0.,0.,0.);
   canvas->Clear();
   canvas->cd();

   SetAtlasStyle();
   gStyle->SetHistLineWidth(1.);

   
   // create main pad
   const double mainPad_ylow  = 0.;
   const double mainPad_yhigh = 1.;
   const double mainPad_xlow = 0.;
   const double mainPad_xhigh = 1.;
   const double pad_margin_left = 0.16;
   const double pad_margin_right  = 0.035;
   
   double main_y_max = -99;
   double main_y_min = -99;

   TPad* mainPad = new TPad("main","main",mainPad_xlow,mainPad_ylow,mainPad_xhigh,mainPad_yhigh);
   mainPad->SetMargin(pad_margin_left,pad_margin_right,0.16,.05); // left, right, bottom, top
   mainPad->Draw();
   mainPad->cd();

   // find max y
   int maxBinBkg = bkgd->GetMaximumBin();
   double bkgYmax = bkgd->GetBinContent(maxBinBkg);
   main_y_max = bkgYmax;
   //   std::cout << "background maximum: " << bkgYmax << std::endl;
   if(main_y_max < .002) main_y_max = .1;
   
   if(doLogAxis){
     mainPad->SetLogy();
     main_y_min = 0.0001;
     main_y_max*=500;
   }else{
     main_y_min = 0.00001;
     main_y_max*=1.6;
   }

   // draw axis
   bkgd->SetMaximum(main_y_max);
   bkgd->SetMinimum(main_y_min);
   std::string title = std::string(";") + axisName + ";Fraction of events";
   std::stringstream binw; 
   binw<<bkgd->GetBinWidth(1);
   std::string width = binw.str();
   if (axisName.find("GeV") != std::string::npos) width += " GeV";
   if(bkgd->GetBinWidth(1) != 1) title += " / "+width;
   bkgd->SetTitle(title.c_str());   
   bkgd->GetYaxis()->SetTitleOffset(1.6);
   bkgd->GetXaxis()->SetTitleOffset(1.2);
   bkgd->GetYaxis()->SetLabelSize(0.03);
   bkgd->GetYaxis()->SetTitleSize(0.045);
   bkgd->GetXaxis()->SetTitleSize(0.045);
   bkgd->GetXaxis()->SetLabelSize(0.03);
   bkgd->SetFillStyle(3354);
   bkgd->SetFillColor(kGray+2);
   bkgd->SetLineColor(kGray+2);
   bkgd->Draw("histf");

   // draw signal
   if(signal[0]){
     std::cout << "printing Tbq" << std::endl;
     signal[0]->SetLineStyle(2);
     signal[0]->SetLineColor(kRed+2); // kGreen+3 was being used before
     signal[0]->SetLineWidth(5);
     signal[0]->Draw("hist same");
   }
   if(signal.size() > 1){
     if(signal[1]){
       std::cout << "printing TTS" << std::endl;
       //   signal[1]->SetLineStyle(2);
       signal[1]->SetLineColor(kRed+2);
       signal[1]->SetLineWidth(4);
       signal[1]->Draw("hist same");
     }
     if(signal.size() > 2){
       if(signal[2]){
	 std::cout << "printing BBS" << std::endl;
	 //	 signal[2]->SetLineStyle(2);
	 signal[2]->SetLineColor(kBlue+2);
	 signal[2]->SetLineWidth(4);
	 signal[2]->Draw("hist same");
       }
     }
   }
   bkgd->Draw("axis same");

   // draw legend
   float leg_height = 0.2;
   float leg_width = 0.4;
   float leg_xoffset = 0.65;
   float leg_yoffset = 0.8;
   
   TLegend* leg = new TLegend(leg_xoffset,leg_yoffset-leg_height/2,leg_xoffset+leg_width,leg_yoffset+leg_height/2);
   leg->SetFillColor(0);
   leg->SetFillStyle(0);
   leg->SetBorderSize(0);
   leg->SetTextFont(72);
   leg->SetTextSize(0.026);
   
   // currently assuming first signal is single T, second is TTS
   leg->AddEntry(bkgd,"Background", "f");
   if(signal.size()>1){
     if(signal.size()>2){
       if(signal[2])
	 leg->AddEntry(signal[2], "B#bar{B} (650 GeV)", "l");
     }
     if(signal[1])
       leg->AddEntry(signal[1], "T#bar{T} (650 GeV)", "l");
   }  
   if(signal[0])
     leg->AddEntry(signal[0], "T#bar{b}q (650 GeV)", "l");
   
   leg->Draw("lpe");
   
   ATLAS_LABEL(0.24,0.86,1);
   myText(0.26, 0.81, 1, .04, "Internal");
   char text[]="#sqrt{s}=8 TeV";
   myText(0.48,0.82,1,.03, text);
   char text_L[]="Simulation";
   myText(0.47, 0.87,1, .03, text_L);
   char text_tri[]="Trilepton";
   myText(0.485, 0.77, 1, .03, text_tri);
   if(channel!=""){
     char chan_txt[channel.size()-1];
     strcpy(chan_txt, (channel.substr(1)).c_str());
     if(channel.size()>10)
       myText(0.55, 0.56, 1, .03, chan_txt);
     else
       myText(0.65, 0.56, 1, .03, chan_txt);
   }
   canvas->cd();
   
   return canvas;
}
Ejemplo n.º 15
0
void wjetsPrint(string type="ps"){

  

  const int nProcs = 2;
  string procs[nProcs] = {"elec", "muon"};

  string event_type = type;

  // ctrl_highm
  if(event_type.find("ps")!=string::npos){

    string vars[] = {"lep_met_pt","dijet_pt","dijet_m","jet_n","met","lep_met_mt","lep_pt","lead_jet_pt","lep_met_dijet_mt","avg_int_per_xing"};
    int tmpVars = sizeof(vars)/sizeof(vars[0]);
    const int nVars = tmpVars;  
    string plot_vars[nVars] = {"Pt(lep,MET)","Dijet Pt","Dijet M","Jet N","MET_RefFinal","MT(lep,met)","Lepton Pt","Leading jet pt","Mt(lep,MET,dijet)","Average Interactions per Xing"};

  }else if(event_type.find("ctrl_ewk")!=string::npos){

    string vars[] = {"mt_dijet_pt","mt_njets","mt_met","mt_lep_met_mt","mt_lep_pt"};
    int tmpVars = sizeof(vars)/sizeof(vars[0]);
    const int nVars = tmpVars;  
    string plot_vars[nVars] = {"Dijet Pt","Jet N","MET_RefFinal","MT(lep,met)","Lepton Pt"};

  }else if(event_type.find("ctrl_highm")!=string::npos){

    string vars[] = {"dijet_m_lep_met_pt","dijet_m_dijet_pt","dijet_m_jet_n","dijet_m_met","dijet_m_lep_met_mt","dijet_m_lep_pt","dijet_m_lead_jet_pt","dijet_m_lep_met_dijet_mt"};
    
    int tmpVars = sizeof(vars)/sizeof(vars[0]);
    const int nVars = tmpVars;  
    string plot_vars[nVars] = {"Pt(lep,MET)","Dijet Pt","Jet N","MET_RefFinal","MT(lep,met)","Lepton Pt","Leading jet pt","Mt(lep,MET,dijet)"};

  }  // // ps


  // string regions[] = {"all"}
  // int tmpRegions = sizeof(regions)/sizeof(regions[0]);
  // const int nRegions = tmpRegions;
    
  gROOT->LoadMacro("../include/atlasstyle-00-03-04/AtlasStyle.C");
  SetAtlasStyle();
  gROOT->LoadMacro("../include/atlasstyle-00-03-04/AtlasUtils.C");
  gROOT->LoadMacro("../include/atlasstyle-00-03-04/AtlasLabels.C");
  
  gROOT->SetBatch();
  
  cout<<endl;
  cout<<"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"<<endl;
  cout<<"In wjetsPrint.C"<<endl;

  //string file_loc = "/Users/elw/analy/lvjj/plots/ctrl_plots/";

  string file_loc;
  if(event_type.find("ps")!=string::npos){
    file_loc="/Users/elw/Dropbox/eMacs/analy/lvjj/plots/gww_plots/";
  }else if(event_type.find("ctrl")!=string::npos){
    file_loc="/Users/elw/Dropbox/eMacs/analy/lvjj/plots/ctrl_plots/";
  }else{
    cout<<"Unknown plot source type: "<<event_type<<endl;
    exit(1);
  }

  //////////////////////////////////////////////////
  // Load Data
  ////////////////////////////////////////////////// 
  string file_end;
  if(event_type.find("ps")!=string::npos){
    file_end=".plot.root";
  }else if(event_type.find("ctrl")!=string::npos){
    file_end=".ctrl.plot.root";
  }else{
    cout<<"Unknown plot source type: "<<event_type<<endl;
    exit(1);
  }
  
  string data_loc = file_loc+"merged/data.lnuj"+file_end;
  TFile* data = (TFile*) TFile::Open(data_loc.c_str());
  //////////////////////////////////////////////////
  // Load Scaled Backgrounds
  //////////////////////////////////////////////////
  
  string sherpa_wjets_loc = file_loc+"merged/mc.sherpa.wjets"+file_end;
  string alpgen_wjets_loc = file_loc+"merged/mc.alpgen.wjets"+file_end;
  string vv_loc = file_loc+"merged/mc.herwig.vv"+file_end;
  string alpgen_qcd_loc = file_loc+"merged/qcd.alpgen"+file_end;
  string sherpa_qcd_loc = file_loc+"merged/qcd.sherpa"+file_end;
  string top_loc = file_loc+"merged/mc.mcatnlo.top"+file_end;  
  string alpgen_zjets_loc = file_loc+"merged/mc.alpgen.zjets"+file_end;
  string sherpa_zjets_loc = file_loc+"merged/mc.sherpa.zjets"+file_end;

  TFile* sherpa_wjets = (TFile*) TFile::Open(sherpa_wjets_loc.c_str(),"READ");  
  TFile* alpgen_wjets = (TFile*) TFile::Open(alpgen_wjets_loc.c_str(),"READ");
  TFile* top = (TFile*) TFile::Open(top_loc.c_str(),"READ");
  TFile* alpgen_qcd = (TFile*) TFile::Open(alpgen_qcd_loc.c_str(),"READ");
  TFile* vv = (TFile*) TFile::Open(vv_loc.c_str(),"READ");
  TFile* sherpa_qcd = (TFile*) TFile::Open(sherpa_qcd_loc.c_str(),"READ");
  TFile* sherpa_zjets = (TFile*) TFile::Open(sherpa_zjets_loc.c_str(),"READ");
  TFile* alpgen_zjets = (TFile*) TFile::Open(alpgen_zjets_loc.c_str(),"READ");


  const int nBkgds = 2;
  TFile* bkgd_files[nBkgds] = {vv,top};

  //////////////////////////////////////////////////
  // Histogram selection
  ////////////////////////////////////////////////// 

  
  TH1F* h_data[nProcs][nVars];
  TH1F* h_sherpa_bkgd[nProcs][nVars];
  TH1F* h_alpgen_bkgd[nProcs][nVars];
  THStack* stk_alpgen_bkgd[nProcs][nVars];
  TH1F* h_sherpa_ratio[nProcs][nVars];
  TH1F* h_alpgen_ratio[nProcs][nVars];
  
  for(int p=0;p<nProcs;p++){// e.g. elec,muon
    string proc = procs[p];

    for(int v=0;v<nVars;v++){// e.g. nocut_dijet_pt, dijet_m_lep_met_mt
      string var = vars[v];

      string hist_name;
      if(event_type.find("ps")!=string::npos){
	hist_name = "ps/h_"+proc+"_"+var;
      }else if(event_type.find("ctrl")!=string::npos){
	hist_name = "h_"+event_type+"_"+proc+"_"+var;
	}else{
	cout<<"Unknown plot source type: "<<event_type<<endl;
	exit(1);
      }

      //////////////////////////////////////////////////
      // Load data
      //////////////////////////////////////////////////
      //h_data[p][v] = (TH1F*) data->Get(hist_name.c_str())->Clone();
      h_data[p][v] = (TH1F*) data->Get(hist_name.c_str());

      //////////////////////////////////////////////////
      // Load backgrounds
      //////////////////////////////////////////////////
      // h_sherpa/alpgen for ratios
      //TH1F* cur_sherpa_wjets_hist = (TH1F*) sherpa_wjets->Get(hist_name.c_str())->Clone();
      TH1F* cur_sherpa_wjets_hist = (TH1F*) sherpa_wjets->Get(hist_name.c_str());
      h_sherpa_bkgd[p][v] = cur_sherpa_wjets_hist;

      TH1F* cur_sherpa_zjets_hist = (TH1F*) sherpa_zjets->Get(hist_name.c_str());
      ((TH1F*) h_sherpa_bkgd[p][v])->Add(cur_sherpa_zjets_hist);
      h_sherpa_bkgd[p][v]->SetLineColor(sherpa_color);

      TH1F* cur_sherpa_qcd_hist = (TH1F*) sherpa_qcd->Get(hist_name.c_str());
      ((TH1F*) h_sherpa_bkgd[p][v])->Add(cur_sherpa_qcd_hist);

      //alpgen
      //TH1F* cur_alpgen_wjets_hist = (TH1F*) alpgen_wjets->Get(hist_name.c_str())->Clone();
      TH1F* cur_alpgen_wjets_hist = (TH1F*) alpgen_wjets->Get(hist_name.c_str());
      h_alpgen_bkgd[p][v] = cur_alpgen_wjets_hist;

      TH1F* cur_alpgen_zjets_hist = (TH1F*) alpgen_zjets->Get(hist_name.c_str());
      ((TH1F*) h_alpgen_bkgd[p][v])->Add(cur_alpgen_zjets_hist);
      h_alpgen_bkgd[p][v]->SetLineColor(alpgen_color);

      //TH1F* cur_alpgen_qcd_hist = (TH1F*) alpgen_qcd->Get(hist_name.c_str())->Clone();
      TH1F* cur_alpgen_qcd_hist = (TH1F*) alpgen_qcd->Get(hist_name.c_str());
      ((TH1F*) h_alpgen_bkgd[p][v])->Add(cur_alpgen_qcd_hist);
      h_alpgen_bkgd[p][v]->SetLineWidth(1);
      
      // h_alpgen_bkgd[p][v] = (TH1F*) alpgen_wjets->Get(hist_name.c_str())->Clone();
      // ((TH1F*) h_alpgen_bkgd[p][v])->Add((TH1F*) alpgen_qcd->Get(hist_name.c_str())->Clone());
      // ((TH1F*) h_alpgen_bkgd[p][v])->Add((TH1F*) alpgen_zjets->Get(hist_name.c_str())->Clone());
      // h_alpgen_bkgd[p][v]->SetLineColor(alpgen_color);
      //

	
      string stack_name = "stk_"+event_type+"_"+proc+"_"+var;
      stk_alpgen_bkgd[p][v] = new THStack(stack_name.c_str(),hist_name.c_str());

      TH1F* vv_hist = (TH1F*) vv->Get(hist_name.c_str())->Clone();
      //vv_hist->SetFillStyle(3013);
      vv_hist->SetFillColor(kYellow-4);
      vv_hist->SetLineWidth(1);
      ((THStack*) stk_alpgen_bkgd[p][v])->Add(vv_hist,"hist");
      // TH1F* alpgen_qcd_hist = (TH1F*) alpgen_qcd->Get(hist_name.c_str())->Clone();
      // alpgen_qcd_hist->SetFillStyle(3003);
      // alpgen_qcd_hist->SetFillColor(kRed);
      // alpgen_qcd_hist->SetLineWidth(1);
      // ((THStack*) stk_alpgen_bkgd[p][v])->Add(alpgen_qcd_hist);
      // TH1F* alpgen_zjets_hist = (TH1F*) alpgen_zjets->Get(hist_name.c_str())->Clone();
      // alpgen_zjets_hist->SetFillStyle(3018);
      // alpgen_zjets_hist->SetFillColor(kYellow);
      // alpgen_zjets_hist->SetLineWidth(1);
      // ((THStack*) stk_alpgen_bkgd[p][v])->Add(alpgen_zjets_hist);
      TH1F* top_hist = (TH1F*) top->Get(hist_name.c_str())->Clone();
      //top_hist->SetFillStyle(3017);
      top_hist->SetFillColor(kAzure+1);
      top_hist->SetLineWidth(1);
      ((THStack*) stk_alpgen_bkgd[p][v])->Add(top_hist,"hist");
      // TH1F* alpgen_wjets_hist = (TH1F*) alpgen_wjets->Get(hist_name.c_str())->Clone();
      // //top_hist->SetF(3003);
      // alpgen_wjets_hist->SetLineColor(6);
      // alpgen_wjets_hist->SetLineWidth(2);
      // ((THStack*) stk_alpgen_bkgd[p][v])->Add(alpgen_wjets_hist);
      ((THStack*) stk_alpgen_bkgd[p][v])->Add((TH1F*) ((TH1F*) h_alpgen_bkgd[p][v])->Clone(),"hist");

	

      //////////////////////////////////////////////////
      // Alpgen printed as stack, to see other backgrounds
      // Sherpa background added
      ////////////////////////////////////////////////// 

	
      for(int b=0;b<nBkgds;b++){

	TH1F* bkgd_hist = (TH1F*) ((TFile*) bkgd_files[b])->Get(hist_name.c_str());
	((TH1F*) h_sherpa_bkgd[p][v])->Add(bkgd_hist);
	((TH1F*) h_alpgen_bkgd[p][v])->Add(bkgd_hist);
      }// bkds

      //////////////////////////////////////////////////
      // make ratio histogram
      //////////////////////////////////////////////////
	
      int n_bins = ((TAxis*) h_data[p][v]->GetXaxis())->GetNbins();
      float x_min = ((TAxis*) h_data[p][v]->GetXaxis())->GetXmin();
      float x_max = ((TAxis*) h_data[p][v]->GetXaxis())->GetXmax();

      string alpgen_ratio_name = "h_alpgen_ratio_"+event_type+"_"+proc+"_"+var;
      TH1F* alpgen_ratio = new TH1F(alpgen_ratio_name.c_str(),"",n_bins,x_min,x_max);

      string sherpa_ratio_name = "h_sherpa_ratio_"+event_type+"_"+proc+"_"+var;
      TH1F* sherpa_ratio = new TH1F(sherpa_ratio_name.c_str(),"",n_bins,x_min,x_max);

      for(int i=0;i<n_bins;i++){ //loop over bins

	float data_count = h_data[p][v]->GetBinContent(i);
	float data_err = h_data[p][v]->GetBinError(i);


	// alpgen
	float alpgen_bkgd_count= h_alpgen_bkgd[p][v]->GetBinContent(i);
	float alpgen_bkgd_err=sqrt(alpgen_bkgd_count);
	// Luminosity Error
	float alpgen_lumi_error = alpgen_bkgd_count*0.037;
	alpgen_bkgd_err = sqrt(pow(alpgen_lumi_error,2.)+pow(alpgen_bkgd_err,2.));


	if(alpgen_bkgd_count && data_count) {
	    
	  //////////////////////////////////////////////////
	  // relErr((D-B)/B) = sqrt( (Err(D-B)/(D-B))^2 + (Err(B)/B)^2)

	  //Err(D-B)
	  double comb_alpgen_bkgd_data_err =
	    sqrt(pow(data_err,2.)+pow(alpgen_bkgd_err,2.));

	  // Err(D-B)/(D-B)
	  double rel_alpgen_bkgd_data_err =
	    comb_alpgen_bkgd_data_err/(data_count-alpgen_bkgd_count);

	  // Err(B)/B
	  double rel_alpgen_bkgd_err =
	    alpgen_bkgd_err/alpgen_bkgd_count;

	  // relErr((D-B)/B)
	  double rel_alpgen_ratio_err =
	    sqrt(pow(rel_alpgen_bkgd_data_err,2.)+pow(rel_alpgen_bkgd_err,2.));

	  double cur_alpgen_ratio = (data_count-alpgen_bkgd_count)/alpgen_bkgd_count;

	  double cur_alpgen_ratio_err = fabs(rel_alpgen_ratio_err*cur_alpgen_ratio);
	  alpgen_ratio->SetBinContent(i,cur_alpgen_ratio);
	  alpgen_ratio->SetBinError(i,cur_alpgen_ratio_err);


	}

	// sherpa
	float sherpa_bkgd_count= h_sherpa_bkgd[p][v]->GetBinContent(i);
	float sherpa_bkgd_err=sqrt(sherpa_bkgd_count);
	// Luminosity Error
	float sherpa_lumi_error = sherpa_bkgd_count*0.037;
	sherpa_bkgd_err = sqrt(pow(sherpa_lumi_error,2.)+pow(sherpa_bkgd_err,2.));


	if(sherpa_bkgd_count && data_count) {
	    
	  //////////////////////////////////////////////////
	  // relErr((D-B)/B) = sqrt( (Err(D-B)/(D-B))^2 + (Err(B)/B)^2)

	  //Err(D-B)
	  double comb_sherpa_bkgd_data_err =
	    sqrt(pow(data_err,2.)+pow(sherpa_bkgd_err,2.));

	  // Err(D-B)/(D-B)
	  double rel_sherpa_bkgd_data_err =
	    comb_sherpa_bkgd_data_err/(data_count-sherpa_bkgd_count);

	  // Err(B)/B
	  double rel_sherpa_bkgd_err =
	    sherpa_bkgd_err/sherpa_bkgd_count;

	  // relErr((D-B)/B)
	  double rel_sherpa_ratio_err =
	    sqrt(pow(rel_sherpa_bkgd_data_err,2.)+pow(rel_sherpa_bkgd_err,2.));

	  double cur_sherpa_ratio = (data_count-sherpa_bkgd_count)/sherpa_bkgd_count;
	  double cur_sherpa_ratio_err = fabs(rel_sherpa_ratio_err*cur_sherpa_ratio);
	 
	  sherpa_ratio->SetBinContent(i,cur_sherpa_ratio);
	  sherpa_ratio->SetBinError(i,cur_sherpa_ratio_err);
	}
      }

      h_sherpa_ratio[p][v] = (TH1F*) sherpa_ratio;
      h_alpgen_ratio[p][v] = (TH1F*) alpgen_ratio;
    }// vars
  }// procs

  //////////////////////////////////////////////////
  // Plotting Loop
  ////////////////////////////////////////////////// 

  const int nCanvases = nProcs*nVars;
  TCanvas* canvases[nCanvases];
  TPad* ratio_pads[nCanvases];
  TPad* plot_pads[nCanvases];

  int c=0; //canvas index
  for(int p=0;p<nProcs;p++){// e.g. elec,muon
    string proc = procs[p];
    for(int v=0;v<nVars;v++){// e.g. nocut_dijet_pt, dijet_m_lep_met_mt
      string var = vars[v];
      
      string canvas_name = "tc_vjets_"+event_type+"_"+proc+"_"+var;
	string hist_name = "h_vjets_"+event_type+"_"+proc+"_"+var;

	//////////////////////////////////////////////////
	// make canvas
	////////////////////////////////////////////////// 

	canvases[c] = 
	  new TCanvas(canvas_name.c_str(),canvas_name.c_str(),0,0,1920,1200);
	canvases[c]->cd();

	
	ratio_pads[c] = new TPad("ratio_pad","ratio_pad",0.01,0.01,0.99,ratio_split);
	ratio_pads[c]->SetTopMargin(0.05);
	ratio_pads[c]->SetBottomMargin(0.31);
	ratio_pads[c]->Draw();

	plot_pads[c] = new TPad("plot_pad","plot_pad",0.01,ratio_split,0.99,0.99);
	plot_pads[c]->SetBottomMargin(0);
	plot_pads[c]->Draw();
	plot_pads[c]->cd();
	plot_pads[c]->Update();  
     
	
	stk_alpgen_bkgd[p][v]->Draw();
	((THStack*) stk_alpgen_bkgd[p][v])->SetMinimum(0.1);
	stk_alpgen_bkgd[p][v]->Draw("hist");

	//h_sherpa_bkgd[p][v]->SetLineColor(sherpa_color);
	h_sherpa_bkgd[p][v]->SetLineWidth(1);
	h_sherpa_bkgd[p][v]->GetXaxis()->SetTitle(plot_vars[v].c_str());
	h_sherpa_bkgd[p][v]->Draw("hist sames");


	h_data[p][v]->SetMarkerStyle(data_marker_style);
	h_data[p][v]->SetMarkerSize(data_marker_size);
	h_data[p][v]->Draw("sames PE");

	cout<<vars[v]<<endl;
	if(vars[v].find("avg_int_per_xing") == string::npos &&
	   vars[v].find("dijet_m")==string::npos){
	  plot_pads[c]->SetLogy();
	}
	canvases[c]->Update();

	//////////////////////////////////////////////////
	// make legend
	////////////////////////////////////////////////// 

	TLegend* lgnd = new TLegend(0.63,0.7,0.9,0.9);
	lgnd->SetFillColor(0);
	lgnd->SetTextSize(0.045);
	lgnd->AddEntry(h_data[p][v],"data","F");
	lgnd->AddEntry(h_sherpa_bkgd[p][v],"SHERPA (qcd,v+jets)","F");
	lgnd->AddEntry(h_alpgen_bkgd[p][v],"ALPGEN (qcd,v+jets)","F");
	lgnd->AddEntry(top_hist,"mc.mcatnlo.top","F");
	lgnd->AddEntry(vv_hist,"mc.herwig.vv","F");
	lgnd->Draw();
	
	//////////////////////////////////////////////////
	// Do ratio
	////////////////////////////////////////////////// 

	ratio_pads[c]->cd();
	ratio_pads[c]->SetGrid();
  
	TAxis* alpgen_ratio_xaxis= h_alpgen_ratio[p][v]->GetXaxis();
	TAxis* alpgen_ratio_yaxis= h_alpgen_ratio[p][v]->GetYaxis();

	h_alpgen_ratio[p][v]->SetMarkerStyle(20);
	h_alpgen_ratio[p][v]->SetMarkerSize(2);
	h_alpgen_ratio[p][v]->SetLineWidth(1);
	h_alpgen_ratio[p][v]->SetLineColor(alpgen_color);

	alpgen_ratio_xaxis->SetLabelSize(0.08);
	alpgen_ratio_yaxis->SetLabelSize(0.08);
    
	alpgen_ratio_xaxis->SetTitle(plot_vars[v].c_str());
	alpgen_ratio_xaxis->SetTitleSize(0.16);
	alpgen_ratio_xaxis->SetTitleOffset(0.7);
	alpgen_ratio_yaxis->SetNdivisions(4,4,4);
	alpgen_ratio_yaxis->SetTitle("(data-MC)/MC");
	alpgen_ratio_yaxis->SetTitleSize(0.07);
	alpgen_ratio_yaxis->SetTitleOffset(0.36);

	alpgen_ratio_yaxis->SetRangeUser(-0.5,0.5);
	h_alpgen_ratio[p][v]->Draw("PE");
	canvases[c]->Update();
	
	TAxis* sherpa_ratio_yaxis= h_sherpa_ratio[p][v]->GetYaxis();
	h_sherpa_ratio[p][v]->SetMarkerStyle(20);
	h_sherpa_ratio[p][v]->SetMarkerSize(2);
	h_sherpa_ratio[p][v]->SetLineColor(sherpa_color);
	sherpa_ratio_yaxis->SetRangeUser(-0.5,0.5);
	h_sherpa_ratio[p][v]->Draw("PE sames");
	canvases[c]->Update();



	plot_pads[c]->cd();
	canvases[c]->RedrawAxis();
	double leg_x1 = lgnd->GetX1NDC();
	double leg_y1 = lgnd->GetY1NDC();
	double offset_x1 = -0.02;
	double offset_y1 = 0.08;
	// If you want to write text on the plot (e.g. integrated luminosity)
	//string atlas_text    = "ATLAS pre-approval";

	string sqrts_text    = "#sqrt{s}= 7 TeV";
	string lumi_text     = "#int Ldt = 4.701 fb^{-1}";
	myText(leg_x1-offset_x1, leg_y1-offset_y1, 1, sqrts_text.c_str());
	myText(leg_x1-offset_x1 + 0.1, leg_y1-offset_y1,1,  lumi_text.c_str());


	string cur_saveas = plot_loc+hist_name+save_ext;
	canvases[c]->SaveAs(cur_saveas.c_str());
	
	++c;
    }
  }

  sherpa_wjets->Close();
  sherpa_zjets->Close();
  vv->Close();
  alpgen_qcd->Close();
  sherpa_qcd->Close();  
  top->Close();
  alpgen_zjets->Close();
  sherpa_zjets->Close();
  
  gROOT->ProcessLine(".q");
}
////////////////////////////////////////////////////////////////////////////////////////
// Draw and save the canvas
// This bit shouldn't need to be updated except the region and channel labels
// As of Jan 10,2013 - the known issues are:
// ++ Error bands don't show correctly
// ++ Data histogram needs to be converted to TGraphAsymmErrors and 
//    plotted w/ poisson errors
// ++ Ratio plot needs to divide the Data TGraphAsymmErrors and
//    TGraphAsymmErrors for the total SM (by turning off the errors since they are
//    shown explicitly)
////////////////////////////////////////////////////////////////////////////////////////
void PlotUnifier(
                  TH1F* histos[9],                   // Array of pointers to histograms
                  TGraphAsymmErrors* smErrorBand,    // Error band for the top pad
                  TGraphAsymmErrors* ratioErrorBand  // Error band for the bottom pad
                )
{
  ////////////////////////////////////////////////////////////////////////////////////////
  // Set Histogram Properties, build the stack and make the ratio plot
  histos[0]->SetMarkerStyle(20)     ; histos[0]->SetMarkerSize(1.2); 
  histos[1]->SetFillColor(kOrange-2); histos[4]->SetLineWidth (2);
  histos[2]->SetFillColor(kAzure-9 ); histos[1]->SetLineWidth (2);
  histos[3]->SetFillColor(kSpring+1); histos[2]->SetLineWidth (2);
  histos[4]->SetFillColor(kAzure+4 ); histos[3]->SetLineWidth (2);
  histos[5]->SetFillColor(kGray    ); histos[5]->SetLineWidth (2);
  histos[6]->SetFillColor(kYellow-9); histos[6]->SetLineWidth (2);
  histos[7]->SetLineColor(kMagenta ); histos[7]->SetLineWidth (3); histos[7]->SetLineStyle(2);
  histos[8]->SetLineColor(kGreen+1 ); histos[8]->SetLineWidth (3); histos[8]->SetLineStyle(2);
  
  ////////////////////////////////////////////////////////////////////////////////////////
  // Here comes the stack 
  THStack* sm = new THStack("sm","sm");
  sm->Add(histos[6]);
  sm->Add(histos[5]);
  sm->Add(histos[4]);
  sm->Add(histos[3]);
  sm->Add(histos[2]);
  sm->Add(histos[1]);

  ////////////////////////////////////////////////////////////////////////////////////////
  // Define the legend and fill in the stack order
  TLegend* legendA        = new TLegend(0.49,0.65,0.74,0.85);
  TLegend* legendB        = new TLegend(0.62,0.65,0.87,0.85);
  legendA->SetTextFont(42);    
  legendB->SetTextFont(42);    
  legendA->SetTextSize(0.03);
  legendB->SetTextSize(0.03);
  legendA->SetBorderSize(0);
  legendB->SetBorderSize(0);
  legendA->SetFillColor(0);
  legendB->SetFillColor(0);
  legendA->AddEntry(histos[0],"Data"               ,"p");
  legendA->AddEntry(histos[1],"Z+jets"             ,"f");
  legendA->AddEntry(histos[2],"WW"                 ,"f");
  legendA->AddEntry(histos[3],"t#bar{t}+Wt"        ,"f");
  legendA->AddEntry(histos[4],"ZV"                 ,"f");
  legendB->AddEntry(histos[5],"Non-prompt leptons" ,"f");
  legendB->AddEntry(histos[6],"Higgs"              ,"f");
  TH1F* histoError = new TH1F("histoError"         ,"histoError",1,0,1);
  histoError->SetFillStyle(3004);
  histoError->SetFillColor(kBlack);
  legendB->AddEntry(histoError,"Bkg. Uncert."      ,"f");
  legendB->AddEntry(histos[7],"Signal 1"           ,"l");
  legendB->AddEntry(histos[8],"Signal 2"           ,"l");

  ////////////////////////////////////////////////////////////////////////////////////////
  // Ratio plot 
  TH1F* ratio      = (TH1F*) histos[0]->Clone(); ratio->Reset(); 
  TH1F* stackHisto = (TH1F*) sm->GetStack()->Last();
  ratio->Divide(histos[0],stackHisto);
  ratio->SetMarkerSize(1.2);
  ratio->SetMarkerStyle(20);
  ratio->SetLineColor(kBlack);
  ratio->SetLineWidth(2);

  ratio->GetXaxis()->SetTitle("Observable");
  ratio->GetYaxis()->SetTitle("Data/SM");
  ratio->GetXaxis()->SetLabelSize(0.13);
  ratio->GetXaxis()->SetLabelOffset(0.02);
  ratio->GetXaxis()->SetTitleSize(0.14);
  ratio->GetXaxis()->SetTitleOffset(1.2);

  ratio->GetYaxis()->SetRangeUser(0,2);
  ratio->GetYaxis()->SetLabelSize(0.13);
  ratio->GetYaxis()->SetLabelOffset(0.0125);
  ratio->GetYaxis()->SetTitleSize(0.14);
  ratio->GetYaxis()->SetTitleOffset(0.5);
  ratio->GetYaxis()->SetNdivisions(5);

  ////////////////////////////////////////////////////////////////////////////////////////
  // Error bands
  smErrorBand->SetMarkerSize(0); 
  smErrorBand->SetFillStyle(3004);
  smErrorBand->SetFillColor(kBlack);
  ratioErrorBand->SetMarkerSize(0); 
  ratioErrorBand->SetFillStyle(3004);
  ratioErrorBand->SetFillColor(kBlack);
 
  ////////////////////////////////////////////////////////////////////////////////////////
  // Draw and save the canvas
  TCanvas* canvas = new TCanvas("canvas","canvas",500,500);
  TPad*    topPad = new TPad("pTop","pTop",0,0.2,1,1);
  TPad*    botPad = new TPad("pBot","pBot",0,0.0,1,0.3);
  topPad->Draw();
  botPad->Draw();

  ////////////////////////////////////////////////////////////////////////////////////////
  // Data is special since I use it to draw the axis labels etc.
  histos[0]->GetXaxis()->SetTitle("Observable"); 
  histos[0]->GetYaxis()->SetTitle("Events / Bin"); 
  histos[0]->GetXaxis()->SetLabelOffset(1.2); 
  histos[0]->GetXaxis()->SetLabelSize(0.03);
  histos[0]->GetYaxis()->SetRangeUser(1.e-2,1.e5);
  histos[0]->GetYaxis()->SetTitleSize(0.055);
  histos[0]->GetYaxis()->SetTitleOffset(1.28);
  histos[0]->GetYaxis()->SetLabelSize(0.05);
  histos[0]->GetYaxis()->SetLabelOffset(0.01);

  ////////////////////////////////////////////////////////////////////////////////////////
  // Top Pad
  topPad      ->cd();
  topPad      ->SetBottomMargin(0.15);
  histos[0]   ->Draw("p && e && x0");
  sm          ->Draw("same && hists");
  smErrorBand ->Draw("same && E2");
  histos[0]   ->Draw("same && p && e && x0");
  histos[7]   ->Draw("same && hist");
  histos[8]   ->Draw("same && hist");
  legendA     ->Draw();
  legendB     ->Draw();
  gPad        ->RedrawAxis();
  gPad        ->SetLogy(1);

  ////////////////////////////////////////////////////////////////////////////////////////
  // Decoration
  char annoyingLabel1[100] = "#bf{#it{ATLAS}}, #sqrt{s} = 8 TeV, 20.3 fb^{-1}";
  char annoyingLabel2[100] = "SF/DF channel"; 
  char annoyingLabel3[100] = "- Top CR for SR-#scale[0.9]{m_{T2}} and SR-WWb/c";
  myText(0.53,0.880,kBlack,annoyingLabel1);
  myText(0.17,0.965,kBlack,annoyingLabel2);
  myText(0.37,0.965,kBlack,annoyingLabel3);

  ////////////////////////////////////////////////////////////////////////////////////////
  // Bottom Pad
  botPad ->cd();
  botPad ->SetBottomMargin(0.4);
  
  ////////////////////////////////////////////////////////////////////////////////////////
  // 1 Line
  TLine* line = new TLine(histos[0]->GetXaxis()->GetXmin(),1,histos[0]->GetXaxis()->GetXmax(),1);
  line   ->SetLineColor(kRed);
  line   ->SetLineStyle(7);

  ////////////////////////////////////////////////////////////////////////////////////////
  // Draw
  ratio          ->Draw("p && e && x0");
  ratioErrorBand ->Draw("same && E2");
  line           ->Draw("same");
  ratio          ->Draw("same && p && e && x0");
  gPad           ->SetGridy(1);

  ////////////////////////////////////////////////////////////////////////////////////////
  // Save
  canvas ->SaveAs("Test_v3.eps");

}