예제 #1
0
//void makeHist(const int sample, const int dataset=1)
void makeHist(const string title="")
{
	vector<Hist> hist2print;
	TPaveText *tx = new TPaveText(.05,.1,.95,.8);
//	tx->AddText("Using Deafult JERs for all jets");
//	tx->AddText("Using b-Jet JERs");

/*	string title("QCD MG:");

	//if (sample==1) title += "NJet(70/50/30>=2/4/5), #slash{E}_{T}>175, Triplet>1, 80<TopMass<270, TOP+0.5*BJET>500, MT2>300, #Delta#Phi(.5,.5,.3), BJets>=1";
	if (sample==1)      title += "All Stop cuts applied (use default JERs for all jets)";
	else if (sample==2) title += "All Stop cuts applied + Inverted #Delta#Phi (use default JERs for all jets)";
	else if (sample==3) title += "All Stop cuts applied (use b-Jet JERs)";
	else if (sample==4) title += "All Stop cuts applied + Inverted #Delta#Phi (use b-Jet JERs)";
	else if (sample==5) title += "No cuts applied";
*/
	unsigned bitMaskArray[] = {0,1,2,3,129,130,131,195,257,258,269,323};
	vector<unsigned> vBitMaskArray(bitMaskArray, bitMaskArray + sizeof(bitMaskArray) / sizeof(unsigned));



	stringstream unclmet_title;
	unclmet_title << title << "Unclutered MET";
	hist2print.push_back(Hist("met",title,2,0.0, 400.0,1));
	hist2print.push_back(Hist("unclmet",unclmet_title.str().c_str(),2,0.0, 100.0,1));
	hist2print.push_back(Hist("mht",title,2,0.0, 400.0,1));
	hist2print.push_back(Hist("ht",title,2,0,2000,1));
	hist2print.push_back(Hist("njet30eta5p0",title,1,0,15,1));
	hist2print.push_back(Hist("nbjets",title,1,0,10,1));
//	hist2print.push_back(Hist("bjetPt",title,2));
	hist2print.push_back(Hist("M123",title,2));
//	hist2print.push_back(Hist("M23overM123",title));
	hist2print.push_back(Hist("MT2",title,2));
	hist2print.push_back(Hist("MTb",title,4));
	hist2print.push_back(Hist("MTt",title,4));
	hist2print.push_back(Hist("MTb_p_MTt",title,2,400,1000,1));
	//hist2print.push_back(Hist("jet1_pt",title,2));
	//hist2print.push_back("bjetPt");
//	hist2print.push_back(Hist("bjetMass",title,2,0,200));
//	hist2print.push_back(Hist("dphimin",title,4));


	TFile *outRootFile = new TFile("Merged.root");

	/*TPad *c1=0, *c2=0;
	TCanvas *c = GetCanvas(c1, c2);
	if (c ==NULL|| c1 == 0 ||c2 == 0)
	{
		cout << " A drawing pad is null !"<< endl;
		cout << "c = " << c << endl;
		cout << "c1 = " << c1 << endl;
		cout << "c2 = " << c2 << endl;
		assert(false);
	}*/
   TCanvas *c = new TCanvas("c1");
   c->Range(0,0,1,1);
   c->SetBorderSize(2);
   c->SetFrameFillColor(0);
  
// ------------>Primitives in pad: c1_1
   TPad *c1_1 = new TPad("c1_1", "c1_1",0.01,0.30,0.99,0.99);
   c1_1->Draw();
   c1_1->cd();
   c1_1->SetBorderSize(2);
   c1_1->SetTickx(1);
   c1_1->SetTicky(1);
   c1_1->SetTopMargin(0.1);
   c1_1->SetBottomMargin(0.0);
   //c1_1->SetFrameFillColor(3);
	//c1_1->SetLogy();
  
  c->cd();
// ------------>Primitives in pad: c1_2
   TPad *c1_2 = new TPad("c1_2", "c1_2",0.01,0.01,0.99,0.30);
   c1_2->Draw();
   c1_2->cd();
   c1_2->SetBorderSize(2);
   c1_2->SetTickx(1);
   c1_2->SetTicky(1);
   c1_2->SetTopMargin(0.0);
   c1_2->SetBottomMargin(0.24);
   c1_2->SetFrameFillColor(0);
	c1_2->SetGridx();
	c1_2->SetGridy();
	c->cd();
	gStyle->SetOptStat(0);
	gPad->Print("samples.eps[");

	for (unsigned i=0;i<vBitMaskArray.size(); ++i)
	{
		unsigned mask = vBitMaskArray.at(i);
		for (unsigned ihist=0; ihist < hist2print.size(); ++ihist)
		{
			stringstream path, reco_hist_name, gen_hist_name, smear_hist_name;
			stringstream reco_hist, gen_hist, smear_hist;
			stringstream folder;
			folder << "Hist/Mask"<< mask << "HT0to8000MHT0to8000/";
			//cout << "folder = " << folder.str() << endl;

			/*	if ((hist2print.at(ihist).Name()).find("Jet"))
				{
				reco_hist_name << folder.str() << "reco" << hist2print.at(ihist).Name() << "_copy";
				reco_hist << folder.str() << "reco" << hist2print.at(ihist).Name();
				smear_hist_name << folder.str() << "smeared" << hist2print.at(ihist).Name() << "_copy";
				smear_hist << folder.str() << "smeared" << hist2print.at(ihist).Name();
				gen_hist_name << folder.str() << "gen" << hist2print.at(ihist).Name() << "_copy";
				gen_hist << folder.str() << "gen" << hist2print.at(ihist).Name();
				} else
				*/	{
					reco_hist_name << folder.str() << "reco_" << hist2print.at(ihist).Name() << "_copy";
					reco_hist << folder.str() << "reco_" << hist2print.at(ihist).Name();
					smear_hist_name << folder.str() << "smeared_" << hist2print.at(ihist).Name() << "_copy";
					smear_hist << folder.str() << "smeared_" << hist2print.at(ihist).Name();
					gen_hist_name << folder.str() << "gen_" << hist2print.at(ihist).Name() << "_copy";
					gen_hist << folder.str() << "gen_" << hist2print.at(ihist).Name();
				}

				TH1* hreco = (TH1*) (outRootFile->Get(reco_hist.str().c_str()));
				if (hreco == NULL) { cout << "hreco = " << reco_hist.str() << " was not found!" << endl; assert(false); } 
				hreco->SetDirectory(0);
				TH1* hsmear = (TH1*) (outRootFile->Get(smear_hist.str().c_str()));
				if (hsmear == NULL) { cout << "hsmear = " << smear_hist.str() << " was not found!" << endl; assert(false); } 
				hsmear->SetDirectory(0);
				TH1* hgen = (TH1*) (outRootFile->Get(gen_hist.str().c_str()));
				//->Clone(gen_hist_name.str().c_str()));
				if (hgen == NULL) { cout << "hgen = " << gen_hist.str() << " was not found!" << endl; assert(false); } 
				hgen->SetDirectory(0);

				hreco->Sumw2();
				hsmear->Sumw2();
				hgen->Sumw2();

				const int rebin = hist2print.at(ihist).Rebin();
				const string title = hist2print.at(ihist).Title();
				const double xmin = hist2print.at(ihist).Xmin();
				const double xmax = hist2print.at(ihist).Xmax();

				if (rebin>1)
				{
					hreco->Rebin(rebin);
					hsmear->Rebin(rebin);
					hgen->Rebin(rebin);
				}
				if (title.length()>0)
				{
					hreco->SetTitle(title.c_str());
					hsmear->SetTitle(title.c_str());
					hgen->SetTitle(title.c_str());
				}
				if (xmin != LargeNegNum || xmax != LargeNegNum)
				{
					hreco->GetXaxis()->SetRangeUser(xmin,xmax);
					hsmear->GetXaxis()->SetRangeUser(xmin,xmax);
					hgen->GetXaxis()->SetRangeUser(xmin,xmax);
				}

				const double reco_max_y  = hreco->GetBinContent(hreco->GetMaximumBin());
				const double smear_max_y = hsmear->GetBinContent(hsmear->GetMaximumBin());
				const double y_max = max(reco_max_y, smear_max_y);
				double y_min = 9999.0;
				for (unsigned bin=1; bin<hreco->GetNbinsX(); ++bin)
				{
					const double v1 = hreco->GetBinContent(bin);
					const double v2 = hsmear->GetBinContent(bin);
					const double minv = min(v1,v2);
					if (minv != 0 && minv < y_min) y_min = minv;
					
				}

				cout << hreco->GetName() << "->ymin/max = " << y_min << "(" << y_min/2.0 << ")/" << y_max << "(" << y_max*2.0 << ")" << endl;
				hreco->GetYaxis()->SetRangeUser(y_min/2.0, y_max*2.0);
				hsmear->GetYaxis()->SetRangeUser(y_min/2.0, y_max*2.0);


				hgen->SetLineColor(kBlue);
				hgen->SetMarkerColor(kBlue);
				hgen->SetMarkerStyle(24);
				hgen->SetLineWidth(2);
				hsmear->SetLineColor(kRed);
				hsmear->SetMarkerColor(kRed);
				hsmear->SetMarkerStyle(24);
				hsmear->SetLineWidth(2);
				hreco->SetLineWidth(2);
				hreco->SetMarkerStyle(kDot);
				hreco->SetLineColor(kBlack);
				hreco->SetMarkerColor(kBlack);
				//hreco->GetXaxis()->SetRangeUser(0,300);
				//hsmear->GetXaxis()->SetRangeUser(0,300);


				hreco->GetYaxis()->CenterTitle(1);
				hreco->SetLabelFont(42,"XYZ");
				hreco->SetTitleFont(42,"XYZ");
				hreco->GetYaxis()->SetTitleOffset(0.8);
				hreco->SetLabelSize(0.05,"XYZ");
				hreco->SetTitleSize(0.06,"XYZ");


				TH1 *hsmeartoreco_ratio = (TH1*) (hsmear->Clone("hsmear_copy"));
				hsmeartoreco_ratio->Divide(hreco);
				hsmeartoreco_ratio->SetTitle("");
				hsmeartoreco_ratio->GetYaxis()->SetTitle("Smear/Reco");
				hsmeartoreco_ratio->GetYaxis()->SetRangeUser(0,2.);

				hsmeartoreco_ratio->GetYaxis()->SetTitleOffset(0.4);
				hsmeartoreco_ratio->GetXaxis()->SetTitleOffset(0.9);
				hsmeartoreco_ratio->GetYaxis()->CenterTitle(1);
				hsmeartoreco_ratio->GetXaxis()->CenterTitle(1);
				hsmeartoreco_ratio->SetLabelSize(0.125,"XYZ");
				hsmeartoreco_ratio->SetTitleSize(0.125,"XYZ");
				//	hsmeartoreco_ratio->SetLabelFont(labelfont,"XYZ");
				//	hsmeartoreco_ratio->SetTitleFont(titlefont,"XYZ");
				hsmeartoreco_ratio->GetXaxis()->SetTickLength(0.07);



				stringstream recoleg,smearleg, genleg;
				const double sum_reco  = hreco->Integral(1, hreco->GetNbinsX()+1);
				const double sum_smear = hsmear->Integral(1, hsmear->GetNbinsX()+1);
				const double sum_gen   = hgen->Integral(1, hgen->GetNbinsX()+1);
				const double err_reco  = StatErr(hreco);
				const double err_smear = StatErr(hsmear);


				cout << setprecision(1) << fixed;

				recoleg << "Reco (" << sum_reco << "#pm" << err_reco << ")";
				smearleg << "Smear (" << sum_smear << "#pm" << err_smear << ")";
				genleg << "Gen (" << sum_gen << ")";
				cout <<  smear_hist_name.str() << "::reco/smear = " << sum_reco << "/" << sum_smear << endl;

				TLegend *l2 = new TLegend(0.6,0.6,0.9,0.9);
				l2->AddEntry(hreco, recoleg.str().c_str());
				//l2->AddEntry(hgen, genleg.str().c_str());
				l2->AddEntry(hsmear, smearleg.str().c_str());

				c1_1->cd();
				gPad->SetLogy(hist2print.at(ihist).LogY());

				hreco->DrawCopy();
				//hgen->DrawCopy("same");
				hsmear->DrawCopy("same");
				l2->Draw();
				//tx->Draw();
				c1_2->cd();
				hsmeartoreco_ratio->DrawCopy();
				c->cd();
				gPad->Print("samples.eps");

		}
	}

	gPad->Print("samples.eps]");
}
예제 #2
0
void AnalyzeData(char *DataFile = "drs4_peds_5buffers.dat", Int_t nevt,
		Int_t startEv = 1, char *PedFile, Int_t DrawExtraGraphs = 0) {


	// Redefine DOMINO Depth in ADC counts
	const Float_t DominoDepthADC = pow(2, DOMINO_DEPTH);

	// open file

	FILE *fdata = OpenDataFile(DataFile);
	struct channel_struct *p;
	struct channel_struct *dep;

	// create histograms
	// create list of histograms for channels and distribution

	TList *DistChList = new TList();
	TH1F *distch; // histo with distribution of cell-charge, for each channel

	TList *DistChSubList = new TList();
	TH1F *distchsub; // histo with distribution of cell-charge, pedestals subtracted, for each channel

	TList *DistCh0SubList = new TList();
	TH1F *distch0sub; // histo with distribution of cell-charge, pedestals subtracted,
	// channel 0 subtracted for each channel

	TList *grPedList = new TList();
	TGraphErrors *grPed; // for each channel, pedestal value and RMS for each cell is plotted

	TList *hCellList = new TList();
	TH1F *hCell; // charge distribution for each cell (DOMINO_NCELL x DOMINO_NCH histos)
	TList *hCellSubList = new TList();
	TH1F *hCellSub; // charge distribution for each cell (DOMINO_NCELL x DOMINO_NCH histos), pedestal subtracted

	TList *hRMSList = new TList();
	TH1F *hRMSdist; // histo with RMS distribution (statistical RMS of distribution)
	TList *hRMSFitList = new TList();
	TH1F *hRMSFitdist; // histo with RMS distribution (RMS of Gaussian fit)

	TList *grDataList = new TList();
	TGraphErrors *grData; // charge-cell and RMS for each cell is plotted

	TList *grDataSubList = new TList();
	TGraphErrors *grDataSub; // pedestal subtracted charge-cell and RMS for each cell is plotted


	for (int h = 0; h < DOMINO_NCH; h++) {
		//
		TString title = "Data Dist channel";
		title += h;
		distch = new TH1F(title, title, DominoDepthADC, 0., DominoDepthADC);
		DistChList->Add(distch);
		//
		TString title = "Data Dist Ped Sub channel";
		title += h;
		distchsub = new TH1F(title, title, DominoDepthADC, -DominoDepthADC/2, DominoDepthADC/2);
		DistChSubList->Add(distchsub);
		//
		TString title = "Data Dist Ped Ch0 Sub channel";
		title += h;
		distch0sub = new TH1F(title, title, DominoDepthADC, -DominoDepthADC/2, DominoDepthADC/2);
		DistCh0SubList->Add(distch0sub);
		//
		TString title = "Pedestal ch";
		title += h;
		grPed = new TGraphErrors(DOMINO_NCELL);
		grPed->SetTitle(title);
		grPedList->Add(grPed);
		//
		TString title = "Data ch";
		title += h;
		grData = new TGraphErrors(DOMINO_NCELL);
		grData->SetTitle(title);
		grDataList->Add(grData);
		//
		// Mean data and RMS for each channel and cell
		TString title = "Data PedSubtracted ch";
		title += h;
		grDataSub = new TGraphErrors(DOMINO_NCELL);
		grDataSub->SetTitle(title);
		grDataSubList->Add(grDataSub);
		//
		for (int ch = 0; ch < DOMINO_NCELL; ch++) {
			// data distribution histos
			TString title = "Data ch";
			title += h;
			title += " cell";
			title += ch;
			hCell = new TH1F(title, title, DominoDepthADC, 0., DominoDepthADC);
			hCellList->Add(hCell);
			// data (ped subtracted) distribution histos
			TString title = "Data PedSub ch";
			title += h;
			title += " cell ";
			title += ch;
			hCellSub = new TH1F(title, title, 2 * DominoDepthADC, -1
					* DominoDepthADC, DominoDepthADC);
			hCellSubList->Add(hCellSub);
		}
		// Data-RMS distribution histos
		TString title = "RMSDist channel";
		title += h;
		hRMSdist = new TH1F(title, title, 100, 0, 20.);
		hRMSList->Add(hRMSdist);
		// Data-RMS (calculated through a fit) distribution histos
		TString title = "RMSFitDist channel";
		title += h;
		hRMSFitdist = new TH1F(title, title, 100, 0, 20.);
		hRMSFitList->Add(hRMSFitdist);
	}
	//--------------
	//
	// calculate or read pedestals from file
	grPedList = OpenPedestals(PedFile);

	//    return;
	//
	// ====== Read data file and subtract the pedestals
	//
	// Count number of events in data file
	int nevtDataMax = 0;
	while (!feof(fdata)) {
		fread((void *) &event_data, 1, sizeof(event_data), fdata);
		nevtDataMax++;
	}
	printf("nevtDataMax: %d\n", nevtDataMax);

	if (nevt > (nevtDataMax - startEv) || nevt == 0)
		nevt = nevtDataMax - startEv;
	cout << endl << "==>> Processing " << nevt << " events from file "
			<< DataFile << endl;

	rewind(fdata);

	Int_t ievt = 1;
	// go to first event (startEv)
	while (ievt < startEv) {
		fread((void *) &event_data, 1, sizeof(event_data), fdata);
		if (feof(fdata))
			break;
		ievt++;
	}
	// filling
	ievt = 1;
	Int_t flagEnd = 0;
	Double_t chtmp;
	Double_t PedVal, itmp, Ch0Val;
	// loop on events
	cout << endl << " --- read DATA file:" << fdata << endl;
	while (ievt <= nevt && !flagEnd) {
		fread((void *) &event_data, 1, sizeof(event_data), fdata);
		if (feof(fdata))
			flagEnd = 1;
		if (ievt % (nevt / 10 + 1) == 0)
			cout << "*" << endl;
		p = (struct channel_struct *) &event_data.ch[0]; // read bunch of data
		dep = (struct channel_struct *) &event_data.ch[1]; // read bunch of data

		TGraphErrors *grCh0 = new TGraphErrors(DOMINO_NCELL);

		// loop on channels
		for (int h = 0; h < DOMINO_NCH; h++) {
			// loop on cells
			distch = (TH1F *) DistChList->At(h);
			distchsub = (TH1F *) DistChSubList->At(h);
			grPed = (TGraphErrors *) grPedList->At(h);
			distch0sub = (TH1F *) DistCh0SubList->At(h);
			if(h==0) {
				for(i = 0; i < DOMINO_NCELL;i++) {
					grPed->GetPoint(i, itmp, PedVal);
					chtmp = (Double_t)(p->data[i]);
					chtmp = chtmp - PedVal;
					grCh0->SetPoint(i,itmp, chtmp);
				}
			}
			for (int i = 0; i < DOMINO_NCELL; i++) {
				// Read pedestal value for this cell
				grPed->GetPoint(i, itmp, PedVal);
				grCh0->GetPoint(i, itmp, Ch0Val);
				//                cout << itmp << ", " << PedVal << endl;
				// Read calibration correction for this cell
				//                CalFact =

				//charge distribution for each cell, pedestal subtracted
				chtmp = (Double_t)(p->data[i]); // data value
				//                cout  << "tcell, tcell, depth: " << chtmp << ","  << p->data[i] << "," << deptmp << endl;
				distch->Fill(chtmp);
				// Check data value: must be within DOMINO Depth
				//                if(chtmp > DominoDepthADC)
				//                    cout << " === WARNING!!! Channel " << h << " Cell " << i << " has value " << chtmp << endl;
				//                cout << "Charge: " << p->data[i] << endl;
				((TH1 *) hCellList->At(h * DOMINO_NCELL + i))->Fill(chtmp);
				// Now the pedestal is subtracted
				chtmp = chtmp - PedVal;
				distchsub->Fill(chtmp);
				((TH1 *) hCellSubList->At(h * DOMINO_NCELL + i))->Fill(chtmp);
				chtmp = chtmp - Ch0Val;
				distch0sub->Fill(chtmp);
			}
			p++; // next channel
		}
		ievt++; // next event
	}
	cout << endl;

	// now mean and RMS for each cell are computed and save in histos and graphs
	cout << " --- filling data histos and grphs " << endl;
	TF1 *fgauss = new TF1("fgauss", Gauss, -10., 10., 3);
	fgauss->SetParLimits(0, 0.1, 10000.);
	fgauss->SetParLimits(1, 0., 4096.);
	fgauss->SetParLimits(2, 0.1, 20.);
	Float_t mean, rms, meansub, rmssub;
	for (int h = 0; h < DOMINO_NCH; h++) {
		//        for (int h=5; h<6; h++){
		cout << " Channel:" << h << endl;
		hRMSdist = (TH1F *) hRMSList->At(h);
		hRMSFitdist = (TH1F *) hRMSFitList->At(h);
		grData = (TGraphErrors *) grDataList->At(h);
		grDataSub = (TGraphErrors *) grDataSubList->At(h);
		for (int ch = 0; ch < DOMINO_NCELL; ch++) {
			// data distribution histos
			//            cout << "cell:" << ch << " index:" << h*DOMINO_NCELL+ch << " Mean,RMS:"<<hCell->GetMean()<< "," << hCell->GetRMS()<<endl;
			hCell = (TH1F *) hCellList->At(h * DOMINO_NCELL + ch);
			mean = hCell->GetMean();
			rms = hCell->GetRMS();
			hCellSub = (TH1F *) hCellSubList->At(h * DOMINO_NCELL + ch);
			meansub = hCellSub->GetMean();
			rmssub = hCellSub->GetRMS();
			fgauss->SetParameter(0, (Double_t) nevt / 4.);
			fgauss->SetParameter(1, mean);
			fgauss->SetParameter(2, rms);
			//            hCell->Fit("fgauss","QN0");
			grData->SetPoint(ch, ch, mean);
			grData->SetPointError(ch, 0, rms);
			grDataSub->SetPoint(ch, ch, meansub);
			//            grDataSub->SetPointError(ch,0.5,rmssub);
			grDataSub->SetPointError(ch, 0.5, 2.1);
			hRMSdist->Fill(rms);
			hRMSFitdist->Fill(fgauss->GetParameter(2));
			//           cout << "cell:" << ch << " index:" << h*DOMINO_NCELL+ch << " Mean,RMS:"<< mean << "," << rms<<endl;
		}
	}

	Double_t x, y, chtmp, x1, x2, y1, y2;

	/*TList *grCellCalibList = OpenCalibFile("CalibrationData1000events.root");

	TGraphErrors *grCellCalib;
	TGraphErrors *grDataSubCalib = new TGraphErrors(DOMINO_NCELL);
	grDataSubCalib->SetTitle("Data after calibration correction");
	grDataSub = (TGraphErrors *) grDataSubList->At(anaChannel);


	for(ch = 0; ch < DOMINO_NCELL; ch++) {
		grCellCalib = ((TGraphErrors *) grCellCalibList->At(ch));
		grCellCalib->Fit("pol3", "Q");
		TF1 *pol3fit = ((TF1 *) grCellCalib->GetFunction("pol3"));
		grDataSub->GetPoint(ch, x, y);
		chtmp = y - (Double_t)(pol3fit->Eval(y/3.25));
		grDataSubCalib->SetPoint(ch, x, chtmp);
	}

	TCanvas *cGrTest = new TCanvas("grTest", "test per vedere i dati", 1000,1000);

	grDataSubCalib->Draw("APEL");*/


	TString Title = "Charge Distribution per channel";
	gStyle->SetOptFit(111);
	TCanvas *cdistch = new TCanvas("cdistch", Title, 1000, 1000);
	cdistch->Divide(3, 3);
	for (int i = 0; i < DOMINO_NCH; i++) {
		cdistch->cd(i + 1);
		TH1 *dhist = (TH1 *) DistChList->At(i);
		dhist->DrawCopy();
		dhist->SetLineWidth(1);
		dhist->Fit("gaus", "Q");
		dhist->GetFunction("gaus")->SetLineColor(4);
		dhist->GetFunction("gaus")->SetLineWidth(2);
	}

	TString Title = "Charge Distribution Pedestals Subtracted per channel";
	TCanvas *cdistchsub = new TCanvas("cdistchsub", Title, 1000, 1000);
	cdistchsub->Divide(3, 3);
	for (int i = 0; i < DOMINO_NCH; i++) {
		cdistchsub->cd(i + 1);
		TH1 *dsubhist = (TH1 *) DistChSubList->At(i);
		dsubhist->DrawCopy();
		dsubhist->SetLineWidth(1);
		dsubhist->Fit("gaus", "Q");
		dsubhist->GetFunction("gaus")->SetLineColor(4);
		dsubhist->GetFunction("gaus")->SetLineWidth(2);
	}

	TString Title = "Charge Distribution Pedestals and Ch0 Subtracted per channel";
	TCanvas *cdistch0sub = new TCanvas("cdistch0sub", Title, 1000, 1000);
	cdistch0sub->Divide(3, 3);
	for (int i = 0; i < DOMINO_NCH; i++) {
		cdistch0sub->cd(i + 1);
		TH1 *dch0subhist = (TH1 *) DistCh0SubList->At(i);
		dch0subhist->DrawCopy();
		dch0subhist->SetLineWidth(1);
		dch0subhist->Fit("gaus", "Q");
		dch0subhist->GetFunction("gaus")->SetLineColor(4);
		dch0subhist->GetFunction("gaus")->SetLineWidth(2);
	}

	TCanvas *cDataSubTest = new TCanvas("cDataSubTest", "Data after pedestal subtraction", 1000, 1000);
	cDataSubTest->Divide(1,8);
	for (h = 0; h< DOMINO_NCH; h++) {
		grDataSub = (TGraphErrors *) grDataSubList->At(h);
		cDataSubTest->cd(h+1);
		grDataSub->GetYaxis()->SetLabelSize(0.06);
		grDataSub->GetXaxis()->SetLabelSize(0.06);
		grDataSub->Draw("APE");
	}

	TCanvas *cDataSubTestCh5 = new TCanvas("cDataSubTestCh5", "Data after pedestal subtraction Ch5", 1200, 800);
	grDataSub = (TGraphErrors *) grDataSubList->At(anaChannel);
	grDataSub->GetYaxis()->SetLabelSize(0.06);
	grDataSub->GetYaxis()->SetTitle("ADC Counts");
	grDataSub->GetXaxis()->SetTitle("Cell");
	grDataSub->GetXaxis()->SetLabelSize(0.06);
	TLine *refval = new TLine(0,350,1024,350);
	refval->SetLineWidth(3);
	refval->SetLineStyle(2);
	refval->SetLineColor(2);
	TLine *i1 = new TLine(121,-50,121,800);
	i1->SetLineStyle(2);
	TLine *i2 = new TLine(291,-50,291,800);
	i2->SetLineStyle(2);
	TLine *i3 = new TLine(461,-50,461,800);
	i3->SetLineStyle(2);
	TLine *i4 = new TLine(632,-50,632,800);
	i4->SetLineStyle(2);
	TLine *i5 = new TLine(803,-50,803,800);
	i5->SetLineStyle(2);
	TLine *i6 = new TLine(975,-50,975,800);
	i6->SetLineStyle(2);
	TLine *ireal1 = new TLine(121+20,600,121+20,800);
	ireal1->SetLineWidth(3);
	ireal1->SetLineColor(4);
	TLine *ireal2 = new TLine(291-20,600,291-20,800);
	ireal2->SetLineWidth(3);
	ireal2->SetLineColor(4);
	TLine *ireal3 = new TLine(461+20,600,461+20,800);
	ireal3->SetLineWidth(3);
	ireal3->SetLineColor(4);
	TLine *ireal4 = new TLine(632-20,600,632-20,800);
	ireal4->SetLineWidth(3);
	ireal4->SetLineColor(4);
	TLine *ireal5 = new TLine(803+20,600,803+20,800);
	ireal5->SetLineWidth(3);
	ireal5->SetLineColor(4);
	TLine *ireal6 = new TLine(975-20,600,975-20,800);
	ireal6->SetLineWidth(3);
	ireal6->SetLineColor(4);
	grDataSub->Draw("APE");
	refval->Draw("SAME");
	i1->Draw("SAME");
	i2->Draw("SAME");
	i3->Draw("SAME");
	i4->Draw("SAME");
	i5->Draw("SAME");
	i6->Draw("SAME");
	ireal1->Draw("SAME");
	ireal2->Draw("SAME");
	ireal3->Draw("SAME");
	ireal4->Draw("SAME");
	ireal5->Draw("SAME");
	ireal6->Draw("SAME");


	TCanvas *cDataTest = new TCanvas("cDataTest", "Raw Data", 1000,1000);
	cDataTest->Divide(1,8);
	for(h = 0; h < DOMINO_NCH; h++) {
		cDataTest->cd(h+1);
		grData = (TGraphErrors *) grDataList->At(h);
		grData->SetMarkerStyle(20);
		grData->SetMarkerSize(0.5);
		grData->Draw("APE");

	}

	// save root file with graph containing channel 5 data after pedestals subtraction.
	/*
	cout << "test" << endl;

	TString OutFile = DataSubFile;
	TFile *f = new TFile(OutFile,"RECREATE");
	int h = anaChannel;
	TString key="DataSubGraph";
	key += h;
	((TGraphErrors*)grDataSubList->At(h))->Write(key);
	f->Close();
	cout << " ---- Write data on file " << endl;
	 */

	// =======================================================//
	// =====================Matteo's Code=====================//
	// =======================================================//
	/*
	Int_t cht, incCht, decCht, xflag, nPeriods, iMax, iMin;
	Double_t xdiff, incDiff, decDiff, incDiffTemp, decDiffTemp, incXDiff, decXDiff;
	Double_t fitMax, fitMin, fitPeriod, chisquare;
	Double_t DominoXval[DOMINO_NCELL];
	Double_t DominoYval[DOMINO_NCELL];
	Double_t FitXval[DOMINO_NCELL];
	Double_t FitYval[DOMINO_NCELL];


        // opens grDataSub.root

        TString FileName = DataSubFile;
        TGraphErrors *grDataSub;
        int h = anaChannel;
        TFile *f = new TFile(FileName);
        TString key = "DataSubGraph";
        key += h;
        grDataSub = (TGraphErrors *) f->Get(key);
        f->Close();


	// Create a new graph with channel 5 data
	TGraphErrors *grDataSubAnaCh;
	int h = anaChannel;
	grDataSubAnaCh = (TGraphErrors *) grDataSubList->At(h);

	TGraphErrors *grDataSubFix = grDataSubAnaCh->Clone();
	TGraphErrors *grRes = new TGraphErrors(DOMINO_NCELL);
	TList *grResPeriodList = new TList();



	Double_t xtemp, ytemp, DominoMax, DominoMin;

	for (int ch = 0; ch < DOMINO_NCELL; ch++){
		// get domino-output point and save in array
		grDataSubAnaCh->GetPoint(ch, DominoXval[ch], DominoYval[ch]);
	}

	// find the domino point with max y-value
	iMax = 0;
	for(int ch = 0; ch < DOMINO_NCELL; ch++) {
		if(DominoYval[ch] > DominoYval[iMax]) {
			DominoMax = DominoYval[ch];
			iMax = ch;
		}
	}

	cout << "DominoMax e': " << DominoMax << endl;

	// find the domino point with min y-value
	iMin = 0;
	for (int ch = 0; ch < DOMINO_NCELL; ch++) {
		if(DominoYval[ch] < DominoYval[iMin]) {
			DominoMin = DominoYval[ch];
			iMin = ch;
		}
	}

	cout << "DominoMin e': " << DominoMin << endl;

	// remove points from the graph that will be used for fit
	for (int ch = 0; ch < DOMINO_NCELL; ch++){
		grDataSubFix->GetPoint(ch, xtemp, ytemp);
		if(ytemp > 0.8*DominoMax || ytemp < 0.2*DominoMin)
			grDataSubFix->RemovePoint(ch);
	}


	TF1 *fsin = new TF1("fsin", sigSin, 0., 1024., 4);
	fsin->SetParameters(600., DOMINO_NCELL / 4., 150., 150.);
	fsin->SetParNames("amplitude", "Period", "Phase", "DC-Offset");
	grDataSubFix->Fit("fsin");
	TF1 *fsinFit = grDataSubFix->GetFunction("fsin");
	fsinFit->SetParNames("amplitude", "Period", "Phase", "DC-Offset");
	chisquare = grDataSub->Chisquare(fsinFit);
	cout << "il chi quadro della funzione di fit e' : " << chisquare << endl;

	for (int ch = 0; ch < DOMINO_NCELL; ch++) {
		// get Fit-value and save in array
		FitXval[ch] = DominoXval[ch];
		FitYval[ch] = fsinFit->Eval(FitXval[ch]);
	}

	fitPeriod = fsinFit->GetParameter("Period");
	cout << "il periodo della funzione e': " << fitPeriod << endl;

	nPeriods = (Int_t) (DOMINO_NCELL/fitPeriod);
	cout << "il numero di periodi della funzione e': " << nPeriods << endl;

	fitMax = fsinFit->GetMaximum();
	cout << "il massimo della funzione e': " << fitMax << endl;

	fitMin = fsinFit->GetMinimum();
	cout << "il minimo della funzione e': " << fitMin << endl;




	// computes the y difference between the ch-domino point and the i-fit point
	// and stops when the difference changes sign
	//
	// first and last points are not included in the cicle
	//
	// if the fit point y-value is bigger or smaller than the fit function max*0.8 or min*0.2
	// the point is removed

	for (int ch = 1; ch < DOMINO_NCELL - 1; ch++) {

		if(FitYval[ch] > 0.8*fitMax || FitYval[ch] < 0.2*fitMin) {
			grRes->RemovePoint(ch);
			continue;
		}

		incDiff = DominoYval[ch] - FitYval[ch];
		incDiffTemp = DominoYval[ch] - FitYval[ch + 1];

		decDiff = DominoYval[ch] - FitYval[ch];
		decDiffTemp = DominoYval[ch] - FitYval[ch - 1];

		if(abs(incDiffTemp) < abs(incDiff) || (sign(incDiff) != sign(incDiffTemp) && abs(decDiffTemp) > abs(decDiff))) {
			for (int i = ch; i < DOMINO_NCELL; i++, incDiff = incDiffTemp) {
				incDiffTemp = DominoYval[ch] - FitYval[i];

				if (sign(incDiff) != sign(incDiffTemp)) {
					if(abs(incDiffTemp) < abs(incDiff))
						incCht = i;
					else
						incCht = i - 1;
					break;
				}
			}
			xflag = 1;
		}
		else if(abs(decDiffTemp) < abs(decDiff) || (sign(decDiff) != sign(decDiffTemp) && abs(incDiffTemp) > abs(incDiff))) {
			for (int j = ch; j >= 0 ; j--, decDiff = decDiffTemp) {
				decDiffTemp = DominoYval[ch] - FitYval[j];

				if (sign(decDiff) != sign(decDiffTemp)) {
					if(abs(decDiffTemp) < abs(decDiff))
						decCht = j;
					else
						decCht = j + 1;
					break;
				}
			}
			xflag = -1;
		}

		if(xflag == 1)
			xdiff = FitXval[incCht] - DominoXval[ch];
		else
			xdiff = FitXval[decCht] - DominoXval[ch];

		grRes->SetPoint(ch, (Double_t) ch, xdiff);
	}

	cout << "Draw Time Residuals" << endl;
	TString Title = "Time Residuals";
	TCanvas *timeres = new TCanvas("timeres", Title, 1200, 780);
	grRes->SetMarkerStyle(20);
	grRes->SetMarkerSize(0.3);
	grRes->GetYaxis()->SetLabelSize(0.12);
	grRes->GetXaxis()->SetLabelSize(0.12);
	grRes->Draw("APE");


	// The previous graph is now split in N graphs, where N is the number of fit periods

	// this will be needed to set the function phase
	//
    //    iMax = 0;
	//
    //    for(ch = 0; ch < fitPeriod - 1; ch++) {
    //            if(FitYval[ch] > FitYval[iMax]) iMax = ch;
    //    }

	cout << "il primo massimo ha l'indice : " << iMax << endl;

	for (i = 0; i < nPeriods; i++) {
		TGraphErrors *grResPeriod = new TGraphErrors((Int_t) fitPeriod);
		grResPeriodList->Add(grResPeriod);

		for(ch = i*fitPeriod + 1; ch < fitPeriod + (i*fitPeriod); ch++) {

			if(FitYval[ch] > 0.8*fitMax || FitYval[ch] < 0.2*fitMin) {
				grResPeriod->RemovePoint(ch);
				continue;
			}

			incDiff = DominoYval[ch] - FitYval[ch];
			incDiffTemp = DominoYval[ch] - FitYval[ch + 1];

			decDiff = DominoYval[ch] - FitYval[ch];
			decDiffTemp = DominoYval[ch] - FitYval[ch - 1];

			if(abs(incDiffTemp) < abs(incDiff) || (sign(incDiff) != sign(incDiffTemp) && abs(decDiffTemp) > abs(decDiff))) {
				for (int k = ch; k < k*fitPeriod + fitPeriod; k++, incDiff = incDiffTemp) {
					incDiffTemp = DominoYval[ch] - FitYval[k];

					if (sign(incDiff) != sign(incDiffTemp)) {
						if(abs(incDiffTemp) < abs(incDiff))
							incCht = k;
						else
							incCht = k - 1;
						break;
					}
				}
				xflag = 1;
			}
			else if(abs(decDiffTemp) < abs(decDiff) || (sign(decDiff) != sign(decDiffTemp) && abs(incDiffTemp) > abs(incDiff))) {
				for (int j = ch; j > i*fitPeriod; j--, decDiff = decDiffTemp) {
					decDiffTemp = DominoYval[ch] - FitYval[j];

					if (sign(decDiff) != sign(decDiffTemp)) {
						if(abs(decDiffTemp) < abs(decDiff))
							decCht = j;
						else
							decCht = j + 1;
						break;
					}
				}
				xflag = -1;
			}

			if(xflag == 1)
				xdiff = FitXval[incCht] - DominoXval[ch];
			else
				xdiff = FitXval[decCht] - DominoXval[ch];

			grResPeriod->SetPoint(ch - i*fitPeriod, (Double_t) (ch - i*fitPeriod), xdiff);
		}
	}

	TCanvas *timeresperiod = new TCanvas("timeresperiod", "Time Residuals Period", 1200, 780);
	for(i = 0; i < nPeriods; i++) {
		grResPeriod = ((TGraphErrors *) grResPeriodList->At(i));
		grResPeriod->SetMarkerStyle(20);
		grResPeriod->SetMarkerSize(0.3);
		grResPeriod->GetYaxis()->SetLabelSize(0.12);
		grResPeriod->GetXaxis()->SetLabelSize(0.12);
		grResPeriod->Draw("APEsame");
	}

	cout << "Draw Data - Pedestals Subtracted" << endl;
	TString Title = "Average Charge - Pedestal subtracted";
	TCanvas *csubdata = new TCanvas("csubdata", Title, 1200, 780);
	grDataSubAnaCh->SetMarkerStyle(20);
	grDataSubAnaCh->SetMarkerSize(0.3);
	grDataSubAnaCh->GetYaxis()->SetLabelSize(0.12);
	grDataSubAnaCh->GetXaxis()->SetLabelSize(0.12);
	grDataSubAnaCh->Draw("APE");
	fsinFit->Draw("same");
	 */
	// draw extra graphs
	if (DrawExtraGraphs == 1) {
		cout << " ----- DRAW Results ------" << endl;
		//================ DRAW Results ==================

		TCanvas *c = new TCanvas("ctmp", "test", 800, 800);
		c->Divide(3, 3);
		for (int pad = 1; pad < 10; pad++) {
			c->cd(pad);
			((TH1 *) hCellList->At(pad * 512 + 219))->DrawCopy();
			hCellSub = (TH1F *) hCellSubList->At(pad * 512 + 219);
			hCellSub->SetLineColor(2);
			hCellSub->DrawCopy("same");
		}

		cout << "Draw RMS distributions" << endl;
		TString Title = "RMS distributions per channel";
		TCanvas *c4 = new TCanvas("c4", Title, 700, 700);
		c4->Divide(3, 3);
		for (int i = 0; i < DOMINO_NCH; i++) {
			c4->cd(i + 2);
			hRMSdist = (TH1F *) hRMSList->At(i);
			hRMSFitdist = (TH1F *) hRMSFitList->At(i);
			hRMSFitdist->SetLineColor(2);
			hRMSFitdist->DrawCopy();
			hRMSdist->DrawCopy("same");
		}


		TList *grDataCh0SubList = new TList();
		TGraphErrors *grDataCh0Sub;
		for(h = 0; h< DOMINO_NCELL; h++) {
			grDataCh0Sub = new TGraphErrors(DOMINO_NCELL);
			grDataCh0SubList->Add(grDataCh0Sub);
		}

		TGraphErrors *grDataSubCh0 = (TGraphErrors *) grDataSubList->At(6);
		for(h = 0; h < DOMINO_NCH; h++) {
			grDataSub = (TGraphErrors *) grDataSubList->At(h);
			grDataCh0Sub = (TGraphErrors *) grDataCh0SubList->At(h);
			for(ch = 0; ch < DOMINO_NCELL; ch++) {
				grDataSubCh0->GetPoint(ch, x1, y1);
				grDataSub->GetPoint(ch, x2, y2);
				grDataCh0Sub->SetPoint(ch, x1 , y2 - y1);
			}
		}

		TCanvas *cDataCH0Sub = new TCanvas("cDataCH0Sub","cDataCH0Sub", 1000,1000);
		cDataCH0Sub->Divide(1,8);
		for(h = 0; h < DOMINO_NCH; h++) {
			cDataCH0Sub->cd(h+1);
			grDataCh0Sub = (TGraphErrors *) grDataCh0SubList->At(h);
			grDataCh0Sub->GetYaxis()->SetLabelSize(0.12);
			grDataCh0Sub->GetXaxis()->SetLabelSize(0.12);
			grDataCh0Sub->Draw("APEL");
		}



		cout << "Draw Data - Pedestals Subtracted" << endl;
		TString Title = "Average Charge - Pedestal subtracted";
		TCanvas *csubdata = new TCanvas("csubdata", Title, 1000, 1000);
		csubdata->Divide(3,3);

		for(h = 0; h < DOMINO_NCH; h++) {
			csubdata->cd(h+1);
			TString title = "DataSub channel ";
			title += h;
			TH1F *hCellDataSub = new TH1F(title, title, 100, -20, 20);
			grDataSub = (TGraphErrors *) grDataSubList->At(h);
			for(ch = 0; ch < DOMINO_NCELL; ch++) {
				grDataSub->GetPoint(ch, x, y);
				hCellDataSub->Fill(y);
			}
			hCellDataSub->Fit("gaus", "Q");
			hCellDataSub->GetXaxis()->SetTitle("ADC Counts");
			hCellDataSub->GetFunction("gaus")->SetLineColor(4);
			hCellDataSub->DrawCopy();
		}

		cout << "breakpoint" << endl;
		TCanvas *csubdata2 = new TCanvas("csubdata2", "DataSub for every channel", 1000, 1000);
		TString title = "DataSub every channel ";
		TH1F *hCellChDataSubTot = new TH1F(title, title, 100, -20, 20);
		for(h = 0; h < DOMINO_NCH; h++) {
			grDataSub = (TGraphErrors *) grDataSubList->At(h);
			for(ch = 0; ch < DOMINO_NCELL; ch++) {
				grDataSub->GetPoint(ch, x, y);
				hCellChDataSubTot->Fill(y);
			}
			hCellChDataSubTot->Fit("gaus", "Q");
			hCellChDataSubTot->GetXaxis()->SetTitle("ADC Counts");
			hCellChDataSubTot->GetFunction("gaus")->SetLineColor(4);
			hCellChDataSubTot->Draw();
		}

		cout << "Draw Pedestals" << endl;
		TString Title = "Pedestals";
		TCanvas *c2 = new TCanvas("c2", Title, 1050, 780);
		c2->SetBorderMode(0);
		c2->SetBorderSize(0.);
		c2->Divide(1, 8);
		//    gStyle->SetCanvasBorderMode(0.);
		//    gStyle->SetCanvasBorderSize(0.);
		Double_t x, y;
		for (int h = 0; h < DOMINO_NCH; h++) {
			c2->cd(h + 1);
			grPed = ((TGraphErrors *) grPedList->At(h));
			grPed->SetMarkerStyle(20);
			grPed->SetMarkerSize(0.5);
			grPed->GetYaxis()->SetLabelSize(0.12);
			grPed->GetXaxis()->SetLabelSize(0.12);
			//        cout <<  " err:" << grPed->GetErrorY(102) << " " ;
			//        cout << x << "--" << y << endl;
			grPed->Draw("APE");
		}

		cout << "Draw Data - Average charge" << endl;
		TString Title = "Average_Charge";
		TCanvas *cdata = new TCanvas("cdata", Title, 1050, 780);
		cdata->Divide(1, 8);
		Double_t x, y;
		for (int h = 0; h < DOMINO_NCH; h++) {
			cdata->cd(h + 1);
			grData = ((TGraphErrors *) grDataList->At(h));
			grData->SetMarkerStyle(20);
			grData->SetMarkerSize(0.3);
			grData->GetYaxis()->SetLabelSize(0.12);
			grData->GetXaxis()->SetLabelSize(0.12);
			grData->GetPoint(10, x, y);
			//        cout << x << "-" << y << endl;
			grData->Draw("APE");
		}

		cout << "Draw Data - Pedestals Subtracted" << endl;
		TString Title = "Average Charge - Pedestal subtracted";
		TCanvas *csubdata = new TCanvas("csubdata", Title, 1200, 780);
		csubdata->Divide(1, 8);
		TF1 *fsin = new TF1("fsin", sigSin, 0., 1024., 4);
		TH1D *resDist = new TH1D("resDist", "Residuals Signal", 100, -100., 100.);

		cout << "Draw Data - Pedestals Subtracted" << endl;
		TString Title = "Residuals";
		TCanvas *residuals = new TCanvas("residuals", Title, 1200, 780);
		resDist->DrawCopy();

	}

	fclose(fdata);

	hCellList->Delete();
	hCellSubList->Delete();
	hRMSList->Delete();
	hRMSFitList->Delete();
}
예제 #3
0
파일: hserv.C 프로젝트: Y--/root
void hserv() {
   // Open a server socket looking for connections on a named service or
   // on a specified port.
   //TServerSocket *ss = new TServerSocket("rootserv", kTRUE);
   TServerSocket *ss = new TServerSocket(9090, kTRUE);

   // Accept a connection and return a full-duplex communication socket.
   TSocket *s0 = ss->Accept();
   TSocket *s1 = ss->Accept();

   // tell the clients to start
   s0->Send("go 0");
   s1->Send("go 1");

   // Close the server socket (unless we will use it later to wait for
   // another connection).
   ss->Close();

   // Check some options of socket 0.
   int val;
   s0->GetOption(kSendBuffer, val);
   printf("sendbuffer size: %d\n", val);
   s0->GetOption(kRecvBuffer, val);
   printf("recvbuffer size: %d\n", val);

   // Get the remote addresses (informational only).
   TInetAddress adr = s0->GetInetAddress();
   adr.Print();
   adr = s1->GetInetAddress();
   adr.Print();

   // Create canvas and pads to display the histograms
   TCanvas *c1 = new TCanvas("c1","The Ntuple canvas",200,10,700,780);
   TPad *pad1 = new TPad("pad1","This is pad1",0.02,0.52,0.98,0.98,21);
   TPad *pad2 = new TPad("pad2","This is pad2",0.02,0.02,0.98,0.48,21);
   pad1->Draw();
   pad2->Draw();

   TMonitor *mon = new TMonitor;

   mon->Add(s0);
   mon->Add(s1);

   while (1) {
      TMessage *mess;
      TSocket  *s;

      s = mon->Select();

      s->Recv(mess);

      if (mess->What() == kMESS_STRING) {
         char str[64];
         mess->ReadString(str, 64);
         printf("Client %d: %s\n", s==s0 ? 0 : 1, str);
         mon->Remove(s);
         if (mon->GetActive() == 0) {
            printf("No more active clients... stopping\n");
            break;
         }
      } else if (mess->What() == kMESS_OBJECT) {
         //printf("got object of class: %s\n", mess->GetClass()->GetName());
         TH1 *h = (TH1 *)mess->ReadObject(mess->GetClass());
         if (h) {
            if (s == s0)
               pad1->cd();
            else
               pad2->cd();
            h->Print();
            h->DrawCopy();  //draw a copy of the histogram, not the histo itself
            c1->Modified();
            c1->Update();
            delete h;       // delete histogram
         }
      } else {
         printf("*** Unexpected message ***\n");
      }

      delete mess;
   }

   printf("Client 0: bytes recv = %d, bytes sent = %d\n", s0->GetBytesRecv(),
          s0->GetBytesSent());
   printf("Client 1: bytes recv = %d, bytes sent = %d\n", s1->GetBytesRecv(),
          s1->GetBytesSent());

   // Close the socket.
   s0->Close();
   s1->Close();
}
예제 #4
0
파일: QA.C 프로젝트: ktf/AliPhysics
void QAtracklets(const Char_t *fdata, const Char_t *fmc)
{

  style();
  
  TFile *fdtin = TFile::Open(fdata);
  TList *ldtin = (TList *)fdtin->Get("clist");
  TH2 *hdtin = (TH2 *)ldtin->FindObject("etaphiTracklets");
  TH1 *pdtin = (TH1 *)hdtin->ProjectionY("pdtin_tracklets");
  pdtin->SetMarkerStyle(20);
  pdtin->SetMarkerSize(1.);
  pdtin->SetMarkerColor(kAzure-3);
  hdtin->Scale(1. / hdtin->GetEntries());
  pdtin->Scale(1. / hdtin->GetEntries());
  
  TFile *fmcin = TFile::Open(fmc);
  TList *lmcin = (TList *)fmcin->Get("clist");

  if(!lmcin) {
      std::cout << "NOLIST" << std::endl;

  }
  lmcin->ls();
  TH2 *hmcin = (TH2 *)lmcin->FindObject("etaphiTracklets");
  if(!hmcin) {
    std::cout << "NO H!! etaphiTracklets" << std::endl;
    
  }
  TH1 *pmcin = (TH1 *)hmcin->ProjectionY("pmcin_tracklets");
  pmcin->SetLineColor(kRed+1);
  pmcin->SetFillStyle(1001);
  pmcin->SetFillColorAlpha(kRed+1, 0.1);
  hmcin->Scale(1. / hmcin->GetEntries());
  pmcin->Scale(1. / hmcin->GetEntries());
  

  /*  
  pdtin->Scale(pmcin->Integral(pmcin->FindBin(0. + 0.001),
			       pmcin->FindBin(1. - 0.001))
	       / pdtin->Integral(pdtin->FindBin(0. + 0.001),
				 pdtin->FindBin(1. - 0.001)));
  */  
  
  TCanvas *cData = new TCanvas("cTrackletData", "cTrackletData", 800, 800);
  //  cData->SetLogz();
  TH1 * hfr = cData->DrawFrame(-2.5, 0., 2.5, 2. * TMath::Pi());
  hfr->SetTitle(";#eta;#varphi");
  hdtin->Draw("same,col");
  cData->SaveAs(canvasPrefix+"trackletData.pdf");

  TCanvas *cMC = new TCanvas("cTrackletMC", "cTrackletMC", 800, 800);
  //  cMC->SetLogz();
  hfr = cMC->DrawFrame(-2.5, 0., 2.5, 2. * TMath::Pi());
  hfr->SetTitle(";#eta;#varphi");
  hmcin->Draw("same,col");
  cMC->SaveAs(canvasPrefix+"trackletMC.pdf");
  
  TCanvas *cPhi = new TCanvas("cTrackletPhi", "cTrackletPhi", 800, 800);
  //  cPhi->SetLogy();
  hfr = cPhi->DrawFrame(0., 0., 2. * TMath::Pi(), 0.01);
  hfr->SetTitle(";#varphi;");
  pdtin->DrawCopy("same");
  pmcin->DrawCopy("same,histo");
  TLegend *legend = new TLegend(0.20, 0.18+0.63, 0.50, 0.30+0.63);
  legend->SetFillColor(0);
  legend->SetBorderSize(0);
  legend->SetTextFont(42);
  legend->SetTextSize(0.04);
  legend->AddEntry(pdtin, "data", "pl");
  legend->AddEntry(pmcin, "Monte Carlo", "l");
  legend->Draw("same");
  cPhi->SaveAs(canvasPrefix+"trackletPhi.pdf");
  
  TCanvas *cPhir = new TCanvas("cTrackletPhir", "cTrackletPhir", 800, 800);
  //  cPhi->SetLogy();
  hfr = cPhir->DrawFrame(0., 0.5, 2. * TMath::Pi(), 1.5);
  hfr->SetTitle(";#varphi;data / Monte Carlo");
  pdtin->Divide(pmcin);
  pdtin->Draw("same");
  cPhir->SaveAs(canvasPrefix+"trackletPhir.pdf");

  
  
}
예제 #5
0
//______________________________________________________________________________
void PIDEnergy()
{
    // Main method.

    Char_t tmp[256];

    // load CaLib
    gSystem->Load("libCaLib.so");

    // general configuration
    const Char_t* data = "Data.PID.E0";
    const Char_t* hName = "CaLib_PID_Energy_Proton_PID_Energy";

    // configuration (December 2007)
    //const Char_t calibration[] = "LD2_Dec_07";
    //const Char_t filePat[] = "/usr/puma_scratch0/werthm/A2/Dec_07/AR/out/ARHistograms_CB_RUN.root";
    //const Char_t mcFile[] = "/usr/panther_scratch0/werthm/A2/Dec_07/MC/calibration/all.root";

    // configuration (February 2009)
    //const Char_t calibration[] = "LD2_Feb_09";
    //const Char_t filePat[] = "/usr/puma_scratch0/werthm/A2/Feb_09/AR/out/ARHistograms_CB_RUN.root";
    //const Char_t mcFile[] = "/usr/panther_scratch0/werthm/A2/Feb_09/MC/calibration/all.root";

    // configuration (May 2009)
    const Char_t calibration[] = "LD2_May_09";
    const Char_t filePat[] = "/usr/puma_scratch0/werthm/A2/May_09/AR/out/ARHistograms_CB_RUN.root";
    const Char_t mcFile[] = "/usr/panther_scratch0/werthm/A2/May_09/MC/calibration/all.root";

    // get number of sets
    Int_t nSets = TCMySQLManager::GetManager()->GetNsets(data, calibration);

    // create canvas
    Int_t n = TMath::Sqrt(nSets);
    TCanvas* cOverview = new TCanvas("c", "c", 1200, 900);
    cOverview->Divide(n, nSets / n + 1);

    // create arrays
    Double_t* pos = new Double_t[nSets+1];
    Double_t* fwhm = new Double_t[nSets+1];

    // total sum histogram
    TH1* hTot = 0;

    // load MC histo
    TFile* fMC = new TFile(mcFile);
    TH2* hMC2 = (TH2*) fMC->Get(hName);
    TH1* hMC = hMC2->ProjectionX("mc");
    hMC->SetLineColor(kBlue);

    // loop over sets
    for (Int_t i = 0; i < nSets; i++)
    {
        // create file manager
        TCFileManager m(data, calibration, 1, &i, filePat);

        // get histo
        TH2* h2 = (TH2*) m.GetHistogram(hName);

        // skip empty histo
        if (!h2) continue;

        // project histo
        sprintf(tmp, "Proj_%d", i);
        TH1* h = (TH1*) h2->ProjectionX(tmp);
        //TH1* h = (TH1*) h2->ProjectionX(tmp, 9, 9);
        //h->Rebin(4);

        // add to total histogram
        if (!hTot) hTot = (TH1*) h->Clone();
        else hTot->Add(h);

        // fit histo
        cOverview->cd(i+1);
        h->SetLineColor(kBlack);
        h->Draw();
        hMC->Scale(h->GetMaximum()/hMC->GetMaximum());
        hMC->DrawCopy("same");
    }
}
예제 #6
0
파일: h1draw.C 프로젝트: davidlt/root
void h1draw()
{
   TString dir = gROOT->GetTutorialDir();
   dir.Append("/hsimple.C");
   dir.ReplaceAll("/./","/");
   if (gBenchmark->GetBench("hsimple") < 0) gInterpreter->LoadMacro(dir.Data());
   TFile *example = (TFile*)gROOT->ProcessLineFast("hsimple(1)");
   if (!example) return;

   example->ls();
   TH1 *hpx = (TH1*)example->Get("hpx");

   TCanvas *c1 = new TCanvas("c1","Histogram Drawing Options",200,10,700,900);
   TPad *pad1 = new TPad("pad1",
      "The pad with the function",0.03,0.62,0.50,0.92);
   TPad *pad2 = new TPad("pad2",
      "The pad with the histogram",0.51,0.62,0.98,0.92);
   TPad *pad3 = new TPad("pad3",
      "The pad with the histogram",0.03,0.02,0.97,0.57);
   pad1->Draw();
   pad2->Draw();
   pad3->Draw();

   // Draw a global picture title
   TPaveLabel *title = new TPaveLabel(0.1,0.94,0.9,0.98,
                    "Drawing options for one dimensional histograms");
   title->SetTextFont(52);
   title->Draw();

   // Draw histogram hpx in first pad with the default option.
   pad1->cd();
   pad1->GetFrame()->SetFillColor(18);
   hpx->SetFillColor(45);
   hpx->DrawCopy();
   TPaveLabel *label1 = new TPaveLabel(-3.5,700,-1,800,"Default option");
   label1->Draw();

   // Draw hpx as a lego. Clicking on the lego area will show
   // a "transparent cube" to guide you rotating the lego in real time.
   pad2->cd();
   hpx->DrawCopy("lego1");
   TPaveLabel *label2 = new TPaveLabel(-0.72,0.74,-0.22,0.88,"option Lego1");
   label2->Draw();
   TPaveLabel *label2a = new TPaveLabel(-0.93,-1.08,0.25,-0.92,
      "Click on lego to rotate");
   label2a->Draw();

   // Draw hpx with its errors and a marker.
   pad3->cd();
   pad3->SetGridx();
   pad3->SetGridy();
   hpx->SetMarkerStyle(21);
   hpx->Draw("e1p");
   TPaveLabel *label3 = new TPaveLabel(2,600,3.5,650,"option e1p");
   label3->Draw();

   // The following illustrates how to add comments using a PaveText.
   // Attributes of text/lines/boxes added to a PaveText can be modified.
   // The AddText function returns a pointer to the added object.
   TPaveText *pave = new TPaveText(-3.78,500,-1.2,750);
   TText *t1=pave->AddText("You can move");
   t1->SetTextColor(4);
   t1->SetTextSize(0.05);
   pave->AddText("Title and Stats pads");
   pave->AddText("X and Y axis");
   pave->AddText("You can modify bin contents");
   pave->Draw();
   c1->Update();
}
void h1draw()
{
   // We attach (or generate) the ROOT file in $ROOTSYS/tutorials/hsimple.root 
   // or $PWD/hsimple.root
   // We draw one histogram in different formats
   //Author: Rene Brun
   TFile *example = TFile::Open("hsimple.root");
   if (!example) return;
   
   example->ls();
   TH1 *hpx = (TH1*)example->Get("hpx");
   
   TCanvas *c1 = new TCanvas("c1","Histogram Drawing Options",200,10,700,900);
   TPad *pad1 = new TPad("pad1",
      "The pad with the function",0.03,0.62,0.50,0.92,21);
   TPad *pad2 = new TPad("pad2",
      "The pad with the histogram",0.51,0.62,0.98,0.92,21);
   TPad *pad3 = new TPad("pad3",
      "The pad with the histogram",0.03,0.02,0.97,0.57,21);
   pad1->Draw();
   pad2->Draw();
   pad3->Draw();

   // Draw a global picture title
   TPaveLabel *title = new TPaveLabel(0.1,0.94,0.9,0.98,
                    "Drawing options for one dimensional histograms");
   title->SetFillColor(16);
   title->SetTextFont(52);
   title->Draw();

   // Draw histogram hpx in first pad with the default option.
   pad1->cd();
   pad1->GetFrame()->SetFillColor(18);
   hpx->SetFillColor(45);
   hpx->DrawCopy();
   TPaveLabel *label1 = new TPaveLabel(-3.5,700,-1,800,"Default option");
   label1->SetFillColor(42);
   label1->Draw();

   // Draw hpx as a lego. Clicking on the lego area will show
   // a "transparent cube" to guide you rotating the lego in real time.
   pad2->cd();
   hpx->DrawCopy("lego1");
   TPaveLabel *label2 = new TPaveLabel(-0.72,0.74,-0.22,0.88,"option Lego1");
   label2->SetFillColor(42);
   label2->Draw();
   TPaveLabel *label2a = new TPaveLabel(-0.93,-1.08,0.25,-0.92,
      "Click on lego to rotate");
   label2a->SetFillColor(42);
   label2a->Draw();

   // Draw hpx with its errors and a marker.
   pad3->cd();
   pad3->SetGridx();
   pad3->SetGridy();
   pad3->GetFrame()->SetFillColor(18);
   hpx->SetMarkerStyle(21);
   hpx->Draw("e1p");
   TPaveLabel *label3 = new TPaveLabel(2,600,3.5,650,"option e1p");
   label3->SetFillColor(42);
   label3->Draw();

   // The following illustrates how to add comments using a PaveText.
   // Attributes of text/lines/boxes added to a PaveText can be modified.
   // The AddText function returns a pointer to the added object.
   TPaveText *pave = new TPaveText(-3.78,500,-1.2,750);
   pave->SetFillColor(42);
   TText *t1=pave->AddText("You can move");
   t1->SetTextColor(4);
   t1->SetTextSize(0.05);
   pave->AddText("Title and Stats pads");
   pave->AddText("X and Y axis");
   pave->AddText("You can modify bin contents");
   pave->Draw();
   c1->Update();
}
예제 #8
0
void CalibrateData(Int_t nevt,Int_t startEv = 1, char *PedFile = "drs4_20100311_t_ped.root") {

	// create progress bar
	TGHProgressBar *gProgress = ProgressBar("Calibrazione dati");

	// Redefine DOMINO Depth in ADC counts
	const Float_t DominoDepthADC = pow(2, DOMINO_DEPTH);

	// create list of histograms for pedestals
	TList *grPedList = new TList();
	TGraphErrors *grPed;

	// create list of histograms for channels
	TList *hCellCalibList = new TList();
	TH1F *hCellCalib;

	TList *grCellCalibList = new TList();
	TGraphErrors *grCellCalib;

	int mV[NCALIBFILES] = {-500,-400,-300,-200,-100,0,100,200,300,400,500};

	/*for (int iFile = 0; iFile < NCALIBFILES; iFile++) {
		mV[iFile] = mVStart;
		mVStart += mVStep;
	}*/

	char *calibrationFile;
	char *calibrationFileArray[NCALIBFILES];
	calibrationFileArray[0] = "drs4_1000ev_dcm500mv.dat";
	calibrationFileArray[1] = "drs4_1000ev_dcm400mv.dat";
	calibrationFileArray[2] = "drs4_1000ev_dcm300mv.dat";
	calibrationFileArray[3] = "drs4_1000ev_dcm200mv.dat";
	calibrationFileArray[4] = "drs4_1000ev_dcm100mv.dat";
	calibrationFileArray[5] = "drs4_1000ev_dc1mv.dat";
	calibrationFileArray[6] = "drs4_1000ev_dc100mv.dat";
	calibrationFileArray[7] = "drs4_1000ev_dc200mv.dat";
	calibrationFileArray[8] = "drs4_1000ev_dc300mv.dat";
	calibrationFileArray[9] = "drs4_1000ev_dc400mv.dat";
	calibrationFileArray[10] = "drs4_1000ev_dc500mv.dat";

	for (int iFile = 0; iFile < NCALIBFILES; iFile++) {
		for (int ch = 0; ch < DOMINO_NCELL; ch++) {
			//
			TString title = "Calibration signal file:";
			title += iFile;
			title += " ch:";
			title += ch;
			hCellCalib = new TH1F(title,title, DominoDepthADC, -DominoDepthADC, DominoDepthADC);
			hCellCalibList->Add(hCellCalib);
		}
	}


	for (int ch = 0; ch < DOMINO_NCELL; ch++) {
		grCellCalib = new TGraphErrors(NCALIBFILES);
		grCellCalibList->Add(grCellCalib);
	}


	// calculate or read pedestals from file
	grPedList = OpenPedestals(PedFile);
	grPedData = (TGraphErrors *) grPedList->At(anaChannel);
	grPedTrig = (TGraphErrors *) grPedList->At(trigChannel);

	// create gauss function
	TF1 *fgauss = new TF1("fgauss", "TMath::Gaus(x,[0],[1],0)", -DOMINO_NCELL, DOMINO_NCELL);
	fgauss->SetParameter(0,0.);
	fgauss->SetParameter(1,1.);
	fgauss->SetParLimits(0, 0., DominoDepthADC);
	fgauss->SetParLimits(1, 0.1, 20.);

	TCanvas *ctest = new TCanvas("ChannelTest", "ChannelTest", 800, 600);
	ctest->Divide(3, 4);

	gProgress->Reset();
	gProgress->SetMax(nevt*NCALIBFILES);

	gSystem->ProcessEvents();


	for (int iFile = 0; iFile < NCALIBFILES; iFile++) {

		// open file

		calibrationFile = calibrationFileArray[iFile];
		FILE *fdata = OpenDataFile(calibrationFile);
		struct channel_struct *p;
		struct channel_struct *dep;

		Double_t refval=0, reftmp = 0;
		Double_t PedVal, itmp;

		// Count number of events in data file
		int nevtDataMax = 0;
		while (!feof(fdata)) {
			fread((void *) &event_data, 1, sizeof(event_data), fdata);
			nevtDataMax++;
		}
		printf("nevtDataMax: %d\n", nevtDataMax);

		if (nevt > (nevtDataMax - startEv) || nevt == 0)
			nevt = nevtDataMax - startEv;
		cout << endl << "==>> Processing " << nevt << " events from file "
				<< calibrationFile << endl;

		rewind(fdata);

		for (int j = 0; j < 1; j++) {
			fread((void *) &event_data, 1, sizeof(event_data), fdata);
			p = (struct channel_struct *) &event_data.ch[0]; // read bunch of data
			p += anaChannel;
			for (ch = 0; ch < DOMINO_NCELL; ch++) {
				grPedData->GetPoint(ch, itmp, PedVal);
				reftmp = TMath::Abs((Double_t)(p->data[ch])-PedVal);
				if (reftmp > 0.8* refval)
					refval = 0.2*reftmp+0.8*refval;
				//					cout << ch << " " <<p->data[ch] << " " <<reftmp << " " << refval <<endl ;
			}
		}
		cout << "refval="<< refval<<endl;
		rewind(fdata);

		Int_t ievt = 1;
		// go to first event (startEv)
		while (ievt < startEv) {
			fread((void *) &event_data, 1, sizeof(event_data), fdata);
			if (feof(fdata))
				break;
			ievt++;
		}

		ievt = 1;
		Int_t iTrig = 0;
		Int_t flagEnd = 0;
		Double_t chtmp, chtrig;
		Double_t ratio;
		Double_t mean, rms;

		// loop on events

		while (ievt <= nevt && !flagEnd) {

			fread((void *) &event_data, 1, sizeof(event_data), fdata);
			if (feof(fdata))
				flagEnd = 1;

			p = (struct channel_struct *) &event_data.ch[0]; // read bunch of data
			dep = (struct channel_struct *) &event_data.ch[1]; // read bunch of data

			//now anaChannel analysis

			p += anaChannel;

			// read data, subtract pedestals values and fill hCellCalibList.

			for (int ch = 0; ch < DOMINO_NCELL; ch++) {
				// Read pedestal value for this cell
				grPedData->GetPoint(ch, itmp, PedVal);
				chtmp = (Double_t)(p->data[ch]); // data value
				chtmp = chtmp - PedVal;
				//if (TMath::Abs(chtmp) > 0.9 * refval)
				((TH1 *) hCellCalibList->At(iFile*DOMINO_NCELL+ch))->Fill(chtmp);
				//cout << ch << " " << iFile << " " << chtmp << endl;
			}

			gProgress->Increment(1);
			gSystem->DispatchOneEvent(kTRUE);
			ievt++; // next event
		}


		TH1 *hCellTmp;
		for(ch = 0; ch < DOMINO_NCELL;ch++) {
			hCellTmp = ((TH1 *) hCellCalibList->At(iFile*DOMINO_NCELL+ch));
			//hCellTmp->Fit("gaus", "Q");
			//mean = (hCellTmp->GetFunction("gaus"))->GetParameter(1);
			//rms = (hCellTmp->GetFunction("gaus"))->GetParameter(2);
			mean = hCellTmp->GetMean();
			rms = hCellTmp->GetRMS();
			((TGraphErrors *) (grCellCalibList->At(ch)))->SetPoint(iFile, (Double_t) mV[iFile], mean);
			((TGraphErrors *) (grCellCalibList->At(ch)))->SetPointError(iFile, 0., rms);
		}


		ctest->cd(iFile + 1);
		hCellTmp = ((TH1 *) hCellCalibList->At(567 + iFile*DOMINO_NCELL));
		hCellTmp->Fit("gaus","Q");
		hCellTmp->DrawCopy();
	}

	TString OutFile = "CalibrationDataNew";
	OutFile += nevt;
	OutFile += "events.root";
	TFile *f = new TFile(OutFile, "RECREATE");
	for (int ch = 0; ch < DOMINO_NCELL; ch++) {
		TString key = "CalibDataCell";
		key += ch;
		((TGraphErrors*) grCellCalibList->At(ch))->Write(key);
	}
	f->Close();

	hCellCalibList->Delete();

	((TGMainFrame *) gProgress->GetParent())->CloseWindow();
	fclose(fdata);
}
void roadsStubsClean5oo6_3 (int savePlots=0, const int nLayers=6, bool use95coverage=0, TString clayerSelect="111111", unsigned bitReduction=0) {

	if (!clayerSelect.IsBin()) {
		cout << "layer selector not a binary integer. Exiting" << endl;
		return;
	}
	if (clayerSelect.Length()!=6) {
		cout << "layer selector length != 6. Specify all the bits, innermost -> outermost <-> LSB -> MSB. Exiting" << endl;
		return;
	}
	bool layerSelect[6];
	cout << "Selecting layers: ";
	for (unsigned ibit=0; ibit<6; ++ibit) {
		layerSelect[ibit]=TString(clayerSelect(ibit)).Atoi();
		cout << layerSelect[ibit] << " " ;
	}
	cout << endl;

	bool isPlottose = false;

	TStyle* style = gStyle;
	style->SetOptStat(1111111);
	style->SetOptStat(0);

	bool isSLHC25=0;

	TString dirPlots("/home/rossin/Dropbox/TT/Work/figures_stubCleaning/OverlapClean_95c_0p8_0p8_0p6_0p8_0p6_0p5/");

//	TString sTree="results_sf1_nz1_tt27_pt2_SingleMuonFlatOneOverPt0p005To0p5_tt27_Sum2M_SL6.root" ;
//	TString sTree="singleMuonNoTest/results_SingleMuonFlatOneOverPt0p005To0p5_tt27NoTest_cfi_py_GEN_SIM_DIGI_L1TrackTrigger_2M.root" ;
//	TString sTree="singleMuNoTest2_2000/results_20150528_SingleMuonFlatOneOverPt0p0005To0p5_tt27NoTest_4M.root" ;
//	TString sTree="singleMuNoTest2_2000/results_20150528_5outOf6_SingleMuonFlatOneOverPt0p0005To0p5_tt27NoTest_4M.root" ;
//	TString sTree="singleMuNoTest2_2000/roads_sf1_nz1_tt27_pt2_SingleMuonFlatOneOverPt0p0005To0p5_tt27NoTest_4M_SLHC25.root"; isSLHC25=1; // 6/6
//	TString sTree="singleMuNoTest2_2000/roads_5outOf6_sf1_nz1_tt27_pt2_SingleMuonFlatOneOverPt0p0005To0p5_tt27NoTest_4M_SLHC25.root"; isSLHC25=1; // 5/6

//	TString sTree="SingleMuonTest_tt27_PU0_140_20150408_SLHC25p3_NewPatterns/roads_sf1_nz1_tt27_pt2_6oo6_SingleMuonTest_tt27_PU0_20150408_SLHC25p3_newBank_10M.root"; isSLHC25=1; TString pName("SingleMu_PU0_6oo6");// 6/6
//	TString sTree="SingleMuonTest_tt27_PU0_140_20150408_SLHC25p3_NewPatterns/roads_sf1_nz1_tt27_pt2_5oo6_SingleMuonTest_tt27_PU0_20150408_SLHC25p3_newBank_10M.root"; isSLHC25=1; TString pName("SingleMu_PU0_5or6oo6");// 5/6

//	TString sTree="SingleMuonTest_tt27_PU0_140_20150408_SLHC25p3_NewPatterns/roads_sf1_nz1_tt27_pt2_6oo6_SingleMuonTest_tt27_PU140_20150408_SLHC25p3_newBank_10M.root"; isSLHC25=1; TString pName("SingleMu_PU140_6oo6");// 5/6
//	TString sTree="SingleMuonTest_tt27_PU0_140_20150408_SLHC25p3_NewPatterns/roads_sf1_nz1_tt27_pt2_5oo6_SingleMuonTest_tt27_PU140_20150408_SLHC25p3_newBank_10M.root"; isSLHC25=1; TString pName("SingleMu_PU140_5or6oo6");// 5/6
//	TString sTree="Neutrino_tt27_PU140_20150408_SLHC25p3_NewPatterns/roads_sf1_nz1_tt27_pt2_6oo6_Neutrino_PU140_20150408_SLHC25p3_newBank_10M.root"; isSLHC25=1; TString pName("Neutrino_PU140_6oo6");// 6/6
//	TString sTree="Neutrino_tt27_PU140_20150408_SLHC25p3_NewPatterns/roads_sf1_nz1_tt27_pt2_5or6oo6_Neutrino_PU140_20150408_SLHC25p3_newBank_10M.root"; isSLHC25=1; TString pName("Neutrino_PU140_5or6oo6");// 5/6
//	TString sTree="TTbarTTbar_tt27_PU140_20150408_SLHC25p3_NewPatterns/roads_sf1_nz1_tt27_pt2_6oo6_TTbarTTbar_tt27_PU140_20150408_SLHC25p3_newBank_10M.root"; isSLHC25=1; TString pName("4Tops_PU140_6oo6");// 6/6
//	TString sTree="TTbarTTbar_tt27_PU140_20150408_SLHC25p3_NewPatterns/roads_sf1_nz1_tt27_pt2_5oo6_TTbarTTbar_tt27_PU140_20150408_SLHC25p3_newBank_10M.root"; isSLHC25=1; TString pName("4Tops_PU140_5or6oo6");// 5/6

//	TString sTree="SingleMuonTest_tt27_PU0_140_20150408_SLHC25p3_NewPatterns/roads_sf1_nz1_tt27_pt2_5oo6_SingleMuonTest_tt27_PU0_20150408_SLHC25p3_newBank_10M.root"; isSLHC25=1; TString pName("SingleMu_PU0_sf1_nz1_pt2_5or6oo6");// 5/6
//	TString sTree="SingleMuonTest_tt27_PU0_140_20150408_SLHC25p3_NewPatterns/roads_sf1_nz1_tt27_pt2_6oo6_SingleMuonTest_tt27_PU0_20150408_SLHC25p3_newBank_10M.root"; isSLHC25=1; TString pName("SingleMu_PU0_sf1_nz1_pt2_6oo6");// 6/6
//	TString sTree="SingleMuonTest_tt27_PU0_140_20150408_SLHC25p3_NewPatterns/roads_5oo6_SingleMuonFlatOneOverPt0p0005To0p5_tt27_sf1_nz4_pt2_SLHC25p3_2M.root"; isSLHC25=1; TString pName("SingleMu_PU0_sf1_nz4_pt2_5or6oo6");// 5/6
//	TString sTree="SingleMuonTest_tt27_PU0_140_20150408_SLHC25p3_NewPatterns/roads_5oo6_SingleMuonFlatOneOverPt0p0005To0p5_tt27_sf1_nz4_pt3_SLHC25p3_2M.root"; isSLHC25=1; TString pName("SingleMu_PU0_sf1_nz4_pt3_5or6oo6");// 5/6
//	TString sTree="SingleMuonTest_tt27_PU0_140_20150408_SLHC25p3_NewPatterns/roads_6oo6_SingleMuonFlatOneOverPt0p0005To0p5_tt27_sf1_nz4_pt2_SLHC25p3_2M.root"; isSLHC25=1; TString pName("SingleMu_PU0_sf1_nz4_pt2_6oo6");// 6/6
//	TString sTree="SingleMuonTest_tt27_PU0_140_20150408_SLHC25p3_NewPatterns/roads_6oo6_SingleMuonFlatOneOverPt0p0005To0p5_tt27_sf1_nz4_pt3_SLHC25p3_2M.root"; isSLHC25=1; TString pName("SingleMu_PU0_sf1_nz4_pt3_6oo6");// 6/6
//	TString sTree="SingleMuonTest_tt27_PU0_20150815_fullNtuple/roads_SingleMuonTest_tt27_PU0_sf1_nz4_pt3_5oo6_95c_100k.root"; isSLHC25=1; TString pName("SingleMuTest_PU0_sf1_nz4_pt3_5oo6"); TString pTitle("SingleMuTest SF=1 Nz=4 Pt>3 GeV/c 5oo6");// 5/6
//	TString sTree="SingleMuonTest_tt27_PU0_20150815_fullNtuple/roads_SingleMuonTest_tt27_PU0_sf1_nz4_pt3_5oo6_95c_100k_removeOverlap.root"; isSLHC25=1; TString pName("SingleMuTest_PU0_sf1_nz4_pt3_5oo6_removeOverlap"); TString pTitle("SingleMuTest SF=1 Nz=4 Pt>3 GeV/c 5oo6 remove Overlap");// 5/6
//	TString sTree="Neutrino_PU140_tt27_sf1_nz4_pt3_OverlapClean_20150903/roads_Neutrino_PU140_tt27_sf1_nz4_pt3_5oo6_95c.root"; isSLHC25=1; TString pName("Neutrino_PU140_sf1_nz4_pt3_5oo6"); TString pTitle("Neutrino PU140 SF=1 Nz=4 Pt>3 GeV/c 5oo6");// 5/6
	TString sTree="Neutrino_PU140_tt27_sf1_nz4_pt3_OverlapClean_20150903/roads_Neutrino_PU140_tt27_sf1_nz4_pt3_5oo6_OverlapClean_95c.root"; isSLHC25=1; TString pName("Neutrino_PU140_sf1_nz4_pt3_5oo6_OverlapClean"); TString pTitle("Neutrino PU140 SF=1 Nz=4 Pt>3 GeV/c 5oo6 remove Overlap");// 5/6
//	TString sTree="Neutrino_PU140_tt27_sf1_nz4_pt3_OverlapClean_20150903/roads_Neutrino_PU140_tt27_sf1_nz4_pt3_5oo6_OverlapClean_95c_0p8_0p8_0p6_0p8_0p6_0p5.root"; isSLHC25=1; TString pName("Neutrino_PU140_sf1_nz4_pt3_5oo6_OverlapClean_0p8_0p8_0p6_0p8_0p6_0p5"); TString pTitle("Neutrino PU140 SF=1 Nz=4 Pt>3 GeV/c 5oo6 remove Overlap");// 5/6

//	TString sTree="Neutrino_tt27_PU140_20150408_SLHC25p3_NewPatterns/roads_sf1_nz4_tt27_pt2_6oo6_Neutrino_PU140_20150408_SLHC25p3_newBank_100M.root"; isSLHC25=1; TString pName("Neutrino_PU140_sf1_nz4_pt2_6oo6"); TString pTitle("PU140 SF=1 Nz=4 Pt>2 GeV/c");;// 6/6
//	TString sTree="Neutrino_tt27_PU140_20150408_SLHC25p3_NewPatterns/roads_sf1_nz4_tt27_pt2_5or6oo6_Neutrino_PU140_20150408_SLHC25p3_newBank_100M.root"; isSLHC25=1; TString pName("Neutrino_PU140_sf1_nz4_pt2_5or6oo6"); TString pTitle("PU140 SF=1 Nz=4 Pt>2 GeV/c");// 6/6
//	TString sTree="Neutrino_tt27_PU140_20150408_SLHC25p3_NewPatterns/roads_sf1_nz4_tt27_pt3_5or6oo6_Neutrino_PU140_20150408_SLHC25p3_newBank_100M.root"; isSLHC25=1; TString pName("Neutrino_PU140_sf1_nz4_pt3_5or6oo6"); TString pTitle("PU140 SF=1 Nz=4 Pt>3 GeV/c");// 6/6


//	TString sTree="TTbarTTbar_tt27_PU140_20150408_SLHC25p3_NewPatterns/roads_sf1_nz4_tt27_pt2_5oo6_TTbarTTbar_tt27_PU140_20150408_SLHC25p3_100M.root"; isSLHC25=1; TString pName("4Tops_PU140_sf1_nz4_pt2_5or6oo6"); TString pTitle("tttt+PU140 SF=1 Nz=4 Pt>2 GeV/c");// 6/6
//	TString sTree="TTbarTTbar_tt27_PU140_20150408_SLHC25p3_NewPatterns/roads_sf1_nz4_tt27_pt2_6oo6_TTbarTTbar_tt27_PU140_20150408_SLHC25p3_100M.root"; isSLHC25=1; TString pName("4Tops_PU140_sf1_nz4_pt2_6oo6"); TString pTitle("tttt+PU140 SF=1 Nz=4 Pt>2 GeV/c");// 6/6
//	TString sTree="TTbarTTbar_tt27_PU140_20150408_SLHC25p3_NewPatterns/roads_sf1_nz4_tt27_pt3_5oo6_TTbarTTbar_tt27_PU140_20150408_SLHC25p3_100M.root"; isSLHC25=1; TString pName("4Tops_PU140_sf1_nz4_pt3_5or6oo6"); TString pTitle("tttt+PU140 SF=1 Nz=4 Pt>3 GeV/c");// 6/6
//	TString sTree="TTbarTTbar_tt27_PU140_20150408_SLHC25p3_NewPatterns/roads_sf1_nz4_tt27_pt3_6oo6_TTbarTTbar_tt27_PU140_20150408_SLHC25p3_100M.root"; isSLHC25=1; TString pName("4Tops_PU140_sf1_nz4_pt3_6oo6"); TString pTitle("tttt+PU140 SF=1 Nz=4 Pt>3 GeV/c");// 6/6

//	TFile *f = TFile::Open("/data/rossin/EOS/patternBank_sf1_nz1_tt27_pt2_400M_ssID_pT.root","READ");
//	TFile *f = TFile::Open("/data/rossin/EOS/patternBank_sf1_nz1_tt27_pt2_first50M.root","READ");
//	TFile *f = TFile::Open("/data/rossin/EOS/patternBank_sf1_nz1_tt27_pt2_SingleMuonFlatOneOverPt0p005To0p5_tt27_Sum2M_SL6.root","READ");
//	TFile *f = TFile::Open("/data/rossin/EOS/patternBank_SingleMuonFlatOneOverPt0p005To0p5_tt27_2M.root","READ");
//	TFile *f = TFile::Open("/data/rossin/EOS/singleMuonNoTest/patternBank_SingleMuonFlatOneOverPt0p005To0p5_tt27_2M.root","READ");
//	TFile *f = TFile::Open("/data/rossin/EOS/singleMuNoTest2_2000/patternBank_sf1_nz1_tt27_pt2_SingleMuonFlatOneOverPt0p0005To0p5_tt27NoTest_4M.root","READ");
//	TFile *f = TFile::Open("/data/rossin/EOS/singleMuNoTest2_2000/patternBank_sf1_nz1_tt27_pt2_SingleMuonFlatOneOverPt0p0005To0p5_tt27NoTest_4M_SLHC25.root","READ"); isSLHC25=1;
//	TFile *f = TFile::Open("/data/rossin/EOS/SingleMuonTest_tt27_PU0_140_20150408_SLHC25p3_NewPatterns/patternBank_sf1_nz1_tt27_pt2_SingleMuon_tt27_SLHC25p3_10M.root","READ"); isSLHC25=1; unsigned npatt95coverage = 104000;

//	TFile *f = TFile::Open("/data/rossin/EOS/SingleMuonTest_tt27_PU0_140_20150408_SLHC25p3_NewPatterns/patternBank_SingleMuonFlatOneOverPt0p0005To0p5_tt27_sf1_nz1_pt2_SLHC25p3_100M.root","READ"); isSLHC25=1; unsigned npatt95coverage = 103200;
//	TFile *f = TFile::Open("/data/rossin/EOS/SingleMuonTest_tt27_PU0_140_20150408_SLHC25p3_NewPatterns/patternBank_SingleMuonFlatOneOverPt0p0005To0p5_tt27_sf1_nz4_pt2_SLHC25p3_100M.root","READ"); isSLHC25=1; unsigned npatt95coverage = 3100200;
//	TFile *f = TFile::Open("/data/rossin/EOS/SingleMuonTest_tt27_PU0_140_20150408_SLHC25p3_NewPatterns/patternBank_SingleMuonFlatOneOverPt0p0005To0p5_tt27_sf1_nz4_pt3_SLHC25p3_100M.root","READ"); isSLHC25=1; unsigned npatt95coverage = 1862700;
//	TFile *f = TFile::Open("/data/rossin/EOS/SingleMuonTest_tt27_PU0_20150815_fullNtuple/patternBank_tt27_sf1_nz4_pt3_100M.root","READ"); isSLHC25=1; unsigned npatt95coverage = 1862700;
	TFile *f = TFile::Open("/data/rossin/EOS/SingleMuonTest_tt27_PU0_20150815_fullNtuple/patternBank_tt27_sf1_nz4_pt3_100M_OverlapClean.root","READ"); isSLHC25=1; unsigned npatt95coverage = 1830100;
//	TFile *f = TFile::Open("/data/rossin/EOS/SingleMuon_PU0_tt27_sf1_nz4_pt3_5or6oo6_OverlapClean_20150828/patternBank_tt27_sf1_nz4_pt3_100M_OverlapClean_0p8_0p8_0p6_0p8_0p6_0p5.3.root","READ"); isSLHC25=1; unsigned npatt95coverage = 1826900;

//	TString sTree="SingleMuonTest_tt27_PU0_140_20150408_SLHC25p3_NewPatterns/roads_6oo6_SingleMuonFlatOneOverPt0p0005To0p5_tt27_sf1_nz1_pt200_SLHC25p3_100M.root"; isSLHC25=1; TString pName("SingleMuon_sf1_nz1_pt200"); TString pTitle("Single Mu SF=1 Nz=1 Pt>200 GeV/c");// 6/6
//	TFile *f = TFile::Open("/data/rossin/EOS/SingleMuonTest_tt27_PU0_140_20150408_SLHC25p3_NewPatterns/patternBank_SingleMuonFlatOneOverPt0p0005To0p5_tt27_sf1_nz1_pt200_SLHC25p3_100M.root","READ"); isSLHC25=1; unsigned npatt95coverage = 1E7;

	if (!f) { return; }
	//	TTree *t=0; f->GetObject("tSSID",t);
	TTree *t=0;
	TTree *tAtt=0;
	if (isSLHC25) f->GetObject("patternAttributes",tAtt);
	f->GetObject("patternBank",t);
	Long64_t tentries = t->GetEntriesFast();
	if (use95coverage) tentries = (npatt95coverage < tentries ? npatt95coverage : tentries);
	cout << "# of patterns in bank: " << tentries << endl;

	std::vector <unsigned int > *AMTTRoads_superstripIds = 0;
	unsigned short ssFrequency;
	double ssPt, ssPtRms, ssPhi, ssPhiRms;
	int ssChargeSum;
	TBranch* bssFrequency=0;
	TBranch *bsuperstripIds= 0;
	TBranch* bssPt  = 0;
	TBranch* bssPtRms = 0;
	TBranch* bssPhi = 0;
	TBranch* bssPhiRms = 0;
	TBranch* bssChargeSum = 0;
	//	t->SetBranchAddress("superstripIds",&AMTTRoads_superstripIds,&bsuperstripIds);
	//	t->Branch("superstripIds"   ,&AMTTRoads_superstripIds);
	//	t->SetBranchAddress("superstripMeanInvPt",&ssPt,&bssPt);
	//	t->SetBranchAddress("superstripRmsInvPt" ,&ssRms,&bssRms);
	t->SetBranchAddress("superstripIds",&AMTTRoads_superstripIds,&bsuperstripIds);
	t->Branch("superstripIds"   ,&AMTTRoads_superstripIds);
	t->SetBranchAddress("frequency",&ssFrequency,&bssFrequency);

	float fssPt, fssPtRms, fssPhi, fssPhiRms;
	if (isSLHC25) {
		tAtt->SetBranchAddress("invPt_mean",&fssPt,&bssPt);
		tAtt->SetBranchAddress("invPt_sigma" ,&fssPtRms,&bssPtRms);
		tAtt->SetBranchAddress("phi_mean",&fssPhi,&bssPhi);
		tAtt->SetBranchAddress("phi_sigma" ,&fssPhiRms,&bssPhiRms);
		//		tAtt->SetBranchAddress("chargeSum" ,&ssChargeSum,&bssChargeSum);
		ssChargeSum = 1;
	}
	else {
		t->SetBranchAddress("meanPt",&ssPt,&bssPt);
		t->SetBranchAddress("rmsPt" ,&ssPtRms,&bssPtRms);
		t->SetBranchAddress("meanPhi",&ssPhi,&bssPhi);
		t->SetBranchAddress("rmsPhi" ,&ssPhiRms,&bssPhiRms);
		t->SetBranchAddress("chargeSum" ,&ssChargeSum,&bssChargeSum);
	}

	//	std::map <vector<unsigned int>, std::pair<std::pair<Double_t,Double_t>,Double_t> > ssIDmap;
	//	std::map <vector<unsigned int>, std::pair<std::pair<Double_t,Double_t>,Double_t> >::iterator it;
	//	std::vector <patternS > vPatternS ; // 6/6 patterns
	//	std::vector <std::vector <patternS > > vvPatternS; // 5/6 patterns
	std::map <vector<unsigned int>, patternS > patternMap;
	std::map <vector<unsigned int>, patternS >::iterator pattern_it;
	vector <std::map <vector<unsigned int>, patternS > > vpatternMap;

	//	for (unsigned iLay=0; iLay<7; ++iLay) {
	//		std::vector <patternS > vPatternSS;
	std::map <vector<unsigned int>, patternS > patternMapS;
	for (Long64_t jentry=0; jentry<tentries;jentry++) {
		Long64_t ientry = t->LoadTree(jentry);
		tAtt->LoadTree(jentry);
		bsuperstripIds->GetEntry(jentry);
		bssFrequency  ->GetEntry(jentry);
		bssPt         ->GetEntry(jentry);
		bssPtRms      ->GetEntry(jentry);
		//			bssPhi        ->GetEntry(jentry);
		//			bssPhiRms     ->GetEntry(jentry);
		if (!isSLHC25) bssChargeSum  ->GetEntry(jentry);
		if (isSLHC25) {		ssPt = (double) fssPt; ssPtRms = (double) fssPtRms; ssPhi= (double) fssPhi; ssPhiRms = (double) fssPhiRms;}

		//		if (!ssChargeSum) continue;

		patternS p;
		p.chargeSum = ssChargeSum;
		p.frequency = ssFrequency;
		p.meanPhi   = ssPhi      ;
		if (isSLHC25) p.meanPt    = ssPt;
		else          p.meanPt    = TMath::Sign(ssPt,(double)ssChargeSum);
		p.rmsPhi    = ssPhiRms   ;
		p.rmsPt     = ssPtRms    ;
		p.superstripIds = *AMTTRoads_superstripIds;
		//			if (iLay==0) {
		//				ssIDmap.insert(make_pair(*AMTTRoads_superstripIds,make_pair(make_pair(TMath::Sign(ssPt,(double)ssChargeSum),ssPhi),ssFrequency)));
		//				vPatternS .push_back(p);
		patternMap.insert(make_pair(p.superstripIds,p));
		//			}
		//			else {
		//				patternS pp(p);
		//				pp.superstripIds.erase(pp.superstripIds.begin()+iLay-1);
		//				vPatternSS.push_back(pp);
		//				patternMapS.insert(make_pair(pp.superstripIds,pp));
		//			}
	}
	//		if (iLay) {
	//			vvPatternS.push_back(vPatternSS);
	//			vpatternMap.push_back(patternMapS);
	//		}
	//	}
	//	cout << "Loaded " << ssIDmap  .size() << " patterns." <<endl;
	cout << "Loaded " << patternMap.size() << " patterns." <<endl;

	/*
	for (unsigned iPatt=0; iPatt<10; ++iPatt) {
		for (unsigned iSS=0; iSS<vPatternS.at(iPatt).superstripIds.size(); ++iSS) cout << vPatternS.at(iPatt).superstripIds[iSS] << "\t";
		cout << endl;
		for (unsigned iLay=0; iLay<vvPatternS.size(); ++iLay) {
			for (unsigned iSS=0; iSS<vvPatternS.at(iLay).at(iPatt).superstripIds.size(); ++iSS) cout << vvPatternS.at(iLay).at(iPatt).superstripIds[iSS] << "\t";
			cout << endl;
		}
		cout << endl;
	}
	 */

	//	TString sStubs("SingleMuonFlatOneOverPt0p005To0p5_tt27_cfi_py_GEN_SIM_DIGI_L1TrackTrigger_100k_ntuple_Sum2M.root");
	//	TTree *tStubs=0;
	//	stubsNtuple stub(sStubs,tStubs);
	//	if (stub.fChain == 0) return;
	//	Long64_t sentries = stub.fChain->GetEntriesFast();
	//	cout << "Loading " << sentries << " stub events" << endl;

	const unsigned nBinsRoughInvPt = 27;
	const unsigned nBinsInvPt      = 30;
	//	double minStubInvPt = -6.75;
	double maxStubInvPt = 6.75;
	//	double minRoadInvPt = -0.5;
	double maxRoadInvPt = 0.5;
	TF1* fgau = new TF1("fgau",gau,-10,10,3); fgau->SetNpx(1000);
	TF1* fp1  = new TF1("fp1" ,"x*[0]"                  ,-10,10);
	TF1* fp3  = new TF1("fp3" ,"x*[0]+x*x*x*[1]",-10,10);

	const unsigned nLayersLoop = 2;

	TProfile* pStubPtroadPt [6][nLayersLoop];
	TH2*     h2StubPtroadPt [6][nLayersLoop];
	TH2*     h2StubPt1roadPt[6];
	//	TH2*     h2roadPtgenPt  [6];
	TH1*     h1StubsPerLayer[6][nLayersLoop][2];
	TH1*     h1RoadPerEvent    [nLayersLoop][2];
	TH1*     h1CombPerRoad     [nLayersLoop][2];
	TH1*     h1CombPerEvent    [nLayersLoop][2];
	TProfile2D*     hProfile2DCombEtaPhi    [nLayersLoop][2];
	TH1*     h1RemovedStubsDeltaSPerLayer[6];
	TH1*     h1RemovedStubsResidualDeltaSPerLayer[6];
	TH2*     h2RemovedStubsResidualDeltaSPerLayer[6];

	TAxis* stubBendQuantized[6];
	double stubBendMax[6] = {2.5,2.5,3.0,4.5,5.5,6.5};
	for (unsigned iLay=0; iLay<6; ++iLay) {
		vector <double> vstubBendQuantized;
		for (unsigned iBend=0; iBend<stubBendMax[iLay]*4; ++iBend) vstubBendQuantized.push_back(-stubBendMax[iLay]+0.5*iBend+0.25);
		if (bitReduction==1) {
			vstubBendQuantized.clear();
			if (iLay<2) {
				double astubBendQuantized[8] = {-2.75,-2.25,-1.75,-0.75,0.75,1.75,2.25,2.75};
				for (unsigned iBend=0; iBend<8; ++iBend) vstubBendQuantized.push_back(astubBendQuantized[iBend]);
			}
			else if (iLay==2) {
				double astubBendQuantized[8] = {-3.25,-2.75,-2.25,-1.25,1.25,2.25,2.75,3.25};
				for (unsigned iBend=0; iBend<8; ++iBend) vstubBendQuantized.push_back(astubBendQuantized[iBend]);
			}
			else if (iLay==3) {
				double astubBendQuantized[16] = {-4.75,-4.25,-3.75,-3.25,-2.75,-2.25,-1.75,-0.75,0.75,1.75,2.25,2.75,3.25,3.75,4.25,4.75};
				for (unsigned iBend=0; iBend<16; ++iBend) vstubBendQuantized.push_back(astubBendQuantized[iBend]);
			}
			else if (iLay==4) {
				double astubBendQuantized[16] = {-5.75,-5.25,-4.75,-4.25,-3.75,-3.25,-2.25,-0.75,0.75,2.25,3.25,3.75,4.25,4.75,5.25,5.75};
				for (unsigned iBend=0; iBend<16; ++iBend) vstubBendQuantized.push_back(astubBendQuantized[iBend]);
			}
			else if (iLay==5) {
				double astubBendQuantized[16] = {-6.75,-6.25,-5.75,-5.25,-4.75,-3.75,-2.75,-0.75,0.75,2.75,3.75,4.75,5.25,5.75,6.25,6.75};
				for (unsigned iBend=0; iBend<16; ++iBend) vstubBendQuantized.push_back(astubBendQuantized[iBend]);
			}
		}
		stubBendQuantized[iLay] = new TAxis(vstubBendQuantized.size()-1,&vstubBendQuantized[0]);
		std::cout << iLay  << "\t";
		for (unsigned iBend=0; iBend<vstubBendQuantized.size()+1; ++iBend) std::cout << stubBendQuantized[iLay]->GetBinCenter(iBend) << " ";
		std::cout << std::endl;
	}

	TFile* fInCuts = 0; bool isfInOpen = false;
//	fInCuts = new TFile("deltaScuts_3p0Sigma.root");
	fInCuts = new TFile("deltaScuts_4p0Sigma.root");
	isfInOpen = fInCuts->IsOpen();
	if (!isfInOpen) {
		cout << "ERROR. Not able to load the deltaS cut file. Exiting..." << endl;
		return;
	}

	TString sName;
	TString sTitle;
	for (unsigned iBin=0; iBin <6; ++iBin) {
		char cc [50];
		char cc2[50];
		sprintf(cc,"_%u",iBin);
		sprintf(cc2,"h1RemovedStubsDeltaSPerLayer_%u",iBin);
		h1RemovedStubsDeltaSPerLayer        [iBin] = new TH1D(cc2,cc2,27,-6.75,6.75);
		sprintf(cc2,"h1RemovedStubsResidualDeltaSPerLayer_%u",iBin);
		h1RemovedStubsResidualDeltaSPerLayer[iBin] = new TH1D(cc2,cc2,5,-1.25,1.25);
		sprintf(cc2,"h2RemovedStubsResidualDeltaSPerLayer_%u",iBin);
		h2RemovedStubsResidualDeltaSPerLayer[iBin] = new TH2D(cc2,cc2,5,-1.25,1.25,27,-6.75,6.75);
		for (unsigned iMissLay=0; iMissLay<nLayersLoop; ++iMissLay) {
			if (iMissLay) sprintf(cc2,"_5oo6_NoLayer_%u",iMissLay-1);
			else          sprintf(cc2,"_6oo6");
			if (iMissLay==nLayersLoop-1) sprintf(cc2,"_5oo6");
			sName=TString("pstubInvPt_VS_roadInvPt")+TString(cc)+TString(cc2);
			pStubPtroadPt  [iBin][iMissLay] = new TProfile(sName,sName,nBinsInvPt,-maxRoadInvPt,maxRoadInvPt,-10,10,"s");
			pStubPtroadPt  [iBin][iMissLay] ->SetXTitle("road mean invPt [c/GeV]");
			pStubPtroadPt  [iBin][iMissLay] ->SetYTitle("#Delta s [strip]");
			sName=TString ("h2stubInvPt_VS_roadInvPt")+TString(cc2)+TString(cc);
			sTitle=TString("stubInvPt VS roadInvPt - Layer")+TString(cc)+TString(cc2);
			h2StubPtroadPt [iBin][iMissLay] = new TH2D    (sName,sTitle,nBinsInvPt,-maxRoadInvPt,maxRoadInvPt,nBinsRoughInvPt,-maxStubInvPt,maxStubInvPt);
			h2StubPtroadPt [iBin][iMissLay] ->SetXTitle("road mean invPt [c/GeV]");
			h2StubPtroadPt [iBin][iMissLay] ->SetYTitle("#Deltas [strip]");

			char cc3[50];
			for (unsigned iClean=0; iClean<2; ++iClean) {
				if (iClean) sprintf(cc3,"_Cleaned");
				else        sprintf(cc3," ");
				sName=TString("h1stubsInLayer_")+TString(cc2)+TString(cc)+TString(cc3);
				h1StubsPerLayer           [iBin][iMissLay][iClean] = new TH1D(sName,sName,20,0,20);
			}
		}
		sName=TString("h2stubInvPt1_VS_roadInvPt")+TString(cc);
		h2StubPt1roadPt[iBin] = new TH2D    (sName,sName,nBinsInvPt,-maxRoadInvPt,maxRoadInvPt,nBinsRoughInvPt,-maxStubInvPt,maxStubInvPt);
		//		sName=TString("h2roadInvPt_VS_genInvPt")+TString(cc);
		//		h2roadPtgenPt  [iBin] = new TH2D    (sName,sName,nBinsInvPt,-0.6         ,0.6         ,nBinsRoughInvPt,-maxRoadInvPt,maxRoadInvPt);
	}
	for (unsigned iMissLay=0; iMissLay<nLayersLoop; ++iMissLay) {
		char cc [50];
		char cc2[50];
		char cc3[50];
		if (iMissLay) sprintf(cc2,"_5oo6_NoLayer_%u",iMissLay-1);
		else          sprintf(cc2,"_6oo6");
		if (iMissLay==nLayersLoop-1) sprintf(cc2,"_5oo6");
		for (unsigned iClean=0; iClean<2; ++iClean) {
			if (iClean) sprintf(cc3,"_Cleaned");
			else        sprintf(cc3," ");
			int nRoadHisto = 50;
			int nCombRoadHisto = 100;
			int nCombHisto = 200;
			if (pName.Contains("4Tops_PU140_")) {
				nRoadHisto=2000;
				nCombRoadHisto = 200;
				nCombHisto=10000;
				if (!iMissLay) {
					nRoadHisto/=8;
					nCombRoadHisto/=2;
					nCombHisto/=8;
				}
			}
			if (pName.Contains("SingleMu_PU140_") || pName.Contains("Neutrino_PU140_")) {
				nRoadHisto=200;
				nCombRoadHisto = 100;
				nCombHisto=500;
				if (!iMissLay) {
					nRoadHisto/=4;
					nCombRoadHisto/=2;
					nCombHisto/=4;
				}
			}

			sName=TString("h1RoadPerEvent")+TString(cc2)+TString(cc3);
			h1RoadPerEvent[iMissLay][iClean] = new TH1D(sName,"",nRoadHisto,0,nRoadHisto);
			h1RoadPerEvent[iMissLay][iClean] ->SetXTitle("# road/tower/BX");
			h1RoadPerEvent[iMissLay][iClean] ->SetTitle(pTitle);
			sName=TString("h1CombPerRoad")+TString(cc2)+TString(cc3);
			h1CombPerRoad[iMissLay][iClean] = new TH1D(sName,"",nCombRoadHisto,0,nCombRoadHisto);
			h1CombPerRoad[iMissLay][iClean] ->SetXTitle("# comb/road/BX");
			h1CombPerRoad[iMissLay][iClean] ->SetTitle(pTitle);
			sName=TString("h1CombPerEvent")+TString(cc2)+TString(cc3);
			h1CombPerEvent[iMissLay][iClean] = new TH1D(sName+TString("_SingleStub"),"",nCombHisto,0,nCombHisto);
			h1CombPerEvent[iMissLay][iClean] ->SetXTitle("# comb/tower/BX");
			h1CombPerEvent[iMissLay][iClean] ->SetTitle(pTitle);

			sName=TString ("hProfile2DCombEtaPhi")+TString(cc2)+TString(cc3);
			sTitle=TString("Combinations per Road")+TString(cc)+TString(cc2);
			hProfile2DCombEtaPhi [iMissLay][iClean] = new TProfile2D    (sName,sTitle,200,0,0.7,200,0.8,1.5);
		}
	}
	//	const int nHoughEv=5*5;
	//	TF1* fHough_zr = new TF1("fHough_zr","[0]+[1]*x",-15,15);
	//	fHough_zr->SetNpx(1000);

	TTree* tree=0;
	roadsStubs r(sTree,tree);
	if (r.fChain == 0) return;

	Long64_t nentries = r.fChain->GetEntries();
	cout << "Loaded " << nentries << " events" << endl;

	//	TCanvas*  cHough_zr = new TCanvas("cHough_zr","cHough_zr",0,0,800,800);
	//	cHough_zr->Divide(sqrt(nHoughEv),sqrt(nHoughEv));


	unsigned nTested=0;
	Long64_t nbytes = 0, nb = 0;
	//	if (!deriveCuts) nentries=0;

	TH2D* hslopes11   = new TH2D("hslopes11"  ,"hslopes11"  ,6,0,6,7,0,7);
	TH2D* hhalfwidths = new TH2D("hhalfwidths","hhalfwidths",6,0,6,7,0,7);
	double slopes11[6][7];
	double slopes1 [6][7];
	double slopes3 [6][7];
	double halfwidths[6][7];
	if (isfInOpen) {
		hslopes11   = (TH2D*) fInCuts->Get("hslopes11"  );
		hhalfwidths = (TH2D*) fInCuts->Get("hhalfwidths");
		if (!hslopes11) return;
		cout << "Loading slopes and halfwidths" << endl;
		for (unsigned iMissLay=0; iMissLay<7; ++iMissLay) {
			for (unsigned iLay=0; iLay<6; ++iLay) {
				slopes11  [iLay][iMissLay] = hslopes11  ->GetBinContent(iLay+1,iMissLay+1);
				halfwidths[iLay][iMissLay] = hhalfwidths->GetBinContent(iLay+1,iMissLay+1);
				cout <<   "slopes11["  <<iLay<<"]["<<iMissLay<<"] = "    << slopes11  [iLay][iMissLay]
																																										 << "; halfwidths["<<iLay<<"]["<<iMissLay<<"] = "    << halfwidths[iLay][iMissLay]
																																																																														 << ";" << endl;
			}
		}
	}

	unsigned countEv        = 0;
	unsigned count6         = 0;
	unsigned count5or6      = 0;

	unsigned count6Clean    = 0;
	unsigned count5or6Clean = 0;


	for (Long64_t jentry=0; jentry<nentries;jentry++) { // LOOPING OVER EVENTS
		//	for (Long64_t jentry=0; jentry<100;jentry++) {
		Long64_t ientry = r.LoadTree(jentry);
		if (ientry < 0) break;
		nb = r.fChain->GetEntry(jentry);   nbytes += nb;
		unsigned int nPart  = r.genParts_pt     ->size();
		//		unsigned int nTotStubs = r.TTStubs_r       ->size();
		unsigned int nRoads = r.AMTTRoads_nstubs->size();
		if (!nRoads) continue;
		++countEv;

		bool eventFired6 = false;
		bool eventFired5or6 = false;
		bool eventFiredClean6 = false;
		bool eventFiredClean5or6 = false;

		unsigned short nCombinationsPerEvent5oo6 = 0;
		unsigned short nCombinationsPerEvent6oo6 = 0;
		unsigned short nCombinationsPerEventClean5oo6 = 0;
		unsigned short nCombinationsPerEventClean6oo6 = 0;

		unsigned short nRoadsPerEvent5oo6 = 0;
		unsigned short nRoadsPerEvent6oo6 = 0;
		unsigned short nRoadsPerEventClean5oo6 = 0;
		unsigned short nRoadsPerEventClean6oo6 = 0;

		double genPartPt  = r.genParts_pt ->at(0);
		double genPartEta = r.genParts_eta->at(0);
		double genPartPhi = r.genParts_phi->at(0);
		double genPartz0  = r.genParts_vz ->at(0);

		//		vector <slhcl1tt::TTRoad> vroadSingleStub;
		//		vector <slhcl1tt::TTRoad> vroadSingleStubDsClean;
		//		vector <slhcl1tt::TTRoad> vroadDsClean;

		//		cout << "nRoads " << nRoads << endl;
		for (unsigned int iRoads=0; iRoads<nRoads; ++iRoads) { // LOOPING OVER ROADS in EVENT
			slhcl1tt::TTRoad road;
			road.stubRefs      = r.AMTTRoads_stubRefs     ->at(iRoads);
			road.superstripIds = r.AMTTRoads_superstripIds->at(iRoads);
			road.nstubs        = r.AMTTRoads_nstubs       ->at(iRoads);
			//			road.patternRef    = r.AMTTRoads_patternRef   ->at(iRoads);
			//			slhcl1tt::TTRoad roadDsClean   (road);


			std::map <short int,unsigned int> stubLayers_map;
			std::map <short int,unsigned int> stubLayers_mapClean;
			short unsigned int stubsPerLayer     [6] = {0,0,0,0,0,0};
			short unsigned int stubsPerLayerClean[6] = {0,0,0,0,0,0};

			pattern_it=patternMap.find(road.superstripIds);
			//			it=ssIDmap.find(road.superstripIds);
			if (pattern_it==patternMap.end() ) {
				continue;
			}
			bool fired6Layer         = false;
			bool fired5Layer         = false;
			bool fired5or6Layer      = false;

			bool fired6LayerClean    = false;
			bool fired5LayerClean    = false;
			bool fired5or6LayerClean = false;


			for (unsigned int iSS=0; iSS<road.superstripIds.size();++iSS) { // Looping over SS in ROAD
				unsigned int ssID = road.superstripIds.at(iSS);
				unsigned int nStubs = road.stubRefs.at(iSS).size();
				//				vector <unsigned> vStubsIDDsClean   ;
				//				vector <unsigned> vStubsIDSingleStubDsClean;
				vector <std::pair<TVector3,unsigned> > vRStubsID;
				for (unsigned int iStub=0; iStub<nStubs; ++iStub) { // looping on stubs 1
					unsigned int stubID = road.stubRefs.at(iSS).at(iStub);
					short int stub_layer = TMath::Floor(r.TTStubs_modId   ->at(stubID)/10000.)-5;
					++stubsPerLayer[stub_layer];
					stubLayers_map [stub_layer]=stubID;
//					double stub_bend = r.TTStubs_trigBend->at(stubID);
				} //end looping on stubs 1
			} // end looping on SS

			if (stubLayers_map.size()==6) {
				fired6Layer   =true; // a 5/6 will fire a 6/6 pattern, but no stub will be found
				fired5or6Layer=true;
				eventFired6   =true;
				eventFired5or6   =true;
			}
			if (stubLayers_map.size()==5) {
				fired5Layer   =true;
				fired5or6Layer=true;
				eventFired5or6   =true;
			}

			double roadInvPt       = -999;
			unsigned roadInvPtFreq = 0;
			int missingLayer = -1;

			if (fired6Layer || fired5Layer) {
				roadInvPt     = pattern_it->second.meanPt;
				roadInvPtFreq = pattern_it->second.frequency;
			}
			else continue;

			if (fired5Layer) {
				for (unsigned iL=0; iL <6; ++iL) {
					if (!stubsPerLayer[iL]) {
						missingLayer=iL;
						break;
					}
				}
			}

			for (unsigned int iSS=0; iSS<road.superstripIds.size();++iSS) { // Looping over SS in ROAD
				for (unsigned int iStub=0; iStub<road.stubRefs.at(iSS).size(); ++iStub) {
					unsigned int stubID = road.stubRefs.at(iSS).at(iStub);
					short int stub_layer = TMath::Floor(r.TTStubs_modId   ->at(stubID)/10000.)-5;
					double halfWidthCut = 0;
					if (fired6Layer) {
						fp1->SetParameter(0,slopes11[stub_layer][0]             );
						halfWidthCut     = halfwidths[stub_layer][0];
					}
					if (fired5Layer) {
						fp1->SetParameter(0,slopes11[stub_layer][missingLayer+1]);
						halfWidthCut     = halfwidths[stub_layer][missingLayer+1];
					}
					double centralValueCut = fp1->Eval(roadInvPt);
					if (centralValueCut==0) cout << "MIEZZEGA" << "\t" << fired6Layer << "\t" << fired5Layer << "\t" <<  roadInvPt << "\t" << fp1->GetParameter(0) << endl;
					if (halfWidthCut==0) cout << "CAZZAROLA" << "\t" << stub_layer << "\t" << missingLayer+1<< endl;
					double stub_bend = r.TTStubs_trigBend->at(stubID);
					double residualStubBend = stub_bend-stubBendQuantized[stub_layer]->GetBinCenter(stubBendQuantized[stub_layer]->FindBin(stub_bend));
					h1RemovedStubsResidualDeltaSPerLayer[stub_layer]->Fill(residualStubBend);
					h2RemovedStubsResidualDeltaSPerLayer[stub_layer]->Fill(residualStubBend,stub_bend);
					if (bitReduction) {
						stub_bend = stubBendQuantized[stub_layer]->GetBinCenter(stubBendQuantized[stub_layer]->FindBin(stub_bend));
					}

					if (!layerSelect[stub_layer] ||
							(centralValueCut-halfWidthCut < stub_bend &&
							stub_bend < centralValueCut+halfWidthCut)) {
						++stubsPerLayerClean[stub_layer];
						stubLayers_mapClean[stub_layer]=stubID;
					}
					else h1RemovedStubsDeltaSPerLayer[stub_layer]->Fill(stub_bend);
				} //end looping on stubs
			} // end looping on SS

			if (stubLayers_mapClean.size()==6) {
				fired6LayerClean   =true; // a 5/6 will fire a 6/6 pattern, but no stub will be found
				fired5or6LayerClean=true;
				eventFiredClean6   =true;
				eventFiredClean5or6=true;
			}
			if (stubLayers_mapClean.size()==5) {
				fired5LayerClean   =true;
				fired5or6LayerClean=true;
				eventFiredClean5or6=true;
			}

			int missingLayerClean = -1;
			if (fired5LayerClean) for (unsigned iLay=0; iLay<6; ++iLay) {
				if (!stubsPerLayerClean[iLay]) {
					missingLayerClean = iLay;
					break;
				}
			}


			unsigned short nCombinationsPerRoad6oo6 = 1;
			unsigned short nCombinationsPerRoad5oo6 = 1;
			unsigned short nCombinationsPerRoadClean6oo6 = 1;
			unsigned short nCombinationsPerRoadClean5oo6 = 1;
			for (unsigned iLay=0; iLay <6; ++iLay) {
				if (fired6Layer) {
					h1StubsPerLayer [iLay][0][0]->Fill(stubsPerLayer[iLay]);
					nCombinationsPerRoad6oo6 *= stubsPerLayer[iLay];
					h1StubsPerLayer [iLay][0][1]->Fill(stubsPerLayerClean[iLay]);

					if (fired6LayerClean) {
						nCombinationsPerRoadClean6oo6 *= stubsPerLayerClean[iLay];
					}
				}

				if (fired5or6Layer) {
					h1StubsPerLayer [iLay][1][0]->Fill(stubsPerLayer[iLay]);
					if (stubsPerLayer[iLay]) nCombinationsPerRoad5oo6 *= stubsPerLayer[iLay];
					h1StubsPerLayer[iLay][1][1]->Fill(stubsPerLayerClean[iLay]);
				}
				if (fired5or6LayerClean) {
					if (stubsPerLayerClean[iLay]) nCombinationsPerRoadClean5oo6 *= stubsPerLayerClean[iLay];
				}
			}

			if (fired6Layer) {
				++nRoadsPerEvent6oo6;
				h1CombPerRoad          [0][0]     ->Fill(nCombinationsPerRoad6oo6);
				if (TMath::Abs(genPartz0)<0.5 && genPartPt>200) hProfile2DCombEtaPhi   [0][0]     ->Fill(genPartEta,genPartPhi,nCombinationsPerRoad6oo6);
				nCombinationsPerEvent6oo6 += nCombinationsPerRoad6oo6;
				if (fired6LayerClean) {
					++nRoadsPerEventClean6oo6;
					h1CombPerRoad          [0][1]   ->Fill(nCombinationsPerRoadClean6oo6);
					nCombinationsPerEventClean6oo6 += nCombinationsPerRoadClean6oo6;
				}
			}

			if (fired5or6Layer) {
				++nRoadsPerEvent5oo6;
				h1CombPerRoad          [1][0]     ->Fill(nCombinationsPerRoad5oo6);
				nCombinationsPerEvent5oo6 += nCombinationsPerRoad5oo6;
			}

			if (fired5or6LayerClean) {
				++nRoadsPerEventClean5oo6;
				h1CombPerRoad          [1][1]     ->Fill(nCombinationsPerRoadClean5oo6);
				nCombinationsPerEventClean5oo6 += nCombinationsPerRoadClean5oo6;
			}
		} // end looping on roads

		h1RoadPerEvent[0][0]->Fill(nRoadsPerEvent6oo6);
		h1RoadPerEvent[0][1]->Fill(nRoadsPerEventClean6oo6);
		h1RoadPerEvent[1][0]->Fill(nRoadsPerEvent5oo6);
		h1RoadPerEvent[1][1]->Fill(nRoadsPerEventClean5oo6);

		h1CombPerEvent[0][0]->Fill(nCombinationsPerEvent6oo6);
		h1CombPerEvent[0][1]->Fill(nCombinationsPerEventClean6oo6);
		h1CombPerEvent[1][0]->Fill(nCombinationsPerEvent5oo6);
		h1CombPerEvent[1][1]->Fill(nCombinationsPerEventClean5oo6);

		if (eventFired6) ++count6;
		if (eventFired5or6) ++count5or6;
		if (eventFiredClean6) ++count6Clean;
		if (eventFiredClean5or6) ++count5or6Clean;

		if (jentry%5000==0 && jentry) {
			cout << "Processing entry " << setw(12) << jentry << setw(12) << 1.0*countEv/jentry
					<< setw(12) << 1.0*count6/countEv << setw(12) << 1.0*count5or6/countEv ;
			cout << setw(12) << 1.0*count6Clean/countEv << setw(12) << 1.0*count5or6Clean/countEv ;
			cout << endl;
		}
	} // end looping over events
	//	cout << count6 << "\t" << count5 << endl;

//		return;

	TFile* fOut=0;
	if (savePlots>1) {
		fOut = new TFile(TString(dirPlots+TString("stubCleaning_")+pName+TString(".root")),"recreate");
		if (fOut->IsOpen()) {
			std::cout << TString(dirPlots+TString("stubCleaning_")+pName+TString(".root")) <<
					"\t" << "has been opened." << std::endl;
		}
		else {
			std::cout << "Unable to open file: " << TString(dirPlots+TString("stubCleaning_")+pName+TString(".root")) << std::endl;
			return;
		}
	}
	TLegend* tl;
	TCanvas* cStubsPerLayer[nLayersLoop][2];
	for (unsigned iMissLay=1; iMissLay <nLayersLoop; ++iMissLay) {
		if (nLayers==6 && iMissLay) continue;
		char cc [50];
		char cc2[50];
		char cc3[50];
		char cc5[50];
		if (iMissLay) {
			sprintf(cc2," 5 or 6 oo6");
			sprintf(cc5,"_5or6oo6");
		}
		else {
			sprintf(cc2," 6oo6");
			sprintf(cc5,"_6oo6_");
		}
		for (unsigned iClean=0; iClean<1; ++iClean) {
			char cc4[50]="";
			//			if (!iClean) sprintf(cc4,"_NoClean");
			TString sTitle(TString("Stubs per layer")+TString(cc2)+TString(cc4));
			TString sName (TString("cStubsPerLayer")+TString(cc5)+TString(cc4));
			cStubsPerLayer[iMissLay][iClean]= new TCanvas(sName,sTitle,0,0,900,900);
			cStubsPerLayer[iMissLay][iClean]->Divide(3,2);
			for (unsigned iLay=0; iLay <6; ++iLay) {
				cStubsPerLayer[iMissLay][iClean]->cd(iLay+1);
				gPad->SetLogy();
				gPad->SetGrid();
				tl = new TLegend(0.3,0.75,0.9,0.9);
				sprintf(cc,"Stubs in Layer %u",iLay);
				h1StubsPerLayer[iLay][iMissLay][0]->SetTitle(TString(cc)+TString(cc2));
				h1StubsPerLayer[iLay][iMissLay][0]->SetLineWidth(2);
				h1StubsPerLayer[iLay][iMissLay][0]->SetXTitle("# stubs/layer/road");
				h1StubsPerLayer[iLay][iMissLay][0]->SetMinimum(0.5);
				h1StubsPerLayer[iLay][iMissLay][0]->DrawCopy();
				if (savePlots>1) 				h1StubsPerLayer[iLay][iMissLay][0]->Write();
				sprintf(cc3,"Mean # stubs: %3.2lf",h1StubsPerLayer[iLay][iMissLay][0]->GetMean());
				tl->AddEntry(h1StubsPerLayer[iLay][iMissLay][0],cc3);

				h1StubsPerLayer[iLay][iMissLay][1]->SetLineWidth(2);
				h1StubsPerLayer[iLay][iMissLay][1]->SetLineColor(2);
				h1StubsPerLayer[iLay][iMissLay][1]->DrawCopy("same");
				if (savePlots>1) 				h1StubsPerLayer[iLay][iMissLay][1]->Write();
				sprintf(cc3,"Mean # stubs clean: %3.1lf",h1StubsPerLayer[iLay][iMissLay][1]->GetMean());
				tl->AddEntry(h1StubsPerLayer[iLay][iMissLay][1],cc3);
				tl->Draw("APL");
			}
			sName =(dirPlots+cStubsPerLayer[iMissLay][iClean]->GetName()+TString("_")+pName+TString("_cleanLay")+clayerSelect);
			if (savePlots) {
				cStubsPerLayer[iMissLay][iClean]->Update();
				cStubsPerLayer[iMissLay][iClean]->SaveAs(sName+TString(".png"));
				if (savePlots>1) {
					cStubsPerLayer[iMissLay][iClean]->Write(cStubsPerLayer[iMissLay][iClean]->GetName()+TString("_")+pName);
				}
			}
		}
	}

//	TCanvas* cRemovedStubsDeltaSPerLayer = new TCanvas("cRemovedStubsDeltaSPerLayer","cRemovedStubsDeltaSPerLayer",0,0,900,900);
//	cRemovedStubsDeltaSPerLayer->Divide(3,2);
//	for (unsigned iLay=0; iLay <6; ++iLay) {
//		cRemovedStubsDeltaSPerLayer->cd(iLay+1);
//		h1RemovedStubsDeltaSPerLayer[iLay]->DrawCopy();
//	}
//
//	TCanvas* cRemovedStubsResidualDeltaSPerLayer = new TCanvas("cRemovedStubsResidualDeltaSPerLayer","cRemovedStubsResidualDeltaSPerLayer",0,0,900,900);
//	cRemovedStubsResidualDeltaSPerLayer->Divide(3,2);
//	for (unsigned iLay=0; iLay <6; ++iLay) {
//		cRemovedStubsResidualDeltaSPerLayer->cd(iLay+1);
//		h1RemovedStubsResidualDeltaSPerLayer[iLay]->DrawCopy();
//	}
//
//	TCanvas* c2RemovedStubsResidualDeltaSPerLayer = new TCanvas("c2RemovedStubsResidualDeltaSPerLayer","cR2emovedStubsResidualDeltaSPerLayer",0,0,900,900);
//	c2RemovedStubsResidualDeltaSPerLayer->Divide(3,2);
//	for (unsigned iLay=0; iLay <6; ++iLay) {
//		c2RemovedStubsResidualDeltaSPerLayer->cd(iLay+1);
//		h2RemovedStubsResidualDeltaSPerLayer[iLay]->DrawCopy("colz0");
//	}

	double  percentiles   [3] = {0.01, 0.5, 0.95};
	double xpercentiles[6][3];
	TCanvas* cRoadPerEvent[2]; // 6oo6, 5oo6 per layer
	TCanvas* cCombPerRoad [2];
	TCanvas* cCombPerEvent[2];
	TCanvas* cRoadPerEventCDF[2]; // 6oo6, 5oo6 per layer
	TCanvas* cCombPerRoadCDF [2];
	TCanvas* cCombPerEventCDF[2];
	for (unsigned iLay=0; iLay <2; ++iLay) {
		if (nLayers==6 && iLay) continue;
		char cc [50];
		char cc2[50];
		if      (iLay==0) {
			sprintf(cc ,"_6oo6");
			sprintf(cc2," 6 oo 6");
		}
		else if (iLay==1) {
			sprintf(cc ,"_5or6oo6");
			sprintf(cc2," 5or6 oo 6");
		}
		TString sName (TString("cRoadsPerEvent")+TString(cc));
		TString sTitle(TString("Roads per event")+TString(cc2));
		cRoadPerEvent[iLay] = new TCanvas(sName,sTitle,0,0,900,900);
		sName  = TString("cRoadsPerEventCDF")+TString(cc);
		sTitle = TString("Roads per event CDF")+TString(cc2);
		cRoadPerEventCDF[iLay] = new TCanvas(sName,sTitle,0,0,900,900);
		sName  = (TString("cCombPerRoad")+TString(cc));
		sTitle = (TString("Combs per road")+TString(cc2));
		cCombPerRoad [iLay] = new TCanvas(sName,sTitle,0,0,900,900);
		sName  = (TString("cCombPerRoadCDF")+TString(cc));
		sTitle = (TString("Combs per road CDF")+TString(cc2));
		cCombPerRoadCDF [iLay] = new TCanvas(sName,sTitle,0,0,900,900);
		sName  = (TString("cCombPerEvent")+TString(cc));
		sTitle = (TString("Combs per event")+TString(cc2));
		cCombPerEvent[iLay] = new TCanvas(sName,sTitle,0,0,900,900);
		sName  = (TString("cCombPerEventCDF")+TString(cc));
		sTitle = (TString("Combs per event CDF")+TString(cc2));
		cCombPerEventCDF[iLay] = new TCanvas(sName,sTitle,0,0,900,900);
	}

//	ofstream myfile;
//	myfile.open ("example.txt", std::ios_base::app);

	for (unsigned iLay=1; iLay <nLayersLoop; ++iLay) {
		if (nLayers==6 && iLay) continue;
		char cc [150];
		char cc2[150];
		char cc3[150];
		if (iLay==0) {
			sprintf(cc2," 6 oo 6");
			sprintf(cc ,"_6oo6_");
		}
		else if (iLay==1) {
			sprintf(cc2," 5or6 oo 6");
			sprintf(cc ,"_5or6oo6_");
		}
		else continue;
		TLegend * tlr=new TLegend(0.3,0.7,0.9,0.9);
		TLegend * tlc=new TLegend(0.3,0.7,0.9,0.9);
		TLegend * tle=new TLegend(0.3,0.7,0.9,0.9);
//		myfile << iLay  << "\t"  << clayerSelect << "\t";
		cout << iLay  << "\t" << clayerSelect << "\t";
		for (unsigned iClean=0; iClean<2; ++iClean) {
			cRoadPerEvent[iLay]->cd();
			gPad->SetLogy();
			gPad->SetGrid();
			h1RoadPerEvent[iLay][iClean]->SetLineWidth(2);
			h1RoadPerEvent[iLay][iClean]->GetQuantiles(3,xpercentiles[0],percentiles);
			if (iClean) {
				h1RoadPerEvent[iLay][iClean]->SetLineColor(2);
				h1RoadPerEvent[iLay][iClean]->DrawCopy("same");
				sprintf(cc3,"# roads clean. #mu=%3.1lf, #Lambda_{95}=%3.1lf",h1RoadPerEvent[iLay][iClean]->GetMean(),xpercentiles[0][2]);
				tlr->AddEntry(h1RoadPerEvent[iLay][iClean],cc3);
				tlr->Draw("APL");
//				myfile << h1RoadPerEvent[iLay][iClean]->GetMean() << "\t" << xpercentiles[0][2] << "\t";
				cout << h1RoadPerEvent[iLay][iClean]->GetMean() << "\t" << xpercentiles[0][2] << "\t";
			}
			else {
				h1RoadPerEvent[iLay][1]     ->DrawCopy();
				h1RoadPerEvent[iLay][1]     ->SetXTitle("# roads/tower/BX");
				h1RoadPerEvent[iLay][1]     ->SetTitle (TString("Roads per Tower")+cc2);
				h1RoadPerEvent[iLay][iClean]->DrawCopy("same");
				sprintf(cc3,"# roads. #mu=%3.1lf, #Lambda_{95}=%3.1lf",h1RoadPerEvent[iLay][iClean]->GetMean(),xpercentiles[0][2]);
				tlr->AddEntry(h1RoadPerEvent[iLay][iClean],cc3);
			}
			cRoadPerEventCDF[iLay]->cd();
			cRoadPerEventCDF[iLay]->SetGridx();
			TH1* hRECDF = makeCDF(h1RoadPerEvent[iLay][iClean]);
			hRECDF->SetMinimum(0.5);
			if (!iClean) {
				hRECDF->DrawCopy();
				TLine l;
				float xmax = h1RoadPerEvent[iLay][iClean]->GetXaxis()->GetXmax();
				l.DrawLine(0,1.0,xmax,1.0);
				l.SetLineStyle(4);
				l.DrawLine(0,0.90,xmax,0.90);
				l.DrawLine(0,0.95,xmax,0.95);
				l.DrawLine(0,0.99,xmax,0.99);
			}
			else         hRECDF->DrawCopy("same");

			cCombPerRoad[iLay]->cd();
			gPad->SetLogy();
			gPad->SetGrid();
			h1CombPerRoad[iLay][iClean]->SetLineWidth(2);
			h1CombPerRoad[iLay][iClean]->GetQuantiles(3,xpercentiles[0],percentiles);
			if (iClean) {
				h1CombPerRoad[iLay][iClean]->SetLineColor(2);
				h1CombPerRoad[iLay][iClean]->DrawCopy("same");
				sprintf(cc3,"# combs clean. #mu=%3.1lf, #Lambda_{95}=%3.1lf",h1CombPerRoad[iLay][iClean]->GetMean(),xpercentiles[0][2]);
				tlc->AddEntry(h1CombPerRoad[iLay][iClean],cc3);
				tlc->Draw("APL");
//				myfile << h1CombPerRoad[iLay][iClean]->GetMean() << "\t" << xpercentiles[0][2] << "\t";
				cout << h1CombPerRoad[iLay][iClean]->GetMean() << "\t" << xpercentiles[0][2] << "\t";
			}
			else {
				h1CombPerRoad[iLay][1]     ->DrawCopy();
				h1CombPerRoad[iLay][1]     ->SetXTitle("# combs/road/BX");
				h1CombPerRoad[iLay][1]     ->SetTitle (TString("Combs per Road")+cc2);
				h1CombPerRoad[iLay][iClean]->DrawCopy("same");
				sprintf(cc3,"# combs. #mu=%3.1lf, #Lambda_{95}=%3.1lf",h1CombPerRoad[iLay][iClean]->GetMean(),xpercentiles[0][2]);
				tlc->AddEntry(h1CombPerRoad[iLay][iClean],cc3);
			}
			cCombPerRoadCDF[iLay]->cd();
			cCombPerRoadCDF[iLay]->SetGridx();
			TH1* hCRCDF = makeCDF(h1CombPerRoad[iLay][iClean]);
			hCRCDF->SetMinimum(0.5);
			if (!iClean) {
				hCRCDF->DrawCopy();
				TLine l;
				float xmax = h1CombPerRoad[iLay][iClean]->GetXaxis()->GetXmax();
				l.DrawLine(0,1.0,xmax,1.0);
				l.SetLineStyle(4);
				l.DrawLine(0,0.90,xmax,0.90);
				l.DrawLine(0,0.95,xmax,0.95);
				l.DrawLine(0,0.99,xmax,0.99);
			}
			else         hCRCDF->DrawCopy("same");

			cCombPerEvent[iLay]->cd();
			gPad->SetLogy();
			gPad->SetGrid();
			h1CombPerEvent[iLay][iClean]->SetLineWidth(2);
			h1CombPerEvent[iLay][iClean]->GetQuantiles(3,xpercentiles[0],percentiles);
			if (iClean) {
				h1CombPerEvent[iLay][iClean]->SetLineColor(2);
				h1CombPerEvent[iLay][iClean]->DrawCopy("same");
				sprintf(cc3,"# combs clean. #mu=%3.1lf, #Lambda_{95}=%3.1lf",h1CombPerEvent[iLay][iClean]->GetMean(),xpercentiles[0][2]);
				tle->AddEntry(h1CombPerEvent[iLay][iClean],cc3);
//				myfile << h1CombPerEvent[iLay][iClean]->GetMean() << "\t" << xpercentiles[0][2] << "\n";
				cout << h1CombPerEvent[iLay][iClean]->GetMean() << "\t" << xpercentiles[0][2] << "\n";
			}
			else {
				h1CombPerEvent[iLay][1]     ->DrawCopy();
				h1CombPerEvent[iLay][1]     ->SetXTitle("# combs/tower/BX");
				h1CombPerEvent[iLay][1]     ->SetTitle (TString("Combs per Tower per BX")+cc2);
				h1CombPerEvent[iLay][iClean]->DrawCopy("same");
				sprintf(cc3,"# combs. #mu=%3.1lf, #Lambda_{95}=%3.1lf",h1CombPerEvent[iLay][iClean]->GetMean(),xpercentiles[0][2]);
				tle->AddEntry(h1CombPerEvent[iLay][iClean],cc3);
				tle->Draw("APL");
			}
			if (savePlots>1) {
				h1RoadPerEvent[iLay][iClean]->Write();
				h1CombPerRoad [iLay][iClean]->Write();
				h1CombPerEvent[iLay][iClean]->Write();
			}
			cCombPerEventCDF[iLay]->cd();
			cCombPerEventCDF[iLay]->SetGridx();
			TH1* hCECDF = makeCDF(h1CombPerEvent[iLay][iClean]);
			hCECDF->SetMinimum(0.5);
			if (!iClean) {
				hCECDF->DrawCopy();
				TLine l;
				float xmax = h1CombPerEvent[iLay][iClean]->GetXaxis()->GetXmax();
				l.DrawLine(0,1.0,xmax,1.0);
				l.SetLineStyle(4);
				l.DrawLine(0,0.90,xmax,0.90);
				l.DrawLine(0,0.95,xmax,0.95);
				l.DrawLine(0,0.99,xmax,0.99);
			}
			else         hCECDF->DrawCopy("same");


//			TCanvas* cCombEtaPhi = new TCanvas("cCombEtaPhi","cCombEtaPhi",0,0,900,900);
//			hProfile2DCombEtaPhi   [0][0]->DrawCopy("colz0");
		}

		if (savePlots) {
			sName=(dirPlots+TString("roadsPerEvent")+TString(cc)+pName+TString("_cleanLay")+clayerSelect);
			cRoadPerEvent [iLay]->Update();
			cRoadPerEvent [iLay]->SaveAs(sName+TString(".png"));
			sName=(dirPlots+TString("combsPerRoad")+TString(cc)+pName+TString("_cleanLay")+clayerSelect);
			cCombPerRoad  [iLay]->Update();
			cCombPerRoad  [iLay]->SaveAs(sName+TString(".png"));
			sName=(dirPlots+TString("combsPerEvent")+TString(cc)+pName+TString("_cleanLay")+clayerSelect);
			cCombPerEvent [iLay]->Update();
			cCombPerEvent [iLay]->SaveAs(sName+TString(".png"));
			sName=(dirPlots+TString("roadsPerEventCDF")+TString(cc)+pName+TString("_cleanLay")+clayerSelect);
			cRoadPerEventCDF[iLay]->SaveAs(sName+TString(".png"));
			sName=(dirPlots+TString("combsPerRoadCDF")+TString(cc)+pName+TString("_cleanLay")+clayerSelect);
			cCombPerRoadCDF [iLay]->SaveAs(sName+TString(".png"));
			sName=(dirPlots+TString("combsPerEventCDF")+TString(cc)+pName+TString("_cleanLay")+clayerSelect);
			cCombPerEventCDF[iLay]->SaveAs(sName+TString(".png"));
			if (savePlots>1) {
				cRoadPerEvent [iLay]->Write();
				cCombPerRoad  [iLay]->Write();
				cCombPerEvent [iLay]->Write();
			}
		}

		//		if (nLayers==5) {
		//			cRoadPerEvent[1]->cd();
		//			gPad->SetLogy();
		//			for (unsigned iClean=0; iClean<2; ++iClean) {
		//				h1RoadPerEvent[iLay][iClean]->SetLineWidth(2);
		//				if (iClean) {
		//					h1RoadPerEvent[iLay][iClean]->SetLineColor(2);
		//					h1RoadPerEvent[iLay][iClean]->DrawCopy("same");
		//				}
		//				else {
		//					h1RoadPerEvent[iLay][1]     ->DrawCopy();
		//					h1RoadPerEvent[iLay][iClean]->DrawCopy("same");
		//				}
		//			}
		//			cCombPerRoad[1]->cd();
		//			gPad->SetLogy();
		//			for (unsigned iClean=0; iClean<2; ++iClean) {
		//				h1CombPerRoad[iLay][iClean]->SetLineWidth(2);
		//				if (iClean) {
		//					h1CombPerRoad[iLay][iClean]->SetLineColor(2);
		//					h1CombPerRoad[iLay][iClean]->DrawCopy("same");
		//				}
		//				else {
		//					h1CombPerRoad[iLay][1]     ->DrawCopy();
		//					h1CombPerRoad[iLay][iClean]->DrawCopy("same");
		//				}
		//			}
		//			cCombPerEvent[1]->cd();
		//			gPad->SetLogy();
		//			for (unsigned iClean=0; iClean<2; ++iClean) {
		//				h1CombPerEvent[iLay][iClean]->SetLineWidth(2);
		//				if (iClean) {
		//					h1CombPerEvent[iLay][iClean]->SetLineColor(2);
		//					h1CombPerEvent[iLay][iClean]->DrawCopy("same");
		//				}
		//				else {
		//					h1CombPerEvent[iLay][1]     ->DrawCopy();
		//					h1CombPerEvent[iLay][iClean]->DrawCopy("same");
		//				}
		//			}
		//		}
	}
//	myfile.close();

	if (savePlots>1) {
		fOut->Close();
	}

	return;

}