void TBDataParser::OnCharacters(const char *characters)
{	
	if(_currentElement != NULL && !strcmp(_currentElement->Data(),"vector")) {
		TString *string = new TString(characters);
		TObjArray *values = string->Tokenize(", ");

		for(Int_t i = 0; i < values->GetEntries(); i++) {
			TObjString *object = (TObjString *) values->At(i);
			TString value = object->GetString().ReplaceAll("\n", "").ReplaceAll("\t", "").ReplaceAll(" ", "").ReplaceAll("\0", "");
			if(value.IsFloat()) {
				_vector->Fill(value.Atof());
			}
		}

		if(_vectorsStack->GetEntries() == 1) {
			_motherVecEntries = _vector->GetEntries();
		} else if(_currentMethod != NULL && !strcmp(_currentMethod->Data(),"all")) {
			for(Int_t i = 1; i < _motherVecEntries; i++) {
				TObjString *object = (TObjString *) values->First();
				TString value = object->GetString().ReplaceAll("\n", "").ReplaceAll("\t", "").ReplaceAll(" ", "").ReplaceAll("\0", "");
				if(value.IsFloat())
					_vector->Fill(value.Atof());
			}
		} 

		values->Delete();

	}

}
Example #2
0
  TCollection* GetEtaBin(TObject* o, Double_t& etaMin, Double_t& etaMax)
  {
    const char* re = "[pm][0-9]*d[0-9]*_[pm][0-9]*d[0-9]*";
    TRegexp     check(re);

    if (!o->IsA()->InheritsFrom(TCollection::Class())) {
      // Warning("GetEtaBin", "Don't know how to deal with %s - a %s",
      //         o->GetName(), o->ClassName());
      return 0;
    }
    TString oN(o->GetName());
    if (oN.Index(check) == kNPOS) { 
      // Warning("GetEtaBin", "Collection %s does not match %s",
      //         oN.Data(), re);
      return 0;
    }
    Int_t    ul     = oN.Index("_");
    TString  sMin   = oN(0, ul);
    TString  sMax   = oN(ul+1, oN.Length()-ul-1);
    sMin.ReplaceAll("p", "+");
    sMin.ReplaceAll("m", "-");
    sMin.ReplaceAll("d", ".");
    sMax.ReplaceAll("p", "+");
    sMax.ReplaceAll("m", "-");
    sMax.ReplaceAll("d", ".");
    etaMin = sMin.Atof();
    etaMax = sMax.Atof();

    return static_cast<TCollection*>(o);
  }
void transferxSecFromTextToROOT(std::string inputStr="xSec_T3G.txt"){

   ifstream fin(inputStr.c_str());
   char line[200];
   TFile *xSecProspinoFile =0;
   TH1D *xSecProspino =0; 
   int minMom = 1000000, maxMom = 0;
   int nBins = 0;

   std::vector<int> momVec; std::vector<double> xSecVec, xSecErrVec;
   while( fin.getline(line, 200) ){
      TString lineT(line);
      if( lineT.Contains("Interactions") ) continue;
      TObjArray *vlist = lineT.Tokenize(" ");
      int nEntries = vlist->GetEntries();
      int mMom;
      double xSec =0, xSecRelErr =0;
      for(int ie=0; ie<nEntries; ie++){
         TObjString* perObj = dynamic_cast<TObjString*>(vlist->At(ie));
         TString perStr = perObj->GetString();
         if( ie==0 ){
            mMom = perStr.Atoi();
            if( minMom > mMom ) minMom = mMom;
            if( maxMom < mMom ) maxMom = mMom;
         }
         if( ie==1 ) xSec = perStr.Atof();
         if( ie==2 ) xSecRelErr = perStr.Atof();
      }
      nBins ++;
      momVec.push_back(mMom); xSecVec.push_back(xSec); xSecErrVec.push_back(xSec*xSecRelErr/100.);
//      std::cout<<"mMom : "<<mMom<<"  xSec : "<<xSec<<"  xSecRelErr : "<<xSecRelErr<<std::endl;
   }
   double divBin = 1.0*(maxMom - minMom)/(nBins-1);
   double lowMom = minMom-divBin/2.0, highMom = maxMom+divBin/2.0;
   std::cout<<"nBins : "<<nBins<<"  minMom : "<<minMom<<"  maxMom : "<<maxMom<<"  divBin : "<<divBin<<"  lowMom : "<<lowMom<<"  highMom : "<<highMom<<std::endl;

   TString rootStrT(inputStr);
   rootStrT.ReplaceAll("txt", "root");

   std::cout<<"root file : "<<rootStrT<<std::endl;
   xSecProspinoFile = new TFile(rootStrT, "RECREATE");

   if( rootStrT.Contains("T1") ) xSecProspino = new TH1D("gluino_xsection", "gluino_xsection", nBins, lowMom, highMom);
   if( rootStrT.Contains("T2") ) xSecProspino = new TH1D("squark_xsection", "squark_xsection", nBins, lowMom, highMom);
   if( rootStrT.Contains("T3G") ) xSecProspino = new TH1D("stop_xsection", "stop_xsection", nBins, lowMom, highMom);

   for(int iv=0; iv<(int)momVec.size(); iv++){
      double mMom = (double)momVec[iv];
      int ib = xSecProspino->FindFixBin(mMom);
      xSecProspino->SetBinContent(ib, xSecVec[iv]);
      xSecProspino->SetBinError(ib, xSecErrVec[iv]);
   }

//   xSecProspino->Write();
   xSecProspinoFile->Write(); xSecProspinoFile->Close();

}
TString get_sample_name(TString name)
{
  TObjArray* arr = name.Tokenize(".");
  
  TString out = ((TObjString*)arr->At(arr->GetEntries()-2))->GetString();
  out.ReplaceAll("_JER_up", "");
  out.ReplaceAll("_JER_down", "");
  out.ReplaceAll("_JEC_up", "");
  out.ReplaceAll("_JEC_down", "");

  out.ReplaceAll("_PU_down", "");
  out.ReplaceAll("_PU_up", "");
  out.ReplaceAll("_LJets_up", "");
  out.ReplaceAll("_LJets_down", "");
  out.ReplaceAll("_BJets_up", "");
  out.ReplaceAll("_BJets_down", "");
  out.ReplaceAll("_MuonSF_down", "");
  out.ReplaceAll("_MuonSF_up", "");
  out.ReplaceAll("_BJets_down", "");
  out.ReplaceAll("_BJets_down", "");
  out.ReplaceAll("_matching_down", "");
  out.ReplaceAll("_matching_up", "");
  out.ReplaceAll("_scale_down", "");
  out.ReplaceAll("_scale_up", "");

  out.ToLower();

  out.ReplaceAll("dyjets_50toinf", "zlight");
  out.ReplaceAll("dyjets", "zlight");
  out.ReplaceAll("dy", "zlight");
  out.ReplaceAll("wjets_bflavor", "wb");
  out.ReplaceAll("wjets_cflavor", "wc");
  out.ReplaceAll("wjets_lflavor", "wlight");
  //out.ReplaceAll("tt", "ttbar");

  
  if (out.Contains("zp")){
    TString temp = out;
    temp.ReplaceAll("zp","");
    temp.ReplaceAll("p", ".");
    TObjArray* arr2 = temp.Tokenize("w");
    TString nom = ((TObjString*)arr2->At(1))->GetString();
    TString denom = ((TObjString*)arr2->At(0))->GetString();
    cout << "nom = " << nom << " denom = " << denom << endl;
    Int_t p = (100*nom.Atof())/denom.Atof();
    cout << "p = " << p << endl;
    out = TString::Format("zp %d w %d p",denom.Atoi(), p);
    out.ReplaceAll(" ", "");
  }
  
  return out;
}
Example #5
0
float *getwq(TH1 *h) {
  TString delim = "_";
  TString hn = h->GetName();
  TObjArray *tokens = hn.Tokenize(delim);
  TObjString *wstro = (TObjString*)tokens->At(1);
  TObjString *qstro = (TObjString*)tokens->At(2);
  TString wstr = wstro->GetString();
  TString qstr = qstro->GetString();
  double wval = wstr.Atof();
  double qval = qstr.Atof();
  float *ret = new float[2];
  ret[0] = wval;
  ret[1] = qval;
  delete tokens;
  return ret;
}
Example #6
0
void bcut::parseWeight(TString wgt){
  cutTypes_.push_back(kFloat);
  fWeights_.push_back(NULL);
  fvWeights_.push_back(NULL);
  indWeights_.push_back(-1);
  constWeights_.push_back(1.);

  if(wgt=="weight")		fWeights_.back() = &baby_base::weight;
  else if(wgt=="w_lumi")	fWeights_.back() = &baby_base::w_lumi;
  else if(wgt=="w_pu")	fWeights_.back() = &baby_base::w_pu;
  else if(wgt=="w_lep")	fWeights_.back() = &baby_base::w_lep;
  else if(wgt=="w_fs_lep")	fWeights_.back() = &baby_base::w_fs_lep;
  else if(wgt=="w_toppt")	fWeights_.back() = &baby_base::w_toppt;
  else if(wgt=="w_btag")	fWeights_.back() = &baby_base::w_btag;
  else if(wgt=="eff_trig")	fWeights_.back() = &baby_base::eff_trig;
  else if(wgt.Contains("[")){ // if weight is a vector element
    TString index_s(wgt);
    wgt.Remove(wgt.Index("["), wgt.Length());
    index_s.Remove(0, index_s.Index("[")+1);
    index_s.Remove(index_s.Index("]"), index_s.Length());
    indWeights_.back() = index_s.Atoi();
    cutTypes_.back() = kvFloat;
    if(wgt=="w_pdf")        fvWeights_.back() = &baby_base::w_pdf;
    else if(wgt=="sys_pdf") fvWeights_.back() = &baby_base::sys_pdf;
    else if(wgt=="sys_isr") fvWeights_.back() = &baby_base::sys_isr;
    else if(wgt=="sys_mur") fvWeights_.back() = &baby_base::sys_mur;
    else if(wgt=="sys_muf") fvWeights_.back() = &baby_base::sys_muf;
    else if(wgt=="sys_murf") fvWeights_.back() = &baby_base::sys_murf;
    else if(wgt=="sys_trig") fvWeights_.back() = &baby_base::sys_trig;
    else if(wgt=="sys_lep") fvWeights_.back() = &baby_base::sys_lep;
    else if(wgt=="sys_fs_lep") fvWeights_.back() = &baby_base::sys_fs_lep;
    else if(wgt=="sys_bctag") fvWeights_.back() = &baby_base::sys_bctag;
    else if(wgt=="sys_fs_bctag") fvWeights_.back() = &baby_base::sys_fs_bctag;
    else if(wgt=="sys_udsgtag") fvWeights_.back() = &baby_base::sys_udsgtag;
    else if(wgt=="sys_fs_udsgtag") fvWeights_.back() = &baby_base::sys_fs_udsgtag;
    else {
      cout<<"Weight \""<<wgt<<" not defined. Add it to bcut::parseWeight in bcut.cpp"<<endl;
      exit(0);
    }
  }else if(wgt.Atof()>0) {
    constWeights_.back() = wgt.Atof();
    cutTypes_.back() = kConst;
  } else {
    cout<<"Weight \""<<wgt<<" not defined. Add it to bcut::parseWeight  in bcut.cpp"<<endl;
    exit(0);
  }   
}
Example #7
0
void TExpenser::calculate_balance() {

    fBalanceXMLParser -> selectMainNode();
    fBalanceXMLParser -> selectNode("entry");
    TString balance = fBalanceXMLParser -> getNodeContent("amount");
    fBalanceXMLParser -> selectNode("date");
    TString balance_year = fBalanceXMLParser -> getNodeContent("year");
    TString balance_month = fBalanceXMLParser -> getNodeContent("month");

    fLastStatusLabel -> SetText(balance_month+"/"+balance_year+": " + balance + " eur");

    // now calculate the current balance (last - expenses since the last)
    TDatime time;

    fXMLParser->selectMainNode();
    fXMLParser->selectNode("expense");
    Double_t expenses_since_last_status = 0;
    while (fXMLParser->getCurrentNode() != 0) {
        XMLNodePointer_t current_node = fXMLParser->getCurrentNode();

        fXMLParser -> selectNode("date");
        TString year = fXMLParser -> getNodeContent("year");
        TString month = fXMLParser -> getNodeContent("month");
        fXMLParser -> setCurrentNode(current_node);

        bool year_more_recent = (year.Atoi() > balance_year.Atoi());
        bool year_same = (year.Atoi() == balance_year.Atoi());
        bool month_more_recent = (month.Atoi()>=balance_month.Atoi());
        bool expense_more_recent_than_balance = (year_more_recent || (year_same && month_more_recent));
        if (  expense_more_recent_than_balance && fXMLParser -> getNodeContent("withdrawn") == "Yes" ) {
            expenses_since_last_status += fXMLParser -> getNodeContent("amount").Atof();
        }

        fXMLParser->selectNextNode("expense");
    }

    // calculate total income since last balance
    fIncomeXMLParser->selectMainNode();
    fIncomeXMLParser->selectNode("entry");
    Double_t income_since_last_status = 0;
    while (fIncomeXMLParser->getCurrentNode() != 0) {
        XMLNodePointer_t current_node = fIncomeXMLParser->getCurrentNode();

        fIncomeXMLParser -> selectNode("date");
        TString year = fIncomeXMLParser -> getNodeContent("year");
        TString month = fIncomeXMLParser -> getNodeContent("month");
        fIncomeXMLParser -> setCurrentNode(current_node);

        if ( ( (month.Atoi()>=balance_month.Atoi()) && (year.Atoi()==balance_year.Atoi()) ) || (year.Atoi()>balance_year.Atoi()) ) {
            income_since_last_status += fIncomeXMLParser -> getNodeContent("amount").Atof();
        }

        fIncomeXMLParser->selectNextNode("entry");
    }

    Double_t new_balance = balance.Atof() - expenses_since_last_status + income_since_last_status;
    fCurrentStatusLabel -> SetText(toStr(time.GetDay())+"/"+toStr(time.GetMonth())+"/"+toStr(time.GetYear())+": " + toStr(new_balance,2) + " eur");
}
Example #8
0
Double_t CalcLednicR(Double_t zr, Double_t zt, Double_t v)
{
  TString cmd = Form("echo '%0.5f,%0.5f,%0.5f'", zr, zt, v);
  cmd+= " | ./lednic_input.exe";
  Printf("%s", cmd.Data());
  cmd = gSystem->GetFromPipe(cmd.Data());
  if (!cmd.IsFloat()) {
    Printf("Problem with program 'lednic_input.exe'");
    return 0;
  }
  return cmd.Atof();
}
void AnalysisConfig::processBinString(vector<pair<float,float> >& binSet, string& inputString)
{
    binSet.clear();

  // Define a regex expression to use to match strings of (float, float) format and a size variable to pass as the size of the resulting match.
    TRegexp numPairRegex("\\(-?[0-9]+\\.?[0-9]?,-?[0-9]+\\.?[0-9]?\\)");
    int* matchLength = new int;

  // Get list of bin strings from input string.
    vector<string> binStrings;
    getListFromString(inputString, binStrings);

  // Extract number information from list of bin strings (Should have format: (i,j) ).
    for(auto& binStr : binStrings)
    {
      // Check if the bin string is a formatted properly.
        *matchLength = 0;
        if(numPairRegex.Index(binStr, matchLength) != 0 || (unsigned int)(*matchLength) != binStr.length())
        { // If the regex expression doesn't find itself in the string *OR* the matched string isn't the full length of the input string...
            cout << "  ERROR (AnalysisConfig::processBinString)\n: Bin string does not have (p,q) format: " << binStr << endl << endl;
            return;     // KICK
        }

        float binMin, binMax;
        TString numStr = "";
        string::iterator it=binStr.begin()+1;

      // Extract bin minimum value
        do{ numStr+=*(it++); } while( it != binStr.end() && *it != ',');
        binMin = numStr.Atof();

     // Extract bin maximum value
        numStr = ""; it++;  // Reset bin number string and move past the comma
        do{ numStr+=*(it++); } while( it != binStr.end() && *it != ')');
        binMax = numStr.Atof();

      // Add pair to bin set.
        binSet.push_back({binMin, binMax});
    }
}
Example #10
0
Int_t KVRTGIDManager::WriteAsciiFile ( const Char_t * filename, const TCollection *selection, Bool_t update )
{
   	// Write identification functions  in file 'filename'.
   	// If selection=0 (default), write all grids.
   	// If update=true, call UpdateListFromIDGridManager() before writing
   	// If selection!=0, write only grids in list.
   	// Returns number of functions written in file.

	if( update ) UpdateListFromIDGridManager();
	if( !fIDGlobalList ){
		Warning("KVRTGIDManager::WriteAsciiFile","No listed identification functions to write");
 	   	return 0;
	}

   	ofstream tgidfile ( filename );
   	if( !tgidfile.is_open() ){
	   	Error("KVRTGIDManager::WriteAsciiFile","No write permission for file %s", filename);
	   	return 0;
   	} 

   	const TCollection *list_tgid = ( selection ? selection : fIDGlobalList );
   	TIter next ( list_tgid );
   	KVTGID *tgid    = NULL;
   	Int_t   n_saved = 0;

   	while ( ( tgid = (KVTGID *)next() ) ) {

		// Not write a KVTGID copy
		TString tmp = tgid->GetTitle();
		if(tmp.Contains("COPY")){
			tmp.Remove(0, tmp.Index("0x"));	
			KVTGID *tmp_tgid = reinterpret_cast<KVTGID *>((Int_t)tmp.Atof());
			Warning("KVRTGIDManager::WriteAsciiFile","The function %s (%s, %p) is not written because it is a copy of %s (%s, %p)"
					, tgid->GetName(), tgid->ClassName(), tgid
					, tmp_tgid->GetName(), tmp_tgid->ClassName(), tmp_tgid);
			continue;
		}
      	tgid->WriteToAsciiFile ( tgidfile );
      	Info( "KVRTGIDManager::WriteAsciiFile", "%s (%s, %p) saved", tgid->GetName(), tgid->ClassName(), tgid );
      	n_saved++;
   	}

   	tgidfile.close();
        return n_saved;
}
void AddTask_HadronicCocktailMC(Int_t particleFlag = 0, Bool_t runLightOutput = kFALSE, TString maxyset = "0.8") {

  Double_t maxy = maxyset.Atof();
  maxy         /= 100;  // needed to enable subwagon feature on grid

  // ================== GetAnalysisManager ===============================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTask_HadronicCocktailMC", "No analysis manager found.");
    return ;
  }

  // ================== GetInputEventHandler =============================
  AliVEventHandler *inputHandler=mgr->GetInputEventHandler();

  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();

  //================================================
  //========= Add task to the ANALYSIS manager =====
  //================================================
  //            find input container
  AliAnalysisTaskHadronicCocktailMC *task=NULL;
  task = new AliAnalysisTaskHadronicCocktailMC(Form("HadronicCocktailMC_%1.2f",maxy));
  task->SetMaxY(maxy);
  task->SetLightOutput(runLightOutput);
  task->SetAnalyzedParticle(particleFlag);          // switch to run: 0 - pi0, 1 - eta, 2 - pi+-

  TString                   analyzedParticle = "";
  if (particleFlag==0)      analyzedParticle = "pi0";
  else if (particleFlag==1) analyzedParticle = "eta";
  else if (particleFlag==2) analyzedParticle = "pi+-";

  //connect containers
  AliAnalysisDataContainer *coutput =
  mgr->CreateContainer(Form("HadronicCocktailMC_%s_%1.2f",analyzedParticle.Data(),maxy), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:HadronicCocktailMC",AliAnalysisManager::GetCommonFileName()));

  mgr->AddTask(task);
  mgr->ConnectInput(task,0,cinput);
  mgr->ConnectOutput(task,1,coutput);

  return;

}
Example #12
0
Int_t getsipm( Char_t *start_datetime, Char_t *end_datetime )
{

  TSQLServer *serv = TSQLServer::Connect("pgsql://phnxdb1.phenix.bnl.gov/daq", "phnxrc", "");
  
  // Create the sql query
  TString sql = "SELECT EXTRACT(EPOCH FROM read_datetime)::INT AS read_timestamp,current FROM sipm WHERE read_datetime >= \'";
  sql += start_datetime;
  sql += "\' AND read_datetime < \'";
  sql += end_datetime;
  sql += "\'";
  std::cout << "sql query: " << sql << std::endl;

  TSQLResult *res;
  res = serv->Query(sql);
  
  // Extract the result of the query into vectors
  
  Int_t nrows = res->GetRowCount();
  Int_t nfields = res->GetFieldCount();
  std::cout << "rows: " << nrows << " columns: " << nfields << std::endl;
  
  TString fieldname;
  TString field;
  TSQLRow *row;
  //  std::vector<double> read_timestamp;
  //  std::vector<double> read_current;

 for (Int_t i = 0; i < nrows; i++) {
    row = res->Next();
    for (Int_t j = 0; j < nfields; j++) {
      fieldname = TString( res->GetFieldName(j) );
      field = TString( row->GetField(j) );
      //      std::cout << "fieldname: " << fieldname << " field: " << field << std::endl;
      if ( fieldname == "read_timestamp" ) read_time_sipm[0].push_back( field.Atof() );
      if ( fieldname.Contains( "current" ) ) sipm_current[0].push_back( field.Atof() );
    }
  }

 return nrows;

}
void ProcYields::Proc_hYW(){
	Info("Proc_hYW()", "");
		
	TDirectory* dirhYW = _fout->mkdir("hYW");
	TH1F* hYW[nVARSET];
	
	TDirectory* dirVarset=NULL;
	for(Int_t iVarset=0;iVarset<nVARSET;iVarset++){
		Info("Proc_hYW()","Varset = Varset%d", iVarset+1);
		dirVarset=dirhYW->mkdir(TString::Format("Varset%d",iVarset+1));
		dirVarset->cd();
		hYW[iVarset] = new TH1F("hYW","hYW", _user.nWbins, _user.Wmin, _user.Wmax);
		hYW[iVarset]->SetXTitle("W[GeV]");
		
		//!Loop over Q2W dirs, get h5Ds and their yields
		TIter nextkey(_fout->GetListOfKeys());
		TKey *key;
		while (key = (TKey*)nextkey()) {
			TString Q2Wdirname = key->GetName();
			if(Q2Wdirname.EqualTo("hYW_Dir") || Q2Wdirname.EqualTo("hYW"))continue;
			Info("Proc_hYW()","Q2Wdir = %s", Q2Wdirname.Data());
			TString wrange = Q2Wdirname.Tokenize("_")->At(1)->GetName();
			TString wlow = wrange.Tokenize(",")->At(0)->GetName();
			wlow.Remove(0,1); //remove "["
			//Float_t w = wlow.Atof();
			Double_t w = wlow.Atof();
									
			sprintf(_hname, "%s/hY5D/Varset%d/hY5D_FULL", Q2Wdirname.Data(),iVarset+1);
			THnSparse* hY5D_FULL = (THnSparse*)_fout->Get(_hname);
			if (hY5D_FULL == NULL) cout <<"could not get h5D" << endl;
			//Float_t yield = getIntegral(hY5D_FULL);
			Double_t yield = getIntegral(hY5D_FULL);
			//hYW[iVarset]->Fill(w, yield);
			hYW[iVarset]->SetBinContent(hYW[iVarset]->FindBin(w+_intrinsic.Wbinw), yield);
			Info("Proc_hYW()","W = %f, bin# = %d, yield = %f\n", w, hYW[iVarset]->FindBin(w+_intrinsic.Wbinw), yield);
		}
	}
	Info("Proc_hYW()", "done\n");
}
Example #14
0
void KVRTGIDManager::BuildGridForAllTGID(const Char_t *idtype, Double_t xmin, Double_t xmax, Int_t ID_min, Int_t ID_max, Int_t npoints, Bool_t logscale){
	// Build a grid (KVTGIDGrid) for all the identification functions
	// of the global list. The new grids are automatically loaded in
	// gIDGridManager and are visible in the Grid Manager GUI.
	// If a function is already associated to a grid then a new grid
	// is not built. No grid is built for copies of KVTGID's made in
	// the method ReadAsciiFile(...).
	//
	// Inputs:  idtype - type of the identification for which the 
	//                   grids will be built (CI-SI, SI-CSI, CI-CSI,
	//                   SI75-SILI, ...). By default, all grids are
	//                   built
	//          xmin
	//          xmax
	//          ID_min
	//          ID_max
	//          npoints
	//          logscale - see KVTGIDGrid::Generate(...)

	if( !fIDGlobalList ) return;

	// First make a sublist of TGID found in object inheriting
	// from KVTGIDGrid in gIDGridManager
	TList  tgid_list;
	GetTGIDfromIDGridManager(&tgid_list);   
	KVIDGridManager *gm = gIDGridManager; 
	KVList *grid_list = NULL;
	if(gm){
		grid_list = gm->GetGrids();
		grid_list->Disconnect("Modified()",gm,"Modified()");
	}
	// If the TGID of the global list is not in the sublist then
	// build grid
	TIter next(fIDGlobalList);
	Bool_t IDtypeOK = strcmp(idtype,"");
	KVTGID *tgid  = NULL;
	while( (tgid = (KVTGID *)next()) ){
		if(tgid_list.FindObject(tgid)) continue;

		if(IDtypeOK){
			KVBase *idt  = NULL;
                        TSeqCollection *idt_list = (TSeqCollection* )GetIDTelescopesForTGID(tgid);
			if(!idt_list) continue;
			if( !(idt = (KVBase *)idt_list->First()) ) continue;
			SafeDelete(idt_list);
			if( strcmp(idtype,idt->GetLabel()) ) continue;
		}
		// Not built grid for a KVTGID copy
		TString tmp = tgid->GetTitle();
		if(tmp.Contains("COPY")){
			tmp.Remove(0, tmp.Index("0x"));	
			KVTGID *tmp_tgid = reinterpret_cast<KVTGID *>((Int_t)tmp.Atof());
			Warning("KVRTGIDManager::BuildGridForAllTGID","No grid built for %s (%s, %p) because it is a copy of %s (%s, %p)"
					, tgid->GetName(), tgid->ClassName(), tgid
					, tmp_tgid->GetName(), tmp_tgid->ClassName(), tmp_tgid);
			continue;
		}
		KVTGIDGrid *grid = new KVTGIDGrid(tgid);
		grid->SetOnlyZId((Bool_t)tgid->GetZorA());
		if(tgid->GetZorA()) grid->SetMassFormula(tgid->GetMassFormula());
		grid->Generate(xmax, xmin, ID_min, ID_max, npoints, logscale);
		Info("KVRTGIDManager::BuildGridForAllTGID","grid built from its TGID function %s (%s, %p)"
				, tgid->GetName(), tgid->ClassName(), tgid);
	}
	if( grid_list ) grid_list->Connect("Modified()","KVIDGridManager",gm,"Modified()");
	gm->Modified();
}
Example #15
0
Int_t getradmon( Char_t *start_datetime, Char_t *end_datetime )
{

  TSQLServer *serv = TSQLServer::Connect("pgsql://phnxdb0.phenix.bnl.gov/daq", "phnxrc", "");
  
  // Create the sql query
  
  TString columns = "id, EXTRACT(EPOCH FROM read_datetime)::INT AS read_timestamp, channel, i_n_set, i_n, v_n, i_k_set, i_k, v_k, i_s_set, i_s, v_s, i_r_set, i_r, v_r";
  
  TString sql = "SELECT ";
  sql += columns;
  sql += " FROM radmon WHERE read_datetime>=\'";
  sql += start_datetime;
  sql += "\' AND read_datetime<=\'";
  sql += end_datetime;
  sql += "\'";
  sql += " AND ABS( (i_r/i_r_set) - 1.0 ) < 0.01"; 
  sql += " AND ABS( (i_s/i_s_set) - 1.0 ) < 0.01";
  sql += " AND ABS( (i_n/i_n_set) - 1.0 ) < 0.01";
  sql += " AND v_n > 0.4 AND v_n < 2.0";
  // key
  sql += " AND v_r < 20.0 AND v_s < 20.0";
  //  sql += " AND v_r < 50.0 AND v_s < 50.0";
  sql += ";";
  cout << "sql query: " << sql << endl;

  TSQLResult *res;
  res = serv->Query(sql);

  // Extract the result of the query into vectors

  Int_t nrows = res->GetRowCount();
  Int_t nfields = res->GetFieldCount();
  cout << "rows: " << nrows << " columns: " << nfields << endl;

  TString fieldname;
  TString field;
  TSQLRow *row;

  Int_t channel = 0;
  Double_t read_timestamp;
  Double_t v_k = 0.0, v_n = 0.0, v_s = 0.0, v_r = 0.0;
  Double_t i_k = 0.0, i_n = 0.0, i_s = 0.0, i_r = 0.0;

  // zero point and temperature correction for radfet 
  // Run 14 after 373780 May 28, 2014
  //  Double_t a0[nsensor] = { 3.923, 7.513, 5.395, 6.038, 4.140, 3.306, 3.263 };
  // Beginning of Run 15 Jan 14, 2015
  //  Double_t a0[nsensor] = { 3.971, 7.871, 5.645, 7.566, 3.322, 3.108, 3.214 };
  // after adding CAN 1 and CAN 2 2015.04.15 
  //  Double_t a0[nsensor] = { 3.971, 7.871, 5.645, 7.566, 3.322, 3.108, 3.214, 3.274, 3.643 };
  Double_t a0[nsensor] = { 3.36, 3.36, 3.36, 3.36, 3.36, 3.36, 3.36, 3.36, 3.36 };

  // Here's at the beginning of Run 14 in January
  //  Double_t a0[nsensor] = { 3.78, 6.74, 4.94, 3.40, 3.45, 3.306, 3.263 };


  // zero point correction for Si detector
  // Run 14 after 373780 May 28, 2014
  //  Double_t s0[nsensor] = { 4.290, 7.220, 6.250, 2.694, 2.050, 1.054, 1.051 };
  // Begining of Run 15 Jan 14, 2015  
  //  Double_t s0[nsensor] = { 4.326, 7.078, 6.208, 3.349, 1.108, 1.048, 1.058 };
  // after adding CAN 1 and CAN 2 2015.04.15 
  //  Double_t s0[nsensor] = { 4.326, 7.078, 6.208, 3.349, 1.108, 1.048, 1.058, 1.046, 1.048 };
  // Here's the beginning of Run 14 in January
  //  Double_t s0[nsensor] = { 3.60, 6.20, 5.26, 1.16, 1.18, 1.054, 1.051 };
  Double_t s0[nsensor] = { 1.05, 1.05, 1.05, 1.05, 1.05, 1.05, 1.05, 1.05, 1.05 };

  for ( channel = 0; channel < nsensor; channel++ ) {
    V_s[channel].clear();
    V_r[channel].clear();
    R_n[channel].clear();
    T_n[channel].clear();
    R_k[channel].clear();
    R_r[channel].clear();
    read_time[channel].clear();
    V_r_corrected[channel].clear();
    V_s_corrected[channel].clear();
    dose_r[channel].clear();
    dose_s[channel].clear();
    rs_ratio[channel].clear();
  }

  Double_t v_r_c = 0.0;
  Double_t v_s_c = 0.0;

  for (Int_t i = 0; i < nrows; i++) {
    row = res->Next();
    for (Int_t j = 0; j < nfields; j++) {
      fieldname = TString( res->GetFieldName(j) );
      field = TString( row->GetField(j) );
      // Extract all columns of each row
      // std::cout << "fieldname: " << fieldname << " field: " << field << std::endl;
      if ( fieldname == "read_timestamp" ) read_timestamp = field.Atof();
      if ( fieldname == "channel" ) channel = field.Atoi();
      if ( fieldname == "v_k" ) v_k = field.Atof();
      if ( fieldname == "v_n" ) v_n = field.Atof();
      if ( fieldname == "v_s" ) v_s = field.Atof();
      if ( fieldname == "v_r" ) v_r = field.Atof();
      if ( fieldname == "i_k" ) i_k = field.Atof();
      if ( fieldname == "i_n" ) i_n = field.Atof();
      if ( fieldname == "i_s" ) i_s = field.Atof();
      if ( fieldname == "i_r" ) i_r = field.Atof();
    }
    // Save all the columns in this row in vectors for plotting
      V_s[channel].push_back(v_s);
      V_r[channel].push_back(v_r);
      R_n[channel].push_back(v_n/i_n);
      T_n[channel].push_back( temperature(v_n,i_n) );
      R_k[channel].push_back(v_k/i_k);
      R_r[channel].push_back(v_r/i_r);
      read_time[channel].push_back(read_timestamp);
      v_r_c = v_r - a0[channel];
      V_r_corrected[channel].push_back( v_r_c );
      //      std::cout << channel << ": " << v_r_c << " " << radfet_dose( &v_r_c, 0 ) << std::endl; 
      dose_r[channel].push_back( radfet_dose( &v_r_c, 0 ) );
      v_s_c = v_s - s0[channel];
      V_s_corrected[channel].push_back( v_s_c );
      dose_s[channel].push_back( si_dose( &v_s_c, 0 ) );
      if ( TMath::Abs( v_s_c ) > 1E-9 ) {
	rs_ratio[channel].push_back( (v_r - a0[channel])/v_s_c );
      } else {
	rs_ratio[channel].push_back( 0.0 );
	};
  }
  
  return nrows;
  
}
void plotxsec_CommonBins(seq_t seq/*=ACC_CORR*/, bool sim/*=kFALSE*/, int Q2Wbin/*=0*/){
  if (setup("vm")==kFALSE) return;

  gStyle->SetOptStat("nemMrRi");

  //sim or data
  TFile* fy[5];
  if (sim) memcpy(fy,_fysim,sizeof(_fysim));
  else     memcpy(fy,_fyexp,sizeof(_fyexp));
 
  //data objects for 5D yields for each Top
  int nTops=4;
  THnSparse* hY5D[nTops];

  //data object yield vs W for each top (com- and noncom-bins seperated)
  TH1F* hYW_combins[nTops];
  TLegend* l_combins = new TLegend(0.1,0.7,0.5,0.9);
  l_combins->SetHeader("Yield - 5D Method(Common Bins)");

  TH1F* hYW_noncombins[nTops];
  TLegend* l_noncombins = new TLegend(0.1,0.7,0.5,0.9);
  l_noncombins->SetHeader("Yield - 5D Method(NonCommon Bins)");

  TH1F* hYW_allbins[nTops];
  TLegend* l_allbins = new TLegend(0.1,0.7,0.5,0.9);
  l_allbins->SetHeader("Yield - 5D Method(All Bins)");

  TString wbng   = _q2w_bng.Tokenize("__")->At(1)->GetName();
  TString nwbins = wbng.Tokenize("-")->At(0)->GetName();
  TString wmin   = wbng.Tokenize("-")->At(1)->GetName();
  TString wmax   = wbng.Tokenize("-")->At(2)->GetName();
  for(int iTop=0;iTop<nTops;iTop++){
    hYW_combins[iTop] = new TH1F(TString::Format("hYW_combins_%d",iTop+1),TString::Format("hYW_combins_%d",iTop+1), nwbins.Atoi(), wmin.Atof(), wmax.Atof());
    hYW_combins[iTop]->SetXTitle("W[GeV]");
    hYW_combins[iTop]->SetMarkerStyle(20+iTop); //+5
    hYW_combins[iTop]->SetMarkerColor(2+iTop);
    l_combins->AddEntry( hYW_combins[iTop], TString::Format("%s", _topNames[iTop].Data()) );

    hYW_noncombins[iTop] = new TH1F(TString::Format("hYW_noncombins_%d",iTop+1),TString::Format("hYW_noncombins_%d",iTop+1), nwbins.Atoi(), wmin.Atof(), wmax.Atof());
    hYW_noncombins[iTop]->SetXTitle("W[GeV]");
    hYW_noncombins[iTop]->SetMarkerStyle(20+iTop); //+5
    hYW_noncombins[iTop]->SetMarkerColor(2+iTop);
    l_noncombins->AddEntry( hYW_noncombins[iTop], TString::Format("%s", _topNames[iTop].Data()) );

    hYW_allbins[iTop] = new TH1F(TString::Format("hYW_allbins_%d",iTop+1),TString::Format("hYW_allbins_%d",iTop+1), nwbins.Atoi(), wmin.Atof(), wmax.Atof());
    hYW_allbins[iTop]->SetXTitle("W[GeV]");
    hYW_allbins[iTop]->SetMarkerStyle(20+iTop); //+5
    hYW_allbins[iTop]->SetMarkerColor(2+iTop);
    l_allbins->AddEntry( hYW_allbins[iTop], TString::Format("%s", _topNames[iTop].Data()) );
  }

  //!Loop over Q2W dirs, get h5Ds and their yields only common bins!
  TIter nextkey(fy[0]->GetListOfKeys());
  TKey *key;
  int counterQ2Wbin=0;
  bool draw=kFALSE;
  if (Q2Wbin>0) draw=kTRUE;

  while (key = (TKey*)nextkey()) {
    TString Q2Wdirname = key->GetName();
    if(Q2Wdirname.EqualTo("hYW_Dir") || Q2Wdirname.EqualTo("hYW"))continue;
    printf("Processing %s\n", Q2Wdirname.Data());
    counterQ2Wbin+=1;
    
    //!if Q2Wbin option > 0, then process only the specified Q2Wbin
    if (Q2Wbin>0 && (counterQ2Wbin != Q2Wbin)) continue; 

    TString wrange = Q2Wdirname.Tokenize("_")->At(1)->GetName();
    TString wlow = wrange.Tokenize(",")->At(0)->GetName();
    wlow.Remove(0,1); //remove "["
    double w = wlow.Atof();
      
    char hname[200];                 
    sprintf(hname, "%s/hY5D/Varset1/hY5D_%s", Q2Wdirname.Data(), seqTitle[seq].Data());
    for(int iTop=0;iTop<nTops;iTop++){
      hY5D[iTop] = (THnSparse*)fy[iTop]->Get(hname);
    }

    float intg_allbins_hY5D[nTops];
    float intgErr_allbins_hY5D[nTops];
    float intg_combins_hY5D[nTops];
    float intgErr_combins_hY5D[nTops];
    float intg_noncombins_hY5D[nTops];
    float intgErr_noncombins_hY5D[nTops];
    
    myTHnTool hntool(kFALSE);
    //!First get integral over all bins
    for(int iTop=0;iTop<nTops;iTop++){
      if (iTop==2 || iTop==3) continue; //not doing for now
      hntool.GetIntegral(hY5D[iTop], intg_allbins_hY5D[iTop], intgErr_allbins_hY5D[iTop]);
    }
    //!Now get integral over only common-bins
    int nComBins = hntool.GetIntegralCommonBins(hY5D[0],hY5D[1],hY5D[2],hY5D[3],
          intg_combins_hY5D[0],intg_combins_hY5D[1],intg_combins_hY5D[2],intg_combins_hY5D[3],
          intgErr_combins_hY5D[0],intgErr_combins_hY5D[1],intgErr_combins_hY5D[2],intgErr_combins_hY5D[3],
          draw);
    printf("Number of common bins for q2w bin %s = %d\n", Q2Wdirname.Data(), nComBins);
    //printf("intgs =  %.2f,%.2f,%.2f,%.2f\n",intg_hY5D[0],intg_hY5D[1],intg_hY5D[2],intg_hY5D[3]);
    //printf("intgs Errors =  %.2f,%.2f,%.2f,%.2f\n",intgErr_hY5D[0],intgErr_hY5D[1],intgErr_hY5D[2],intgErr_hY5D[3]);
    //! Now get integral over non-common-bins
    for(int iTop=0;iTop<nTops;iTop++){
      if (iTop==2 || iTop==3) continue; //not doing for now
      intg_noncombins_hY5D[iTop] = intg_allbins_hY5D[iTop] - intg_combins_hY5D[iTop];
      intgErr_noncombins_hY5D[iTop] = TMath::Sqrt(TMath::Power(intgErr_allbins_hY5D[iTop],2)+TMath::Power(intgErr_combins_hY5D[iTop],2));
    }


    for(int iTop=0;iTop<nTops;iTop++){
      hYW_allbins[iTop]->SetBinContent(hYW_allbins[iTop]->FindBin(w+.005), intg_allbins_hY5D[iTop]); //+5Mev = _instrinsic.Wbinw
      hYW_allbins[iTop]->  SetBinError(hYW_allbins[iTop]->FindBin(w+.005), intgErr_allbins_hY5D[iTop]); //+5Mev = _instrinsic.Wbinw
      hYW_combins[iTop]->SetBinContent(hYW_combins[iTop]->FindBin(w+.005), intg_combins_hY5D[iTop]); //+5Mev = _instrinsic.Wbinw
      hYW_combins[iTop]->  SetBinError(hYW_combins[iTop]->FindBin(w+.005), intgErr_combins_hY5D[iTop]); //+5Mev = _instrinsic.Wbinw
      hYW_noncombins[iTop]->SetBinContent(hYW_noncombins[iTop]->FindBin(w+.005), intg_noncombins_hY5D[iTop]); //+5Mev = _instrinsic.Wbinw
      hYW_noncombins[iTop]->  SetBinError(hYW_noncombins[iTop]->FindBin(w+.005), intgErr_noncombins_hY5D[iTop]); //+5Mev = _instrinsic.Wbinw
    }
  }
  TCanvas* cy = new TCanvas();
  cy->Divide(3,1);
  //if (seq==HOLE) cy->SetLogy();
  for(int iTop=0;iTop<nTops;iTop++){
    if (iTop==0) {
      //if (seq==HOLE) hYW_combins[iTop]->SetMinimum(1);
      cy->cd(1);
      if (seq==HOLE) {
        gPad->SetLogy();
        hYW_combins[iTop]->SetMinimum(1);
      }
      hYW_combins[iTop]->Draw("p");
      cy->cd(2);
      if (seq==HOLE) {
        gPad->SetLogy();
        hYW_noncombins[iTop]->SetMinimum(1);
      }
      hYW_noncombins[iTop]->Draw("p");
      cy->cd(3);
      if (seq==HOLE) {
        gPad->SetLogy();
        hYW_allbins[iTop]->SetMinimum(1);
      }
      hYW_allbins[iTop]->Draw("p");
    }else {
      cy->cd(1);
      hYW_combins[iTop]->Draw("p sames");
      cy->cd(2);
      hYW_noncombins[iTop]->Draw("p sames");
      cy->cd(3);
      hYW_allbins[iTop]->Draw("p sames");

    }
  }
  cy->cd(1);
  l_combins->Draw("same");
  cy->cd(2);
  l_noncombins->Draw("same");
  cy->cd(3);
  l_allbins->Draw("same");

}
Example #17
0
void keys(TString sam="0", TString smooth = "100") {
  gSystem->Load("libHtml");
  gSystem->Load("libMinuit");
  gSystem->Load("libRooFitCore.so");
  gSystem->Load("libRooFitModels.so");
  using namespace RooFit;
  time_t start,end;
  time (&start);
  double dif;
  RooRealVar mmiss2("candM2","candM2",-4,12);
  RooRealVar pstarl("candPstarLep","candPstarLep",0.,2.4);

  RooArgSet myVars(mmiss2,pstarl);

  TString inputfile = "fitSamples/pdfSample"; inputfile += sam; inputfile += ".root";
  cout << "File = " << inputfile << endl;	
  TChain c("ntp1");
  c.Add(inputfile);
  RooDataSet  data("data","data",myVars);

  Int_t MCType,MCSubmode,MCDssmode,MCD,MCPions,MCCombB,MCCombDs,MCDoubleSL,
    candTruLep,candDstarType,isBzero,isSP6,MCTaumode,trueLepCharge;
  Float_t candM2,candPstarLep;
  Float_t truePPi0,trueDssPPi0,CTL,CTV,Chi,Q2,trueDmass;
  c.SetBranchAddress("MCType",&MCType);
  c.SetBranchAddress("MCSubmode",&MCSubmode);
  c.SetBranchAddress("MCDssmode",&MCDssmode);
  c.SetBranchAddress("MCD",&MCD);
  c.SetBranchAddress("MCPions",&MCPions);
  c.SetBranchAddress("MCCombB",&MCCombB);
  c.SetBranchAddress("MCCombDs",&MCCombDs);
  c.SetBranchAddress("MCDoubleSL",&MCDoubleSL);
  c.SetBranchAddress("candLepTru",&candTruLep);
  c.SetBranchAddress("candDstarType",&candDstarType);
  c.SetBranchAddress("isBzero",&isBzero);
  c.SetBranchAddress("isSP6",&isSP6);
  c.SetBranchAddress("MCTaumode",&MCTaumode);
  c.SetBranchAddress("truePPi0",&truePPi0);
  c.SetBranchAddress("trueDssPPi0",&trueDssPPi0);
  c.SetBranchAddress("trueCTL",&CTL);
  c.SetBranchAddress("trueCTV",&CTV);
  c.SetBranchAddress("trueChi",&Chi);
  c.SetBranchAddress("trueQ2",&Q2);
  c.SetBranchAddress("trueLepCharge",&trueLepCharge);
  c.SetBranchAddress("trueDmass",&trueDmass);
  c.SetBranchAddress("candM2",&candM2);
  c.SetBranchAddress("candPstarLep",&candPstarLep);
  TRandom3 rand; int ran;
  int transform = 1;
  TCanvas mm("mm","KEYS fits to mmiss-pstarl",1200,800);
  gStyle->SetPalette(1);
  double All = 8;
  TH2F rotated("rotated","Rotated m^{2}_{miss}-p*_{l}",200,-All,All,200,-All,All);
  TH2F ori("ori","Original m^{2}_{miss}-p*_{l}",200,-All,All,200,-All,All);
  //TH2F totcov("ori2","Original m^{2}_{miss}-p*_{l}",200,-All,All,200,-All,All);
  double r11, r12, Xmean, Ymean;
  double x[] = {-2,-1,1,2};
  double y[] = {-4,-2,2,4};
  if(transform ==1){
    c.Draw("candPstarLep:candM2>>cov(200,-4,12,200,0,2.4)","","contz");
    TH2F *totcov = (TH2F*)gDirectory->Get("cov");
    //for(int i=0;i<4;i++)totcov.Fill(x[i],y[i]);
    double xx = totcov->GetRMS(1); xx = xx*xx;
    double yy = totcov->GetRMS(2); yy = yy*yy;
    double xy = totcov->GetCovariance();
    Xmean = totcov->GetMean(1);
    Ymean = totcov->GetMean(2);
    double lambda = (-sqrt(xx*xx-2*xx*yy+4*xy*xy+yy*yy)+xx+yy)/2;
    double lambda2 = (sqrt(xx*xx-2*xx*yy+4*xy*xy+yy*yy)+xx+yy)/2;
    if(lambda2>lambda) lambda = lambda2;
    r11 = (lambda-yy)/xy;
    r12 = -1/sqrt(r11*r11+1);
    r11 = -r11/sqrt(r11*r11+1);
    if(r12*r11>0&&r12<0 || r12*r11<0&&r11<0){
      r12 = -r12;
      r11 = -r11;
    }
    cout<<"RMSx "<<xx<<", RMSy "<<yy<<", lambda "<<lambda<<" and covariance "<<xy<<endl;
  }
  double mmp, plp;
  double entries = c.GetEntries();
  //entries = 4;
  for (int evt = 0 ; evt < entries; evt ++) {
    ran = rand.Uniform(entries);
    //c.GetEvent(ran);
    c.GetEvent(evt);
    double Mx = candM2-Xmean, Py = candPstarLep-Ymean;
    mmp = r11*(Mx)+r12*(Py);
    plp = -r12*(Mx)+r11*(Py);
    ori.Fill(Mx,Py);
    rotated.Fill(mmp,plp);
    mmiss2.setVal(candM2);
    pstarl.setVal(candPstarLep);
//     if (MCType == 0)
//       totWeight.setVal(myWM->getCombWeight(MCCombB,MCCombDs,MCDoubleSL,candTruLep));
//     else
//       totWeight.setVal(myWM->getEventWeight(candType,candDstarType,MCType,MCSubmode,MCDssmode,MCD,MCPions,
// 					    isBzero,isSP6,MCTaumode,truePPi0,trueDmass,CTL,CTV,Chi,Q2,
// 					    trueLepCharge,candM2));
    data.add(RooArgSet(mmiss2,pstarl));
  }
  //data.setWeightVar(totWeight);
  ori.Draw("contz");
  mm.SaveAs("original.eps");
  rotated.Draw("contz");
  mm.SaveAs("rotated.eps");
  cout<<"("<<r11<<", "<<r12<<") and covariance "<<rotated.GetCovariance()<<endl;
  return;

  double smoo = smooth.Atof()/100.;
  Roo2DKeysPdf DPpdf("DPpdf","DPpdf",mmiss2,pstarl,data,"av",smoo);
  time (&end);dif = difftime (end,start);
  cout<<dif<<" seconds after finding the KEYS function"<<endl;
  time (&start);
  int ntotbin = 800;
  TH2F *h2 = new TH2F("h2","KEYS",ntotbin,-4,12,ntotbin,0,2.4);
  DPpdf.fillHistogram(h2,RooArgList(mmiss2,pstarl));
  TString hname = "AWG82/results/keys/root/hKeys"; hname += sam; hname += "_"; hname += smooth; hname += ".root";
  TFile* hfile = new TFile(hname,"RECREATE"); 
  h2->Write();
  hfile->Close();
  cout<<"KEYS histogram saved in "<<hname<<endl;
  RooDataHist* Rdh2 = new RooDataHist("Rdh2","KEYS",RooArgList(mmiss2,pstarl),h2);
  RooHistPdf* Rh2 = new RooHistPdf("Rh2","KEYS",RooArgList(mmiss2,pstarl),*Rdh2,2);
  time (&end);dif = difftime (end,start);
  cout<<dif<<" seconds after making histogram"<<endl;
  time (&start);

  Float_t xlow,xhigh;
  Int_t nbinx,nbiny,Sam = sam.Atoi();
  xlow = -4;
  xhigh = 12;
  nbinx = 80;
  nbiny = 80;
  if (Sam==0 || Sam==2 || Sam==10 || Sam==12 || Sam == 20 || Sam == 23 || Sam == 26 || Sam == 29) {
    xlow = -2; xhigh = 4;
    if (Sam > 12) {nbinx = 40; nbiny = 40;}
  }
  else if (Sam==1 || Sam==11) {
    xlow = -2; xhigh = 6;
  }
  if (Sam==6 || Sam==7 || Sam==16 || Sam==17) {
    nbinx = 40; nbiny = 40;
  }
  if (Sam==8 || Sam==18) {
    xhigh = 4; nbinx = 40; nbiny = 40;
  }
  if (Sam==9 || Sam==19) {
    nbinx = 40; nbiny = 40;
  }
  if (Sam==21 || Sam==22 || Sam==24 || Sam==25 || Sam==27 || Sam==28 || Sam==30 || Sam==31) {
    xhigh = 8; nbinx = 40; nbiny = 20;
  }
  if (Sam > 31) {
    nbinx = 40; nbiny = 20;
  }

  TString M2titles[] = {"0 < p*_{l} < 1 GeV","1 < p*_{l} < 1.4 GeV","1.4 < p*_{l} < 1.8 GeV",
		      "1.8 < p*_{l} < 2.4 GeV","0 < p*_{l} < 2.4 GeV"};
  TString Pltitles[] = {"-4 < m^{2}_{miss} < 1.5 GeV^{2}","1.5 < m^{2}_{miss} < 12 GeV^{2}",
			"-4 < m^{2}_{miss} < 12 GeV^{2}"};
  TString M2cuts[] = {"candPstarLep<1","candPstarLep>1&&candPstarLep<1.4",
		      "candPstarLep>1.4&&candPstarLep<1.8","candPstarLep>1.8&&candPstarLep<2.4", ""};
  TString Plcuts[] = {"candM2<1.5","candM2>=1.5",""};
  double limits[] = {0, 1, 1.4, 1.8, 2.4};
  int binlim[5];
  for(int i=0;i<5;i++) binlim[i] = limits[i]/2.4*ntotbin;

  TString psname = "AWG82/results/keys/eps/eps2Keys"; psname+=sam; psname+="_";
  psname += smooth; psname += ".ps";
  double tot = 0;
  mm.Print(psname+"[");
  TH1F *hm2[5], *m2[5], *hpl[3], *pl[3];
  TString M2names[5], Plnames[3];
  for(int i=0;i<5;i++){
    M2names[i] = "hm2_"; M2names[i] += i;
    hm2[i] = new TH1F(M2names[i],M2titles[i],ntotbin,-4,12); 
    if(i<3) {
      Plnames[i] = "hpl_"; Plnames[i] += i;
      hpl[i] = new TH1F(Plnames[i],Pltitles[i],ntotbin,0,2.4); 
    }
  }    
  for(int i=0;i<5;i++){
    TString hname = "m2"; hname += i;
    TString vari = "candM2>>"; vari+=hname; vari+="("; vari+= nbinx; vari+=",";vari+= xlow; 
    vari+=",";vari+= xhigh; vari+=")";
    c.Draw(vari,M2cuts[i]);
    m2[i] = (TH1F*)gDirectory->Get(hname);
    m2[i]->SetXTitle("m^{2}_{miss} [GeV^{2}]");
    m2[i]->SetTitle(M2titles[i]);
    m2[i]->Sumw2();
    m2[i]->SetMarkerStyle(20);
    m2[i]->SetMarkerSize(1);
    gStyle->SetOptStat(0);
    if(i<4){
      for(int j=1; j<ntotbin+1; j++){
	double binVal = 0;
	for(int binp = binlim[i]+1; binp < binlim[i+1]+1; binp++){
	  binVal += h2->GetBinContent(j,binp)*entries*ntotbin*(xhigh-xlow)/nbinx/16;	
	}
	hm2[i]->SetBinContent(j,binVal);
      }
    } 
    hm2[i]->SetLineColor(4);
    hm2[i]->SetLineWidth(2);
    if(i<4) hm2[4]->Add(hm2[i]);
  }
  int plbinlim[3] = {0,ntotbin*5.5/16,ntotbin};
  for(int i=0;i<3;i++){
    TString hname = "pl"; hname += i;
    TString vari = "candPstarLep>>"; vari+=hname; vari+="("; vari+= nbiny; vari+=",0,2.4)";
    c.Draw(vari,Plcuts[i]);
    pl[i] = (TH1F*)gDirectory->Get(hname);
    pl[i]->SetXTitle("p*_{l} [GeV]");
    pl[i]->SetTitle(Pltitles[i]);
    pl[i]->Sumw2();
    pl[i]->SetMarkerStyle(20);
    pl[i]->SetMarkerSize(1);
    gStyle->SetOptStat(0);
    if(i<2){
      for(int j=1; j<ntotbin+1; j++){
	double binVal = 0;
	for(int binp = plbinlim[i]+1; binp < plbinlim[i+1]+1; binp++){
	  binVal += h2->GetBinContent(binp,j)*entries*ntotbin/nbiny;	
	}
	hpl[i]->SetBinContent(j,binVal);
      }
    }
    hpl[i]->SetLineColor(4);
    hpl[i]->SetLineWidth(2);
    if(i<2) hpl[2]->Add(hpl[i]);
  }
  m2[4]->Draw("e1"); hm2[4]->Draw("c same"); mm.Print(psname);
  pl[2]->Draw("e1"); hpl[2]->Draw("c same"); mm.Print(psname);
  for(int i=0;i<4;i++){
    m2[i]->Draw("e1"); hm2[i]->Draw("c same"); mm.Print(psname);
  }
  for(int i=0;i<2;i++){
    pl[i]->Draw("e1"); hpl[i]->Draw("c same"); mm.Print(psname);
  }
  mm.Print(psname+"]");
  time (&end);dif = difftime (end,start);
  cout<<dif<<" seconds after plotting data. Written "<<psname<<endl;
  return; 

} 
Example #18
0
Int_t getscaler( Int_t scalervector, Int_t scalerchannel, Char_t *start_datetime, Char_t *end_datetime )
{

  TSQLServer *serv = TSQLServer::Connect("mysql://phnxdb1.phenix.bnl.gov/scalers", "phoncs", "phenix7815");
  
  // Create the sql query
  
  Int_t which_table, which_rate;

  which_table = (scalerchannel/16) + 1;
  which_rate = ( scalerchannel%16 ) + 1;
  
  TString scaler_field_name = "rate";
  scaler_field_name += which_rate;

  TString columns = "UNIX_TIMESTAMP(rs.read_datetime) AS read_timestamp,rs.";
  columns += scaler_field_name;
  columns += ", (@csum:[email protected]+60.0*rs.";
  columns += scaler_field_name;
  columns += ") as cum";
  
  TString sql = "SELECT ";
  sql += columns;
  sql += " FROM rhicscaler";
  sql += which_table;
  sql += " AS rs WHERE";
  sql += " rs.read_datetime>=\"";
  sql += start_datetime;
  sql += "\" AND rs.read_datetime<=\"";
  sql += end_datetime;
  sql += "\";";

  cout << "sql query: " << sql << endl;

  TSQLResult *res;
  res = serv->Query("SET @csum=0.0;");
  res = serv->Query(sql);

  // Extract the result of the query into vectors

  Int_t nrows = res->GetRowCount();
  Int_t nfields = res->GetFieldCount();
  cout << "rows: " << nrows << " columns: " << nfields << endl;

  TString fieldname;
  TString field;
  TSQLRow *row;

  Double_t read_timestamp;
  Double_t cum;
  Double_t running_sum = 0.0;
  Double_t summand = 0.0;

  sread_time[scalervector].clear();
  cum_scaler_db[scalervector].clear();
  cum_scaler_sum[scalervector].clear();

  for (Int_t i = 0; i < nrows; i++) {
    row = res->Next();
    for (Int_t j = 0; j < nfields; j++) {
      fieldname = TString( res->GetFieldName(j) );
      field = TString( row->GetField(j) );
      // Extract all columns of each row
      // std::cout << "fieldname: " << fieldname << " field: " << field << std::endl;
      if ( fieldname == "read_timestamp" ) read_timestamp = field.Atof();
      if ( fieldname == "cum" ) cum = field.Atof();
      if ( fieldname == scaler_field_name ) summand = field.Atof();
    }
    // Save all the columns in this row in vectors for plotting
    sread_time[scalervector].push_back(read_timestamp);
    cum_scaler_db[scalervector].push_back(cum);
    running_sum += 60.0*summand;
    cum_scaler_sum[scalervector].push_back(running_sum);
  }
  
  return nrows;
  
}
void plot_pad_size_in_layer(TString digiPar="trd.v13/trd_v13g.digi.par", Int_t nlines=1, Int_t nrows_in_sec=0, Int_t alllayers=1) 
{

  gStyle->SetPalette(1,0);
  gROOT->SetStyle("Plain");
  gStyle->SetPadTickX(1);                        
  gStyle->SetPadTickY(1); 
  gStyle->SetOptStat(kFALSE);
  gStyle->SetOptTitle(kFALSE);

  Bool_t read = false;
  TH2I *fLayerDummy = new TH2I("LayerDummy","",1200,-600,600,1000,-500,500);
  fLayerDummy->SetXTitle("x-coordinate [cm]");
  fLayerDummy->SetYTitle("y-coordinate [cm]");
  fLayerDummy->GetXaxis()->SetLabelSize(0.02);
  fLayerDummy->GetYaxis()->SetLabelSize(0.02);
  fLayerDummy->GetZaxis()->SetLabelSize(0.02);
  fLayerDummy->GetXaxis()->SetTitleSize(0.02);
  fLayerDummy->GetXaxis()->SetTitleOffset(1.5);
  fLayerDummy->GetYaxis()->SetTitleSize(0.02);
  fLayerDummy->GetYaxis()->SetTitleOffset(2);
  fLayerDummy->GetZaxis()->SetTitleSize(0.02);
  fLayerDummy->GetZaxis()->SetTitleOffset(-2);

  TString title;
  TString title1, title2, title3;
  TString buffer;
  TString firstModule = "";
  Int_t blockCounter(0), startCounter(0); // , stopCounter(0);
  Double_t msX(0), msY(0), mpX(0), mpY(0), mpZ(0), psX(0), psY(0);
  Double_t ps1X(0), ps1Y(0), ps2X(0), ps2Y(0), ps3X(0), ps3Y(0);
  Int_t modId(0), layerId(0);
  Double_t sec1(0), sec2(0), sec3(0);
  Double_t row1(0), row2(0), row3(0);
  std::map<float, TCanvas*> layerView;// map key is z-position of modules
  std::map<float, TCanvas*>::iterator it;
  ifstream digipar;

  digipar.open(digiPar.Data(), ifstream::in);
  while (digipar.good()) {
    digipar >> buffer;
    //cout << "(" << blockCounter << ")    " << buffer << endl;
    if (blockCounter == 19)
      firstModule = buffer;
    if (buffer == (firstModule + ":")){
      //cout << buffer << " <===========================================" << endl;
      read = true;
    }
    if (read) {
      startCounter++;
      if (startCounter == 1)   // position of module position in x
      {
	modId = buffer.Atoi();
        layerId = (modId & (15 << 4)) >> 4;  // from CbmTrdAddress.h
      }

      if (startCounter == 5)   // position of module position in x
	mpX = buffer.Atof();
      if (startCounter == 6)   // position of module position in y
	mpY = buffer.Atof();
      if (startCounter == 7)   // position of module position in z
	mpZ = buffer.Atof();
      if (startCounter == 8)   // position of module size in x
	msX = buffer.Atof();
      if (startCounter == 9)   // position of module size in y
	msY = buffer.Atof();

      if (startCounter == 12)   // sector 1 size in y
	sec1 = buffer.Atof();
      if (startCounter == 13)   // position of pad size in x - do not take the backslash (@14)
	ps1X = buffer.Atof();
      if (startCounter == 15)   // position of pad size in y
	ps1Y = buffer.Atof();

      if (startCounter == 17)   // sector 2 size in y
	sec2 = buffer.Atof();
      if (startCounter == 18)   // position of pad size in x
      {
	ps2X = buffer.Atof();
        psX = ps2X;   // for backwards compatibility - sector 2 is default sector
      }
      if (startCounter == 19)   // position of pad size in y
      {
	ps2Y = buffer.Atof();
        psY = ps2Y;   // for backwards compatibility - sector 2 is default sector
      }

      if (startCounter == 21)   // sector 3 size in y
	sec3 = buffer.Atof();
      if (startCounter == 22)   // position of pad size in x
	ps3X = buffer.Atof();
      if (startCounter == 23)   // position of pad size in y
	ps3Y = buffer.Atof();

//      if (startCounter == 23)   // last element
//      {
//        printf("moduleId         : %d, %d\n", modId, layerId);
//        printf("pad size sector 1: (%.2f cm, %.2f cm) pad area: %.2f cm2\n", ps1X, ps1Y, ps1X*ps1Y);
//        printf("pad size sector 2: (%.2f cm, %.2f cm) pad area: %.2f cm2\n", ps2X, ps2Y, ps2X*ps2Y);
//        printf("pad size sector 3: (%.2f cm, %.2f cm) pad area: %.2f cm2\n", ps3X, ps3Y, ps3X*ps3Y);
//        printf("rows per sector  : %.1f %.1f %.1f\n", sec1/ps1Y, sec2/ps2Y, sec3/ps3Y);
//        printf("\n");
//      }

      //printf("module position: (%.1f, %.1f, %.1f) module size: (%.1f, %.1f) pad size: (%.2f, %.2f) pad area: %.2f\n",mpX,mpY,mpZ,2*msX,2*msY,psX,psY,psX*psY);

      if (startCounter == 23) { // if last element is reached
	startCounter = 0; // reset

        if ( alllayers == 0 )   
          if ( !((layerId == 0) || (layerId == 4) || (layerId == 8)) )   // plot only 1 layer per station
            continue;

        row1 = sec1 / ps1Y;
        row2 = sec2 / ps2Y;
        row3 = sec3 / ps3Y;

	it = layerView.find(mpZ);
	if (it == layerView.end()){	
	  //	  title.Form("pad_size_layer_at_z_%.2fm",mpZ);  
	  title.Form("%02d_pad_size_layer%02d", layerId, layerId);  
	  layerView[mpZ] = new TCanvas(title,title,1200,1000);
	  fLayerDummy->DrawCopy("");

        // now print cm2 in the center
	layerView[mpZ]->cd();
	title.Form("cm^{2}");  // print cm2
	TPaveText *text = new TPaveText(0 - 28.5,
					0 - 28.5,
					0 + 28.5,
					0 + 28.5
					);
	text->SetFillStyle(1001);
	text->SetLineColor(1);
        text->SetFillColor(kWhite);
	text->AddText(title);
	text->Draw("same");
	}

        // print pad size in each module
	layerView[mpZ]->cd();
	//	title.Form("%2.0fcm^{2}",psX*psY);  // print pad size
	//	title.Form("%.0f",psX*psY);  // print pad size - 1 digit
	TPaveText *text = new TPaveText(mpX - msX,
					mpY - msY,
					mpX + msX,
					mpY + msY
					);
	text->SetFillStyle(1001);
	text->SetLineColor(1);
	//        text->SetFillColor(kViolet);

	// vary background color
//        if ((int)(psX*psY+.5) == 2)
//        {
//          text->SetFillColor(kOrange + 9);
//        } 
//        else 
        if (psX*psY <= 1.1)
        {
          text->SetFillColor(kOrange + 10);
        }
        else if (psX*psY <= 2.1)
        {
          text->SetFillColor(kOrange -  3);
        }
        else if (psX*psY <= 3.1)
        {
          text->SetFillColor(kOrange -  4);
        }
        else if (psX*psY <= 5)
        {
          text->SetFillColor(kOrange + 10 - ((int)(psX*psY+.5)-1) * 2);
//        printf("%2.1f: %d\n", psX*psY, 10 - ((int)(psX*psY+.5)-1) * 2);
        } 
        else if (psX*psY <= 10)
	{
          text->SetFillColor(kSpring + 10 - ((int)(psX*psY+.5)-4) * 2);
//        printf("%2.1f: %d\n", psX*psY, 10 - ((int)(psX*psY+.5)-4) * 2);
        } 
        else if (psX*psY > 10)
	{
          text->SetFillColor(kGreen);
//        printf("%2.1f: %s\n", psX*psY, "green");
        } 

        if (nrows_in_sec == 1)   // print number of rows in sector
	{
   	  title1.Form("%3.1f - %2.0f", ps1X*ps1Y, row1);  // print pad size and nrows - 2 digits - sector 1
	  title2.Form("%3.1f - %2.0f", ps2X*ps2Y, row2);  // print pad size and nrows - 2 digits - sector 2
	  title3.Form("%3.1f - %2.0f", ps3X*ps3Y, row3);  // print pad size and nrows - 2 digits - sector 3
	}
        else
	{
   	  title1.Form("%3.1f",ps1X*ps1Y);  // print pad size - 2 digits - sector 1
	  title2.Form("%3.1f",ps2X*ps2Y);  // print pad size - 2 digits - sector 2
	  title3.Form("%3.1f",ps3X*ps3Y);  // print pad size - 2 digits - sector 3
	}

        if (nlines==1)   // plot pad size for central sector only
	{
	  text->AddText(title2);
        }
        else   // plot pad size for all 3 sectors
	{
	  text->AddText(title1);
	  text->AddText(title2);
	  text->AddText(title3);
        }
	text->Draw("same");
	//layerView[mpZ]->Update();
      }
    }  
    blockCounter++;
  }
void plotxsec_CommonBins(seq_t seq/*=ACC_CORR*/, bool sim/*=kFALSE*/, int Q2Wbin/*=0*/){
  if (setup("vm")==kFALSE) return;

  //! Stats. Box option for this function
  if (Q2Wbin>0) gStyle->SetOptStat("nemMrRi");
  else          gStyle->SetOptStat(0);
  
  //!sim or data
  TFile* fy[5];
  if (sim) memcpy(fy,_fysim,sizeof(_fysim));
  else     memcpy(fy,_fyexp,sizeof(_fyexp));
 
  //!data objects for 5D yields for each Top
  THnSparse* hY5D[nTOP];

  //![Q2,W] binning information
  TString wbng   = _q2w_bng.Tokenize("__")->At(1)->GetName();
  TString nwbins = wbng.Tokenize("-")->At(0)->GetName();
  TString wmin   = wbng.Tokenize("-")->At(1)->GetName();
  TString wmax   = wbng.Tokenize("-")->At(2)->GetName();

  //! Some constants needed to define good variable names
  //! Yield(all-bins)= Yield(com-bins) + Yield(noncom-bins)
  const int kNumBinGrps = 3;
  enum BinGrps {kAll=0,kCom=1,kNonCom=2};
  TString bingrp_name[kNumBinGrps] ={"all_bins","com_bins","noncom_bins"};
  TString bingrp_title[kNumBinGrps]={"All Bins", "Common Bins", "NonCommon Bins"};

  //! Per Q2W bin: Data Objects for Yield vs W for each Top and each BinGrp therein
  TH1F* hYvW[nTOP][kNumBinGrps];
  
  TLegend* leg[kNumBinGrps];
  for (int ibingrp=0;ibingrp<kNumBinGrps;ibingrp++){
      leg[ibingrp] = new TLegend(0.1,0.7,0.5,0.9);
      leg[ibingrp]->SetHeader(TString::Format("%s Yield(%s)", seqTitle[seq].Data(), bingrp_title[ibingrp].Data()));
  }

  for(int iTop=0;iTop<nTOP;iTop++){
    for (int ibingrp=0;ibingrp<kNumBinGrps;ibingrp++){
      //TString hname = TString::Format("hYvW_%d_%s",iTop+1,bingrp_name[ibingrp].Data());
      //TString hname = TString::Format("hYvW_%s",bingrp_name[ibingrp].Data());
      TString hname = TString::Format("hYvW");
      TString htitle = hname;
      hYvW[iTop][ibingrp] = new TH1F(hname,htitle, nwbins.Atoi(), wmin.Atof(), wmax.Atof());
      hYvW[iTop][ibingrp]->SetXTitle("W[GeV]");
      hYvW[iTop][ibingrp]->SetMarkerStyle(20+iTop); //+5
      hYvW[iTop][ibingrp]->SetMarkerColor(2+iTop);
      leg[ibingrp]->AddEntry( hYvW[iTop][ibingrp], TString::Format("%s", _topNames[iTop].Data()) );
    }
  }
  
 
  //!Loop over Q2W dirs, get h5Ds and their yields only common bins!
  TIter nextkey(fy[0]->GetListOfKeys());
  TKey *key;
  int counterQ2Wbin=0;
  bool draw=kFALSE;
  if (Q2Wbin>0) draw=kTRUE;

  while (key = (TKey*)nextkey()) {
    TString Q2Wdirname = key->GetName();
    if(Q2Wdirname.EqualTo("hYW_Dir") || Q2Wdirname.EqualTo("hYW"))continue;
    printf("Processing %s\n", Q2Wdirname.Data());
    counterQ2Wbin+=1;
    
    //!if Q2Wbin option > 0, then process only the specified Q2Wbin
    if (Q2Wbin>0 && (counterQ2Wbin != Q2Wbin)) continue; 

    TString wrange = Q2Wdirname.Tokenize("_")->At(1)->GetName();
    TString wlow = wrange.Tokenize(",")->At(0)->GetName();
    wlow.Remove(0,1); //remove "["
    double w = wlow.Atof();
      
    char hname[200];                 
    sprintf(hname, "%s/hY5D/Varset1/hY5D_%s", Q2Wdirname.Data(), seqTitle[seq].Data());
    for(int iTop=0;iTop<nTOP;iTop++){
      hY5D[iTop] = (THnSparse*)fy[iTop]->Get(hname);
    }

    //! Reset Data structures 
    float    intg_hY5D[nTOP][kNumBinGrps] = {0.0};
    float intgErr_hY5D[nTOP][kNumBinGrps] = {0.0};
    
    myTHnTool hntool(kFALSE);

    //!F1. Get integral over all bins
    //printf("Integral over all bins\n");
    for(int iTop=0;iTop<nTOP;iTop++){
      if (iTop==2 || iTop==3) continue; //not doing for now
      hntool.GetIntegral(hY5D[iTop], intg_hY5D[iTop][kAll], intgErr_hY5D[iTop][kAll]);
      //printf("Top%d = %f\n",iTop+1,intg_hY5D[iTop][kAll]);
    }

    //!2. Get integral over only common-bins
    //NOTE, in hntool.GetIntegralCommonBins(), currently, hY5D[2] & hY5D[3] are not considered
    int num_combins = hntool.GetIntegralCommonBins(
                  hY5D[0],              hY5D[1],              hY5D[2],              hY5D[3],
             intg_hY5D[0][kCom],   intg_hY5D[1][kCom],   intg_hY5D[2][kCom],   intg_hY5D[3][kCom],
          intgErr_hY5D[0][kCom],intgErr_hY5D[1][kCom],intgErr_hY5D[2][kCom],intgErr_hY5D[3][kCom],
          draw);
    printf("Number of common bins for q2w bin %s = %d\n", Q2Wdirname.Data(), num_combins);
    
    //!2. Get integral over non-common-bins
    for(int iTop=0;iTop<nTOP;iTop++){
      if (iTop==2 || iTop==3) continue; //not doing for now
      intg_hY5D[iTop][kNonCom] = intg_hY5D[iTop][kAll] - intg_hY5D[iTop][kCom];
      intgErr_hY5D[iTop][kNonCom] = TMath::Sqrt(TMath::Power(intgErr_hY5D[iTop][kAll],2)+
                                                TMath::Power(intgErr_hY5D[iTop][kCom],2));
    }

    //! Now fill Histogram Objects
    for(int iTop=0;iTop<nTOP;iTop++){
      if (iTop==2 || iTop==3) continue; //not doing for now
      for (int ibingrp=0; ibingrp<kNumBinGrps;ibingrp++){
        hYvW[iTop][ibingrp]->SetBinContent(hYvW[iTop][ibingrp]->FindBin(w+.005), intg_hY5D[iTop][ibingrp]); //+5Mev = _instrinsic.Wbinw
        hYvW[iTop][ibingrp]->  SetBinError(hYvW[iTop][ibingrp]->FindBin(w+.005), intgErr_hY5D[iTop][ibingrp]); //+5Mev = _instrinsic.Wbinw
      }
    }
  }

  //!Now Draw the Histogram Objects
  TString cname = TString::Format("%s Yield Analysis", seqTitle[seq].Data());
  TCanvas* cy = new TCanvas(cname, cname);
  cy->Divide(kNumBinGrps,1);
  for(int iTop=0;iTop<nTOP;iTop++){
    if (iTop==2 || iTop==3) continue; //not doing for now
    for (int ibingrp=0; ibingrp<kNumBinGrps;ibingrp++){
      cy->cd(ibingrp+1);
      if (iTop==0) {
        if (seq==HOLE) {
          gPad->SetLogy();
          hYvW[iTop][ibingrp]->SetMinimum(.0001);
        }else{
          hYvW[iTop][ibingrp]->SetMinimum(0);
          //set max of histograms as per [Top=2][kAll]
          float max_t1 = hYvW[0][kAll]->GetBinContent(hYvW[0][kAll]->GetMaximumBin()) + 100;
          float max_t2 = hYvW[1][kAll]->GetBinContent(hYvW[1][kAll]->GetMaximumBin()) + 100;
          if (max_t2>max_t1) hYvW[iTop][ibingrp]->SetMaximum(max_t2);
          //printf("max_t2 = %f\n",max_t2);
        }
        hYvW[iTop][ibingrp]->Draw("p");
      }else {
        hYvW[iTop][ibingrp]->Draw("p sames");
      }
    }
  }
  //!Finally draw the Legend
  for (int ibingrp=0; ibingrp<kNumBinGrps;ibingrp++){
    cy->cd(ibingrp+1);
    leg[ibingrp]->Draw("same");
  }
}
Example #21
0
int main(int argc,char *argv[])
{
  string usage = "\nCNVnator ";
#ifdef CNVNATOR_VERSION
  usage += CNVNATOR_VERSION;
#else
  usage += "v???";
#endif
  usage += "\n\nUsage:\n";
  usage += argv[0];
  usage += " -root out.root  [-genome name] [-chrom 1 2 ...] -tree  file1.bam ...\n";
  usage += argv[0];
  usage += " -root out.root  [-genome name] [-chrom 1 2 ...] -merge file1.root ...\n";
  usage += argv[0];
  usage += " -root file.root [-genome name] [-chrom 1 2 ...] [-d dir] -his bin_size\n";
  usage += argv[0];
  usage += " -root file.root [-chrom 1 2 ...] -stat      bin_size\n";
  usage += argv[0];
  usage += " -root file.root                  -eval      bin_size\n";
  usage += argv[0];
  usage += " -root file.root [-chrom 1 2 ...] -partition bin_size [-ngc]\n";
  // usage += argv[0];
  //usage += " -root file.root [-chrom 1 2 ...] -spartition bin_size [-gc]\n";
  usage += argv[0];
  usage += " -root file.root [-chrom 1 2 ...] -call      bin_size [-ngc]\n";
  usage += argv[0];
  usage += " -root file.root -genotype bin_size [-ngc]\n";
  usage += argv[0];
  usage += " -root file.root -view     bin_size [-ngc]\n";
  usage += argv[0];
  usage += " -pe   file1.bam ... -qual val(20) -over val(0.8) [-f file]\n";
  usage += "\n";
  usage += "Valid genomes (-genome option) are: NCBI36, hg18, GRCh37, hg19\n";

  if (argc < 2) {
    cerr<<"Not enough parameters."<<endl;
    cerr<<usage<<endl;
    return 0;
  }

#ifdef USE_YEPPP
  YepStatus yepStatus = yepLibrary_Init();
  if (yepStatus != YepStatusOk) {
    cerr<<"Yeppp library initialization failed with status "<<yepStatus<<"."<<endl;
    return 1;
  }
#endif

  static const int OPT_TREE       = 0x00001;
  static const int OPT_MERGE      = 0x00002;
  static const int OPT_HIS        = 0x00004;
  static const int OPT_HISMERGE   = 0x00008;
  static const int OPT_STAT       = 0x00010;
  static const int OPT_PARTITION  = 0x00020;
  static const int OPT_EPARTITION = 0x00040;
  static const int OPT_CALL       = 0x00080;
  static const int OPT_VIEW       = 0x00100;
  static const int OPT_GENOTYPE   = 0x00200;
  static const int OPT_EVAL       = 0x00400;
  static const int OPT_PE         = 0x00800;
  static const int OPT_PANEL      = 0x01000;
  static const int OPT_FIT        = 0x02000;

  static const int OPT_SPARTITION = 0x04000;
  static const int OPT_HIS_NEW    = 0x08000;
  static const int OPT_AGGREGATE  = 0x10000;

  // tree, merge, his, stat, partition, spartition, call, view, genotype
  int max_opts = 10000, n_opts = 0, opts[max_opts], bins[max_opts], gbin = 0;
  for (int i = 0;i < n_opts;i++) bins[i] = 0;
  bool useGCcorr = true,useATcorr = false;
  bool forUnique = false,relaxCalling = false;
  string out_root_file(""),call_file(""),group_name("");
  string chroms[1000],data_files[100000],root_files[100000] = {""},dir = ".";
  int n_chroms = 0,n_files = 0,n_root_files = 0,range = 128, qual = 20;
  double over = 0.8;
  Genome *genome = NULL;

  int index = 1;
  while (index < argc) {
    string option = argv[index++];
    if (option == "-tree"  || option == "-merge" || option == "-pe") {
      if (option == "-tree")  opts[n_opts++] = OPT_TREE;
      if (option == "-merge") opts[n_opts++] = OPT_MERGE;
      if (option == "-pe")    opts[n_opts++] = OPT_PE;
      while (index < argc && argv[index][0] != '-')
	if (strlen(argv[index++]) > 0) data_files[n_files++] = argv[index - 1];
    } else if (option == "-his"        || option == "-his_new"    ||
	       option == "-hismerge"   ||
	       option == "-stat"       || option == "-eval"       ||
	       option == "-partition"  || option == "-spartition" ||
	       option == "-epartition" ||
	       option == "-call"       || option == "-view"       ||
	       option == "-genotype"   || option == "-aggregate") {
      int bs = 0;
      if (index < argc && argv[index][0] != '-') {
	TString tmp = argv[index++];
	if (!tmp.IsDigit()) {
	  cerr<<"Bin size must be integer for option '"<<option<<"'."<<endl;
	  cerr<<usage<<endl;
	  return 0;
	}
	bs = tmp.Atoi();
      }
      if (option == "-his")        opts[n_opts] = OPT_HIS;
      if (option == "-hismerge")   opts[n_opts] = OPT_HISMERGE;
      if (option == "-stat")       opts[n_opts] = OPT_STAT;
      if (option == "-partition")  opts[n_opts] = OPT_PARTITION;
      if (option == "-epartition") opts[n_opts] = OPT_EPARTITION;
      if (option == "-spartition") opts[n_opts] = OPT_SPARTITION;
      if (option == "-call")       opts[n_opts] = OPT_CALL;
      if (option == "-view")       opts[n_opts] = OPT_VIEW;
      if (option == "-genotype")   opts[n_opts] = OPT_GENOTYPE;
      if (option == "-his_new")    opts[n_opts] = OPT_HIS_NEW;
      if (option == "-eval")       opts[n_opts] = OPT_EVAL;
      if (option == "-aggregate")  opts[n_opts] = OPT_AGGREGATE;
      bins[n_opts++] = bs;
    } else if (option == "-panel") {
      opts[n_opts++] = OPT_PANEL;
    } else if (option == "-fit")   {
      opts[n_opts++] = OPT_FIT;
      if (index < argc && argv[index][0] != '-') group_name = argv[index++];
      else {
	cout<<"Please provide name of a sample group."<<endl;
	return 0;
      }
    } else if (option == "-outroot") {
      if (index < argc && argv[index][0] != '-') out_root_file = argv[index++];
      else {
	cout<<"Please provide new root-file name."<<endl;
	return 0;
      }
    } else if (option == "-root") {
      while (index < argc && argv[index][0] != '-')
	if (strlen(argv[index++]) > 0)
	  root_files[n_root_files++] = argv[index - 1];
      if (n_root_files == 0) {
	cerr<<"Please provide root-file name."<<endl;
	cerr<<usage<<endl;
	return 0;
      }
    } else if (option == "-outroot") {
      if (index < argc && argv[index][0] != '-') out_root_file = argv[index++];
      else {
	cout<<"Please provide new root-file name."<<endl;
	return 0;
      }
    } else if (option == "-chrom") {
      while (index < argc && argv[index][0] != '-')
	chroms[n_chroms++] = argv[index++];
      if (n_chroms == 0) {
	cerr<<"Provide chromosome names."<<endl;
	cerr<<usage<<endl;
	return 0;
      }
    } else if (option == "-ngc") {
      useGCcorr = false;
    } else if (option == "-at") {
      useATcorr = true;
    } else if (option == "-genome") {
      if (index < argc)	genome = Genome::get(argv[index++]);
    } else if (option == "-d") {
      if (index < argc && argv[index][0] != '-')
	dir = argv[index++];
      else cerr<<"No directory is given."<<endl;
    } else if (option == "-qual") {
      if (index >= argc || argv[index][0] == '-') {
	cerr<<"No quality value is provided."<<endl;
	cerr<<usage<<endl;
	return 0;
      }
      TString tmp = argv[index++];
      if (!tmp.IsDigit()) {
	cerr<<"Quality value must be integer."<<endl;
	cerr<<usage<<endl;
	return 0;
      }
      qual = tmp.Atoi();
    } else if (option == "-over") {
      if (index >= argc || argv[index][0] == '-') {
	cerr<<"No fraction of overlap is provided."<<endl;
	cerr<<usage<<endl;
	return 0;
      }
      TString tmp = argv[index++];
      if (!tmp.IsFloat()) {
	cerr<<"Fraction of overlap must be number."<<endl;
	cerr<<usage<<endl;
	return 0;
      }
      over = tmp.Atof();
    } else if (option == "-f") {
      if (index >= argc || argv[index][0] == '-') {
	cerr<<"No file name is provided."<<endl;
	cerr<<usage<<endl;
	return 0;
      }
      call_file = argv[index++];
    } else if (option == "-unique") {
      forUnique = true;
    } else if (option == "-range") {
      range = atoi(argv[index++]);
    } else if (option == "-relax") {
      relaxCalling = true;
    } else if (option[0] == '-') {
      cerr<<"Unknown option '"<<option<<"'.\n"<<endl;
    }
  }

  if (out_root_file.length() <= 0) out_root_file = root_files[0];
  if (out_root_file.length() <= 0)
    cerr<<"WARNING: no name of root-file provided."<<endl;

  for (int o = 0;o < n_opts;o++) {
    int option = opts[o];
    int bin = bins[o]; if (bin <= 0) bin = gbin;
    if (option == OPT_TREE) { // tree
      HisMaker maker(out_root_file,genome);
      maker.setDataDir(dir);
      maker.produceTrees(chroms,n_chroms,data_files,n_files,forUnique);
    }
    if (option == OPT_MERGE) { // merge
      HisMaker maker(out_root_file,genome);
      maker.mergeTrees(chroms,n_chroms,data_files,n_files);
    }
    if (option == OPT_HIS ||
	option == OPT_HISMERGE) { // his
      HisMaker maker(out_root_file,bin,useGCcorr,genome);
      maker.setDataDir(dir);
      maker.produceHistograms(chroms,n_chroms,root_files,n_root_files,false);
      if (option == OPT_HISMERGE)
	maker.produceHistograms(chroms,n_chroms,root_files,n_root_files,true);
    }
    if (option == OPT_STAT) { // stat
      HisMaker maker(out_root_file,bin,useGCcorr,genome);
      maker.stat(chroms,n_chroms,useATcorr);
    }
    if (option == OPT_PARTITION) { // partition
      HisMaker maker(out_root_file,bin,useGCcorr,genome);
      maker.partition(chroms,n_chroms,false,useATcorr,useGCcorr,false,range);
    }
    if (option == OPT_EPARTITION) { // exome partition
      HisMaker maker(out_root_file,bin,useGCcorr,genome);
      maker.partition(chroms,n_chroms,false,useATcorr,useGCcorr,true,range);
    }
    if (option == OPT_CALL) { // call
      HisMaker maker(out_root_file,bin,useGCcorr,genome);
      maker.callSVs(chroms,n_chroms,useATcorr,useGCcorr,relaxCalling);
    }
    if (option == OPT_VIEW) { // view
      HisMaker maker(out_root_file,bin,useGCcorr,genome);
      TApplication theApp("App",0,0);
      maker.view(root_files,n_root_files,useATcorr,useGCcorr);
      theApp.Run();
    }
    if (option == OPT_GENOTYPE) { // genotype
      HisMaker maker(out_root_file,bin,useGCcorr,genome);
      TApplication theApp("App",0,0);
      maker.genotype(root_files,n_root_files,useATcorr,useGCcorr);
      theApp.Run();
    }
    if (option == OPT_EVAL) { // eval
      HisMaker maker(out_root_file,bin,useGCcorr,genome);
      maker.eval(root_files,n_root_files,useATcorr,useGCcorr);
    }
    if (option == OPT_PE) { // pe
      HisMaker maker("null",genome);
      if (call_file.length() > 0) 
	maker.pe_for_file(call_file,data_files,n_files,over,qual);
      else {
	TApplication theApp("App",0,0);
	maker.pe(data_files,n_files,over,qual);
	theApp.Run();
      }
    }
    if (option == OPT_SPARTITION) { // spartition
      HisMaker maker(out_root_file,bin,useGCcorr,genome);
      maker.partition(chroms,n_chroms,true,useATcorr,useGCcorr,false,range);
    }
    if (option == OPT_HIS_NEW) { // his_new
      HisMaker maker(out_root_file,bin,useGCcorr,genome);
      maker.setDataDir(dir);
      maker.produceHistogramsNew(chroms,n_chroms);
    }
    // EXOnator options
    if (option == OPT_PANEL) { // panel
      EXOnator exonator(out_root_file);
      exonator.makeTables();
    }
    if (option == OPT_FIT) { // fit
      EXOnator exonator(out_root_file);
      exonator.fit(group_name);
    }
    if (option == OPT_AGGREGATE) { // aggregate
      HisMaker maker(out_root_file,bin,useGCcorr,genome);
      maker.setDataDir(dir);
      maker.aggregate(root_files,n_root_files,chroms,n_chroms);
    }
  }

  return 0;
}
Example #22
0
void onecut::assignBranch(TString var, TString val){
  if(var == "ht"){
    cutType_ = kFloat;
    bf_ = &baby_base::ht;
  } else if(var == "st"){
    cutType_ = kFloat;
    bf_ = &baby_base::st;
  }else if(var=="met"){
    cutType_ = kFloat;
    bf_ = &baby_base::met;
  }else if(var=="met_tru"){
    cutType_ = kFloat;
    bf_ = &baby_base::met_tru;
  }else if(var=="ht_ra2"){
    cutType_ = kFloat;
    bf_ = &baby_base::ht_ra2;
  }else if(var=="ht_clean"){
    cutType_ = kFloat;
    bf_ = &baby_base::ht_clean;
  }else if(var=="mht"){
    cutType_ = kFloat;
    bf_ = &baby_base::mht;
  }else if(var=="mt"){
    cutType_ = kFloat;
    bf_ = &baby_base::mt;
  }else if(var=="elelv_pt"){
    cutType_ = kFloat;
    bf_ = &baby_base::elelv_pt;
  }else if(var=="elel_pt"){
    cutType_ = kFloat;
    bf_ = &baby_base::elel_pt;
  }else if(var=="elelv_m"){
    cutType_ = kFloat;
    bf_ = &baby_base::elelv_m;
  }else if(var=="elel_m"){
    cutType_ = kFloat;
    bf_ = &baby_base::elel_m;
  }else if(var=="mumuv_pt"){
    cutType_ = kFloat;
    bf_ = &baby_base::mumuv_pt;
  }else if(var=="mumu_pt"){
    cutType_ = kFloat;
    bf_ = &baby_base::mumu_pt;
  }else if(var=="mumuv_m"){
    cutType_ = kFloat;
    bf_ = &baby_base::mumuv_m;
  }else if(var=="mumu_m"){
    cutType_ = kFloat;
    bf_ = &baby_base::mumu_m;
  }else if(var=="mj"){
    cutType_ = kFloat;
    bf_ = &baby_base::mj;
  }else if(var=="mj08"){
    cutType_ = kFloat;
    bf_ = &baby_base::mj08;
  }else if(var=="mj14"){
    cutType_ = kFloat;
    bf_ = &baby_base::mj14;
  }else if(var=="mj16"){
    cutType_ = kFloat;
    bf_ = &baby_base::mj16;
  }else if(var=="nleps"){
    cutType_ = kInt;
    bi_ = &baby_base::nleps;
  }else if(var=="nvels"){
    cutType_ = kInt;
    bi_ = &baby_base::nvels;
  }else if(var=="nels"){
    cutType_ = kInt;
    bi_ = &baby_base::nels;
  }else if(var=="nvmus"){
    cutType_ = kInt;
    bi_ = &baby_base::nvmus;
  }else if(var=="nveto"){
    cutType_ = kInt;
    bi_ = &baby_base::nveto;
  }else if(var=="nmus"){
    cutType_ = kInt;
    bi_ = &baby_base::nmus;
  }else if(var=="ntruleps"){
    cutType_ = kInt;
    bi_ = &baby_base::ntruleps;
  }else if(var=="ntrutaush"){
    cutType_ = kInt;
    bi_ = &baby_base::ntrutaush;
  }else if(var=="njets"){
    cutType_ = kInt;
    bi_ = &baby_base::njets;
  }else if(var=="njets_ra2"){
    cutType_ = kInt;
    bi_ = &baby_base::njets_ra2;
  }else if(var=="njets_clean"){
    cutType_ = kInt;
    bi_ = &baby_base::njets_clean;
  }else if(var=="run"){
    cutType_ = kInt;
    bi_ = &baby_base::run;
  }else if(var=="nbm"){
    cutType_ = kInt;
    bi_ = &baby_base::nbm;
  }else if(var=="pass"){
    cutType_ = kBool;
    bb_ = &baby_base::pass;
  }else if(var=="stitch"){
    cutType_ = kBool;
    bb_ = &baby_base::stitch;
  }else if(var=="nonblind"){
    cutType_ = kBool;
    bb_ = &baby_base::nonblind;
  }else if(var=="pass_ra2"){
    cutType_ = kBool;
    bb_ = &baby_base::pass_ra2;
  }else if(var=="pass_jets"){
    cutType_ = kBool;
    bb_ = &baby_base::pass_jets;
  } else if(var.Contains("[")){ // if var is a vector element
    TString index_s(var);
    var.Remove(var.Index("["), var.Length());
    index_s.Remove(0, index_s.Index("[")+1);
    index_s.Remove(index_s.Index("]"), index_s.Length());
    ivector_ = index_s.Atoi();
    if(var=="trig"){
      cutType_ = kvBool;
      bvb_ = &baby_base::trig;
    }else if(var=="sys_pass"){
      cutType_ = kvBool;
      bvb_ = &baby_base::sys_pass;
    }else if(var=="sys_ht"){ 
      cutType_ = kvFloat;
      bvf_ = &baby_base::sys_ht;
    }else if(var=="sys_st"){ 
      cutType_ = kvFloat;
      bvf_ = &baby_base::sys_st;
    }else if(var=="sys_met"){ 
      cutType_ = kvFloat;
      bvf_ = &baby_base::sys_met;
    }else if(var=="leps_pt"){ 
      cutType_ = kvFloat;
      bvf_ = &baby_base::leps_pt;
    }else if(var=="sys_njets"){ 
      cutType_ = kvInt;
      bvi_ = &baby_base::sys_njets;
    }else if(var=="sys_nbm"){ 
      cutType_ = kvInt;
      bvi_ = &baby_base::sys_nbm;
    }else if(var=="sys_mj"){ 
      cutType_ = kvFloat;
      bvf_ = &baby_base::sys_mj;
    }else if(var=="sys_mj14"){ 
      cutType_ = kvFloat;
      bvf_ = &baby_base::sys_mj14;
    }else if(var=="sys_mt"){ 
      cutType_ = kvFloat;
      bvf_ = &baby_base::sys_mt;
    }else {
      cout<<endl<<"Branch \""<<var<<" not defined. Add it to onecut::assignBranch in bcut.cpp"<<endl<<endl;
      exit(0);
    }
  }else {
    cout<<endl<<"Branch \""<<var<<" not defined. Add it to onecut::assignBranch in bcut.cpp"<<endl<<endl;
    exit(0);
  } 

  if(cutType_ == kFloat || cutType_ == kvFloat) cutf_ = val.Atof();
  if(cutType_ == kInt || cutType_ == kvInt)     cuti_ = val.Atoi();
}
void draw() {

  gROOT->Reset();

// first make a canvas and a 2D histogram for the axes

  TCanvas* canvas = new TCanvas("canvas", "canvas", 10, 10, 500, 500);
  canvas->SetFillColor(0);
  canvas->SetBorderMode(0);  
  canvas->SetFrameBorderMode(0);   // need this to turn off red hist frame!

  gROOT->SetStyle("Plain");
  canvas->UseCurrentStyle();

  gPad->SetLeftMargin(0.15);
  gPad->SetRightMargin(0.05);
  gPad->SetTopMargin(0.07);
  gPad->SetBottomMargin(0.17);

  gStyle->SetOptStat(0);
  gStyle->SetTitleBorderSize(0);
  gStyle->SetTitleSize(0.04);

  gStyle->SetTextFont(42);
  gStyle->SetTextSize(0.04);
  gStyle->SetTitleFont(42, "hxy");    // for histogram and axis title
  gStyle->SetLabelFont(42, "xyz");    // for axis labels (values)

  gStyle->SetTitleOffset(0.8, "h");        // what does this do?
  gStyle->SetTitleX(0.15);
  gStyle->SetTitleY(0.99);

  gROOT->ForceStyle();

  // can make histogram or alternatively use the histograms automatically
  // connected to the TF1 or TGraph objects

  double xMin = 0.1;
  double xMax = 100.;
  // double yMin = 0.1;
  // double yMax = 10.;
  double yMin = 0.;
  double yMax = 8.;
  TH2F* axhist = new TH2F("axhist", "title", 10, xMin, xMax, 10, yMin, yMax);
  axhist->SetTitle("");
  axhist->SetXTitle("b");
  axhist->SetYTitle("med[Z|s]");
  gPad->SetLogx(1);
  gPad->SetLogy(0);

  double u[20];
  double x[20][500];

  // Read in data from file and insert in TTree

  TString fileName;
  // cout << "Enter file name: ";
  // cin >> fileName;
  fileName = "medsig_s5_rel_bi.txt";

  ifstream inFile;
  inFile.open(fileName);
  if (inFile.fail()) { 
    cout << "Couldn't open file!" << endl;
    exit(1); 
  }

  bool readLine = true;
  int lineNum = 0;
  int ncol;
  while ( readLine ){

    TString line;
    stringstream ss;
    line.ReadLine(inFile);
    readLine = inFile.good();

    if ( readLine ) {

      TString firstChar = line(0,1);
      bool useLine = firstChar != "#";

      if ( useLine ){

        int i = 0;
        stringstream ss;
        ss << line;              // put whole line into ss
        TString token;
        bool getToken = true;

        while ( getToken ) {
          ss >> token;           // extracts one token
          if ( token.Length() > 0 ) {
            u[i] = token.Atof();
            i++;
          } 
          else {
            getToken = false;
          }
        }             // getToken
        ncol = i;  

        for (int i=0; i<ncol; i++){
          x[i][lineNum] = u[i];
        }
        lineNum++;

      }               // useLine

    }         // readLine

  }           // readLine

  int n = lineNum;
  inFile.close();

  //  for (int i=0; i<n; i++){
  //  cout << i << "  " << x[0][i] << "  " << x[3][i] << "  " 
  //	 << x[4][i] << endl;
  //  }

  TGraph* tg1 = new TGraph(n, x[0], x[1]);
  TGraph* tg2 = new TGraph(n, x[0], x[2]);
  TGraph* tg3 = new TGraph(n, x[0], x[3]);
  TGraph* tg4 = new TGraph(n, x[0], x[4]);
  TGraph* tg5 = new TGraph(n, x[0], x[5]);
  TGraph* tg6 = new TGraph(n, x[0], x[6]);
  TGraph* tg7 = new TGraph(n, x[0], x[7]);
  TGraph* tg8 = new TGraph(n, x[0], x[8]);
  TGraph* tg9 = new TGraph(n, x[0], x[9]);
  TGraph* tg10 = new TGraph(n, x[0], x[10]);
  TGraph* tg11 = new TGraph(n, x[0], x[11]);
  TGraph* tg12 = new TGraph(n, x[0], x[12]);
  TGraph* tg13 = new TGraph(n, x[0], x[13]);
  TGraph* tg14 = new TGraph(n, x[0], x[14]);
  TGraph* tg15 = new TGraph(n, x[0], x[15]);

  TAxis* xa = axhist->GetXaxis();
  TAxis* ya = axhist->GetYaxis();

  xa->SetTitleOffset(1.2);    //  factor multiplies default offset
  ya->SetTitleOffset(1.1);

  xa->SetLabelOffset(0.005);
  ya->SetLabelOffset(0.005);

  xa->SetTickLength(0.015);  // default  = 0.03
  ya->SetTickLength(0.015);  // default  = 0.03

  xa->SetTitleSize(0.05);
  ya->SetTitleSize(0.05);

  //  gPad->SetLogx(1);
  //  xa->SetLimits(90., 700.);

  xa->SetNdivisions(-5); // negative value should force number of divisions?
  ya->SetNdivisions(-4);

  xa->SetLabelSize(0.05);
  ya->SetLabelSize(0.05);

  // Draw axes and then add stuff

  // kDot=1, kPlus, kStar, kCircle=4, kMultiply=5,
  // kFullDotSmall=6, kFullDotMedium=7, kFullDotLarge=8,
  // kFullCircle=20, kFullSquare=21, kFullTriangleUp=22,
  // kFullTriangleDown=23, kOpenCircle=24, kOpenSquare=25,
  // kOpenTriangleUp=26, kOpenDiamond=27, kOpenCross=28,
  // kFullStar=29, kOpenStar=30

  axhist->Draw();

  tg1->SetLineColor(kRed);
  tg1->SetLineWidth(2);
  tg1->SetLineStyle(2);
  tg1->SetMarkerColor(kRed);
  tg1->SetMarkerSize(0.8);
  tg1->SetMarkerStyle(20);
  tg1->Draw("L,same");              // or P for points

  tg2->SetLineColor(kRed);
  tg2->SetLineWidth(2);
  tg2->SetLineStyle(2);
  tg2->SetMarkerColor(kRed);
  tg2->SetMarkerSize(0.8);
  tg2->SetMarkerStyle(20);
  tg2->Draw("L,same");              // or P for points

  tg3->SetLineColor(kRed);
  tg3->SetLineWidth(2);
  tg3->SetLineStyle(2);
  tg3->SetMarkerColor(kRed);
  tg3->SetMarkerSize(0.8);
  tg3->SetMarkerStyle(20);
  // tg3->Draw("L,same");              // or P for points

  tg4->SetLineColor(kBlue);
  tg4->SetLineWidth(2);
  tg4->SetLineStyle(1);
  tg4->SetMarkerColor(kBlue);
  tg4->SetMarkerSize(0.8);
  tg4->SetMarkerStyle(20);
  tg4->Draw("L,same");              // or P for points

  tg5->SetLineColor(kBlue);
  tg5->SetLineWidth(2);
  tg5->SetLineStyle(1);
  tg5->SetMarkerColor(kBlue);
  tg5->SetMarkerSize(0.8);
  tg5->SetMarkerStyle(20);
  tg5->Draw("L,same");              // or P for points

  tg6->SetLineColor(kBlue);
  tg6->SetLineWidth(2);
  tg6->SetLineStyle(1);
  tg6->SetMarkerColor(kBlue);
  tg6->SetMarkerSize(0.8);
  tg6->SetMarkerStyle(20);
  // tg6->Draw("L,same");              // or P for points

  tg7->SetLineColor(kRed);
  tg7->SetLineWidth(2);
  tg7->SetLineStyle(1);
  tg7->SetMarkerColor(kRed);
  tg7->SetMarkerSize(0.8);
  tg7->SetMarkerStyle(21);
  // tg7->Draw("P,same");              // or P for points

  tg8->SetLineColor(kRed);
  tg8->SetLineWidth(2);
  tg8->SetLineStyle(1);
  tg8->SetMarkerColor(kRed);
  tg8->SetMarkerSize(0.8);
  tg8->SetMarkerStyle(21);
  // tg8->Draw("P,same");              // or P for points

  tg9->SetLineColor(kRed);
  tg9->SetLineWidth(2);
  tg9->SetLineStyle(2);
  tg9->SetMarkerColor(kRed);
  tg9->SetMarkerSize(0.8);
  tg9->SetMarkerStyle(21);
  // tg9->Draw("P,same");              // or P for points

  tg10->SetLineColor(kBlack);
  tg10->SetLineWidth(2);
  tg10->SetLineStyle(2);
  tg10->SetMarkerColor(kBlack);
  tg10->SetMarkerSize(0.8);
  tg10->SetMarkerStyle(20);
  tg10->Draw("P,same");              // or P for points

  tg11->SetLineColor(kBlack);
  tg11->SetLineWidth(2);
  tg11->SetLineStyle(2);
  tg11->SetMarkerColor(kBlack);
  tg11->SetMarkerSize(0.8);
  tg11->SetMarkerStyle(20);
  tg11->Draw("P,same");              // or P for points

  tg12->SetLineColor(kBlack);
  tg12->SetLineWidth(2);
  tg12->SetLineStyle(2);
  tg12->SetMarkerColor(kBlack);
  tg12->SetMarkerSize(0.8);
  tg12->SetMarkerStyle(20);
  // tg12->Draw("P,same");              // or P for points

  tg13->SetLineColor(kBlack);
  tg13->SetLineWidth(2);
  tg13->SetLineStyle(3);
  tg13->SetMarkerColor(kBlack);
  tg13->SetMarkerSize(0.8);
  tg13->SetMarkerStyle(20);
  // tg13->Draw("L,same");              // or P for points

  tg14->SetLineColor(kBlack);
  tg14->SetLineWidth(2);
  tg14->SetLineStyle(3);
  tg14->SetMarkerColor(kBlack);
  tg14->SetMarkerSize(0.8);
  tg14->SetMarkerStyle(20);
  // tg14->Draw("L,same");              // or P for points

  tg15->SetLineColor(kBlack);
  tg15->SetLineWidth(2);
  tg15->SetLineStyle(3);
  tg15->SetMarkerColor(kBlack);
  tg15->SetMarkerSize(0.8);
  tg15->SetMarkerStyle(20);
  // tg15->Draw("L,same");              // or P for points


  TLegend* leg = new TLegend(0.53, 0.48, 0.95, .73); // x1, y1, x2, y2
  leg->SetTextSize(0.05);
  leg->SetTextFont(42);
  leg->SetBorderSize(0);
  leg->SetFillColor(0);
  leg->AddEntry(tg1, " s / #sqrt{b + #sigma_{b}^{2}}", "l");
  leg->AddEntry(tg4, "  Z_{A}", "l");
  // leg->AddEntry(tg7, " #sqrt{q0}, MC median", "p");
  leg->AddEntry(tg10, " Monte Carlo", "p");
  // leg->AddEntry(tg13, " Z_{bi}" , "l");
  // leg->AddEntry(tg4, "s = 0.03", "l");
  leg->Draw();

  TLatex* tl = new TLatex();
  tl->SetTextAlign(11);
  tl->SetTextSize(0.05);
  tl->SetTextFont(42);
  tl->SetNDC();
  // tl->DrawLatex(.76, 0.33, "s = 2");  
  // tl->DrawLatex(.76, 0.465, "s = 5");  
  // tl->DrawLatex(.76, 0.6, "s = 10");  
  //   tl->DrawLatex(.76, 0.73, "s = 20");  

  // tl->DrawLatex(.5, .77, "#sigma_{b}/b = 0.2, 0.5, 1");
  tl->DrawLatex(.5, .77, "#sigma_{b}/b = 0.2, 0.5");
  tl->DrawLatex(.5, .85, "s = 5");

  // Fix idiotic problem with frame

  TLine* tli = new TLine();
  tli->SetLineStyle(1);
  tli->SetLineWidth(1);
  tli->DrawLine(xMin, yMin, xMax, yMin);
  tli->DrawLine(xMax, yMin, xMax, yMax);
  tli->DrawLine(xMin, yMax, xMax, yMax);
  tli->DrawLine(xMin, yMin, xMin, yMax);

  TPostScript psfile("medsig_s5_rel_bi.eps", 113);     // 113 makes eps
  canvas->Draw();
  psfile.Close();
  // canvas->Print("plot.gif", "gif");

}
Int_t AddRsnDaughterCutsPhiNsigma(AliPID::EParticleType type1,AliPID::EParticleType type2,TString opt,AliRsnInputHandler *rsnIH=0,AliAnalysisTaskSE *task=0)
{

  if (!rsnIH) return 0;
  
  Bool_t valid = kTRUE;
  //   Int_t collisionType = AliRsnTrainManager::GetGlobalInt("IsCollisionType",valid);
  Int_t useCommonQualityCut = AliRsnTrainManager::GetGlobalInt("RsnCommonQualityCut",valid);
  TString rsnQualityCut = AliRsnTrainManager::GetGlobalStr("RsnQualityCut",valid);
  Int_t isMC = AliRsnTrainManager::GetGlobalInt("IsMC",valid);
  Int_t isRsnMini = AliRsnTrainManager::GetGlobalInt("IsRsnMini",valid);
  Int_t isMixing = AliRsnTrainManager::GetGlobalInt("IsMixing",valid);

  // experts only (don't touch)
  Int_t isRsnDev = AliAnalysisManager::GetGlobalInt("rsnUseRSNParDev",valid);

  // === USER HAS TO SET CORRECT NUMBER OF CUTS SETS =====
  Int_t numberOfCuts = 1;

  //---------------------------------------------
  //  Define single cuts
  //---------------------------------------------

  Printf("AliRsnCutPIDNSigma Option : %s",opt.Data());

  Double_t nSigmaTPC=3.0;
  Double_t nSigmaTOF=3.0;
  Double_t etaMin=-0.8;
  Double_t etaMax=0.8;
  Double_t trackPtMin=0.;
  Double_t trackPtMax=1.e10;
  Int_t NclTPC=70;
  Char_t DCAxyFormula[100]="0.0182+0.035/pt^1.01";

  Bool_t useTPC_K=kFALSE;
  Bool_t useTOF_K=kFALSE;
  Bool_t rejectUnmatchedTOF_K=kTRUE;
  Bool_t useTrackPtCut=kFALSE;

  if (opt.Contains("qualityonly")) {
    useTPC_K=kFALSE;
    useTOF_K=kFALSE;
  }

  if (opt.Contains("KTPCnsig"))  useTPC_K=kTRUE;
  if (opt.Contains("KTOFnsig"))  useTOF_K=kTRUE;
  if (opt.Contains("KTOFacceptUnmatched")) rejectUnmatchedTOF_K=kFALSE;

  if (opt.Contains("KTPCnsig05")) nSigmaTPC = 0.5;
  if (opt.Contains("KTPCnsig08")) nSigmaTPC = 0.8;
  if (opt.Contains("KTPCnsig10")) nSigmaTPC = 1.0;
  if (opt.Contains("KTPCnsig15")) nSigmaTPC = 1.5;
  if (opt.Contains("KTPCnsig20")) nSigmaTPC = 2.0;
  if (opt.Contains("KTPCnsig25")) nSigmaTPC = 2.5;
  if (opt.Contains("KTPCnsig30")) nSigmaTPC = 3.0;
  if (opt.Contains("KTPCnsig40")) nSigmaTPC = 4.0;
  if (opt.Contains("KTPCnsig50")) nSigmaTPC = 5.0;
  if (opt.Contains("KTPCnsig1000")) nSigmaTPC = 100.0;

  if (opt.Contains("KTOFnsig10")) nSigmaTOF = 1.0;
  if (opt.Contains("KTOFnsig15")) nSigmaTOF = 1.5;
  if (opt.Contains("KTOFnsig20")) nSigmaTOF = 2.0;
  if (opt.Contains("KTOFnsig25")) nSigmaTOF = 2.5;
  if (opt.Contains("KTOFnsig30")) nSigmaTOF = 3.0;
  if (opt.Contains("KTOFnsig40")) nSigmaTOF = 4.0;
  if (opt.Contains("KTOFnsig50")) nSigmaTOF = 5.0;
  if (opt.Contains("KTOFnsig1000")) nSigmaTOF = 100.0;

  if (opt.Contains("trackPt")) {
    useTrackPtCut = kTRUE;
    if (opt.Contains("trackPtMin015")) trackPtMin = 0.15;
    if (opt.Contains("trackPtMin02")) trackPtMin = 0.2;
    if (opt.Contains("trackPtMin05")) trackPtMin = 0.5;
    if (opt.Contains("trackPtMin06")) trackPtMin = 0.6;

    if (opt.Contains("trackPtMax18")) trackPtMax = 1.8;
    if (opt.Contains("trackPtMax20")) trackPtMax = 2.0;
    if (opt.Contains("trackPtMax25")) trackPtMax = 2.5;
  }

  Bool_t usePDG=kFALSE;
  if (opt.Contains("pdg")) {
    Printf("Using PDG");
    usePDG = kTRUE;
  }

  Bool_t useEta = kFALSE;
  if (opt.Contains("eta")) {
    for(int j=1;j<=9;j++) if(opt.Contains(Form("eta0%i",j))){etaMin=-0.1*j; etaMax=0.1*j;}

    for(int j=1;j<=9;j++) if(opt.Contains(Form("etaMinMinus0%i",j))) etaMin=-0.1*j;
    if(opt.Contains("etaMin00")) etaMin=0.;
    for(int j=1;j<=9;j++) if(opt.Contains(Form("etaMinPlus0%i",j))) etaMin=0.1*j;

    for(int j=1;j<=9;j++) if(opt.Contains(Form("etaMaxMinus0%i",j))) etaMax=-0.1*j;
    if(opt.Contains("etaMax00")) etaMax=0.;
    for(int j=1;j<=9;j++) if(opt.Contains(Form("etaMaxPlus0%i",j))) etaMax=0.1*j;

    Printf("Using ETA range (%.2f,%.2f)",etaMin,etaMax);
    useEta = kTRUE;
  }

  Bool_t useNclTPC = kFALSE;
  if (opt.Contains("NclTPC")) {
    if (opt.Contains("NclTPC70")) NclTPC=70;
    if (opt.Contains("NclTPC75")) NclTPC=75;
    if (opt.Contains("NclTPC80")) NclTPC=80;
    if (opt.Contains("NclTPC85")) NclTPC=85;
    if (opt.Contains("NclTPC90")) NclTPC=90;
    useNclTPC = kTRUE;
  }

  Bool_t useDCAxy = kFALSE;
  if (opt.Contains("DCAxy")) {
    if (opt.Contains("DCAxyFormula7s")) sprintf(DCAxyFormula,"0.0182+0.035/pt^1.01");
    if (opt.Contains("DCAxyFormula6s")) sprintf(DCAxyFormula,"0.0156+0.03/pt^1.01");
    if (opt.Contains("DCAxyFormula5s")) sprintf(DCAxyFormula,"0.013+0.025/pt^1.01");
    useDCAxy = kTRUE;
  }

  //---------------------------------------------
  //  Combine cuts
  //---------------------------------------------

  TString cutname = "K_Phi";
  if (!opt.IsNull()) cutname += Form("_%s",opt.Data());
  AliRsnCutSet *cuts = new AliRsnCutSet(cutname.Data(), AliRsnTarget::kDaughter);

  TString scheme="";
  AliRsnCutTrackQuality *qualityCut = new AliRsnCutTrackQuality("cutQualityK");
  if (!rsnQualityCut.IsNull()) {
    AliESDtrackCuts *esdTK = RsnQualityCut(rsnQualityCut.Data());
    if(useDCAxy) esdTK->SetMaxDCAToVertexXYPtDep(DCAxyFormula);
    qualityCut->SetESDtrackCuts(esdTK);
  } else {
    if (useCommonQualityCut>=0) {
      qualityCut->SetAODTestFilterBit(useCommonQualityCut);
      if(useDCAxy) {qualityCut->SetCheckOnlyFilterBit(kFALSE); qualityCut->SetDCARPtFormula(DCAxyFormula);}
    } else {
      qualityCut->SetDefaults2010();
      if(useDCAxy) qualityCut->SetDCARPtFormula(DCAxyFormula);
    }
  }

  cuts->AddCut(qualityCut);
  if (!scheme.IsNull()) scheme += "&";
  scheme += qualityCut->GetName();


  if (useTPC_K) {
    AliRsnCutPIDNSigma *cutKTPC = new AliRsnCutPIDNSigma("cutPIDNSigmaTPCK",AliPID::kKaon,AliRsnCutPIDNSigma::kTPC);
    cutKTPC->SinglePIDRange(nSigmaTPC);
    cuts->AddCut(cutKTPC);
    if (!scheme.IsNull()) scheme += "&";
    scheme += cutKTPC->GetName();
  }

  if (useTOF_K) {
    AliRsnCutPIDNSigma *cutKTOF = new AliRsnCutPIDNSigma("cutPIDNSigmaTOFK",AliPID::kKaon,AliRsnCutPIDNSigma::kTOF);
    cutKTOF->SinglePIDRange(nSigmaTOF);
    cuts->AddCut(cutKTOF);
    if(rejectUnmatchedTOF_K){
      if (!scheme.IsNull()) scheme += "&";
      scheme += cutKTOF->GetName();
    }else{
      AliRsnCutTOFMatch *cutKTOFMatch = new AliRsnCutTOFMatch("cutKTOFMatch");
      cuts->AddCut(cutKTOFMatch);
      if (!scheme.IsNull()) scheme += "&";
      scheme += Form("(%s|(!%s))",cutKTOF->GetName(),cutKTOFMatch->GetName());
    }
  }

  if (useEta) {
    Printf("Adding ETA ...");
    AliRsnValueDaughter *valEta = new AliRsnValueDaughter(Form("val%sETA%s",AliPID::ParticleName(type1),opt.Data()),AliRsnValueDaughter::kEta);
    AliRsnCutValue *cutEta = new AliRsnCutValue(Form("cut%sETA%s",AliPID::ParticleName(type1),opt.Data()),etaMin,etaMax);
    cutEta->SetTargetType(AliRsnTarget::kDaughter);
    cutEta->SetValueObj(valEta);
    cuts->AddCut(cutEta);
    if (!scheme.IsNull()) scheme += "&";
    scheme += cutEta->GetName();
  }

  if (useTrackPtCut) {
    Printf("Adding Pt min=%.3f max=%.3f ...",trackPtMin,trackPtMax);
    AliRsnValueDaughter *valTrackPt = new AliRsnValueDaughter(Form("val%sTrackPt%s",AliPID::ParticleName(type1),opt.Data()),AliRsnValueDaughter::kPt);

    AliRsnCutValue *cutTrackPt = new AliRsnCutValue(Form("cut%sTrackPt%s",AliPID::ParticleName(type1),opt.Data()),trackPtMin,trackPtMax);
    cutTrackPt->SetTargetType(AliRsnTarget::kDaughter);
    cutTrackPt->SetValueObj(valTrackPt);
    cuts->AddCut(cutTrackPt);
    if (!scheme.IsNull()) scheme += "&";
    scheme += cutTrackPt->GetName();
  }

  if (useNclTPC) {
    Printf("Adding NclTPC >= %i",NclTPC);
    AliRsnValueDaughter *valNclTPC = new AliRsnValueDaughter(Form("val%sNclTPC%s",AliPID::ParticleName(type1),opt.Data()),AliRsnValueDaughter::kNTPCclusters);
    AliRsnCutValue *cutNclTPC = new AliRsnCutValue(Form("cut%sNclTPC%s",AliPID::ParticleName(type1),opt.Data()),NclTPC-0.1,1000.);
    cutNclTPC->SetTargetType(AliRsnTarget::kDaughter);
    cutNclTPC->SetValueObj(valNclTPC);
    cuts->AddCut(cutNclTPC);
    if (!scheme.IsNull()) scheme += "&";
    scheme += cutNclTPC->GetName();
  }

  if (usePDG) {
    Printf("Adding PDG ...");
    AliRsnCutPID *cutPDG = new AliRsnCutPID(Form("cut%sPDG%s",AliPID::ParticleName(type1),opt.Data()),type1,0.0,kTRUE);
    cuts->AddCut(cutPDG);
    if (!scheme.IsNull()) scheme += "&";
    scheme += cutPDG->GetName();
  }

  Printf ("CUT Scheme is '%s'",scheme.Data());
  cuts->SetCutScheme(scheme.Data());

  if (opt.Contains("mon")) {
    AddMonitorOutput(cuts->GetMonitorOutput(),opt);
  }
  if (isRsnMini) {
    AliRsnMiniAnalysisTask *taskRsnMini = (AliRsnMiniAnalysisTask *)task;
    if (taskRsnMini) {
      taskRsnMini->AddTrackCuts(cuts);
    }
  } else {
    AliRsnDaughterSelector *sel = rsnIH->GetSelector();
    //       sel->SetLabelCheck(kFALSE);
    sel->Add(cuts, kTRUE);
    if (isRsnDev>=0 && opt.Contains("pairPID")) {
      AliRsnActPostDaughterSelection *pairPID = new AliRsnActPostDaughterSelection();
      pairPID->SetID(0);

      const char *fn="rsnRange.txt";
      if (!gSystem->AccessPathName(fn)) {
	TString minStr = gSystem->GetFromPipe(TString::Format("head -n 1 %s").Data());
	TString maxStr = gSystem->GetFromPipe(TString::Format("tail -n 1 %s").Data());
	pairPID->SetMass(minStr.Atof(),maxStr.Atof());
      } else {
	//       pairPID->SetMass(1.01,1.03);
	pairPID->SetMass(1.015,1.025);
	pairPID->SetMass(1.019,1.021);
	pairPID->SetMass(1.0195,1.0205);
	pairPID->SetMass(1.1000,1.1005);
	//       pairPID->SetMass(1.1005,1.1010);
      }
      sel->AddAction(pairPID);
    }

  }
  return numberOfCuts;

}
Example #25
0
void THDM_Comp(TString HigTag = "100", int PDFindex=5, int isPLep = 0){

  int nHis = 2, nPads = 3;
  Styles style; style.setPadsStyle(nPads); 
  //style.PadRightMargin = 0.029; style.PadLeftMargin = 0.151; style.yTitleOffset = 1.06; 
  style.applyStyle();
  TCanvas can("can","2HDM PDFs");
  can.Divide(nPads,1); 


  double legW = 0.3, legH = 0.18;
  double legX = 1-style.PadRightMargin-0.01-legW, legY = 1-style.PadTopMargin-0.01;
  TLegend leg(legX, legY-legH, legX+legW, legY);
  leg.SetTextSize(style.LabelSize); leg.SetFillColor(0); 
  leg.SetTextFont(style.nFont); leg.SetBorderSize(0);


  TString Name, Variable[] = {"trueQ2", "trueCTL", "candPstarLep"}, legName[4];
  TString xTitle[] = {"q_{true}^{2} (GeV^{2})", "cos(#theta_{#tau,true})", "p*_{l} (GeV)"};
  TString yTitle[] = {"Density/(GeV^{2})","Density","Density/(GeV)"};

  TString Cuts = "weight*(MCTaumode>0&&(MCType=="; Cuts += PDFindex; Cuts += "||MCType=="; Cuts += PDFindex+6; Cuts += "))";
  TString Folder[] = {"AWG82/ntuples/Arxivsmall/FitRAllHigx",  "AWG82/ntuples/small/FitRAllHigx"};
  TString EndName[] = {"_RunAll.root", "_RunAll.root"};
  TString LegName[] = {"ME", "ME + p_{l}"};
  int nBins = 20, color[] = {4,1,28};
  if(HigTag=="000") color[1] = 2;
  //double maxH[] = {0,0,0}, tBmH[4], limX[3][2] = {{3, 12}, {0, 3.2}, {0, 2.2}};
  double maxH[] = {0,0,0}, tBmH[4], limX[3][2] = {{3, 12}, {-1, 1}, {0, 2.2}};
  if(isPLep){
    Variable[2] = "truePLep";
    limX[2][1] = 3;
    xTitle[2] = "p_{l,true} (GeV)";
  }
  
  TH1F *Histo[3][4];
  for(int his=0; his<nHis; his++){
    TString cName = Folder[his]; cName += HigTag; cName += EndName[his];
    //cout<<"Reading "<<cName<<endl;
    TChain chain("ntp1");
    chain.Add(cName);
    tBmH[his] = HigTag.Atof()/100.;
    legName[his] = LegName[his]; 
    for(int pad=0; pad<nPads; pad++){
      can.cd(pad+1);
      Name = "Histo"; Name += pad; Name += his;
      Histo[pad][his] = new TH1F(Name, "",nBins,limX[pad][0],limX[pad][1]);
      TString vari = Variable[pad];
      //if(pad==1 && PDFindex==6) vari = "acos(trueCTL)";
      if(pad==1 && PDFindex==5) vari = "cos(trueCTL)";
      chain.Project(Name, vari, Cuts);
      Histo[pad][his]->SetLineWidth(2);
      Histo[pad][his]->SetLineColor(color[his]);
      Histo[pad][his]->Scale(nBins/Histo[pad][his]->Integral()/(limX[pad][1]-limX[pad][0]));
      if(maxH[pad]<Histo[pad][his]->GetMaximum()) maxH[pad]=Histo[pad][his]->GetMaximum();
      if(pad==0) leg.AddEntry(Histo[pad][his], legName[his]);
    }
  }
    
  for(int pad=0; pad<nPads; pad++){
    can.cd(pad+1);
    for(int his=0; his<nHis; his++){
      if(his==0) {
	Histo[pad][his]->SetMinimum(0);
	Histo[pad][his]->SetMaximum(maxH[pad]*1.05);
	Histo[pad][his]->Draw("");
	style.setTitles(Histo[pad][his],xTitle[pad],yTitle[pad]);
      }else Histo[pad][his]->Draw("same");
    }
    if(pad==2) leg.Draw();
  }
  TString epsName = "public_html/THDM_Comp_"; epsName += HigTag; epsName += "_";
  epsName += PDFindex; epsName += ".eps";
  can.SaveAs(epsName);

  for(int pad=0; pad<nPads; pad++)
    for(int his=0; his<nHis; his++)
      if(Histo[pad][his]) Histo[pad][his]->Delete();
}
void gep_trigger_analysis_elastic( const char *rootfilename, const char *logicfilename_ecal, const char *logicfilename_hcal, const char *thresholdfilename_ecal, const char *thresholdfilename_hcal, const char *outputfilename, double thetacaldeg=29.0, int pheflag=0, const char *assocfilename="ECAL_HCAL_correlations_nophe.txt", int Q2cut=0 ){

  double nominal_threshold_HCAL = 0.5;
  double nominal_threshold_ECAL = 0.9;
  
  double thetacal = thetacaldeg*PI/180.0;
  
  TFile *fout = new TFile(outputfilename,"RECREATE");
  TChain *C = new TChain("T");
  C->Add(rootfilename);

  gep_tree_elastic *T = new gep_tree_elastic( C );

  G4SBSRunData *rd;

  long ngen = 0;
  int nfiles = 0;
  
  TObjArray *FileList = C->GetListOfFiles();
  TIter next(FileList);

  TChainElement *chEl = 0;

  set<TString> bad_file_list;
  
  while( (chEl=(TChainElement*)next() )){
    TFile newfile(chEl->GetTitle());
    newfile.GetObject("run_data",rd);
    if( rd ){
      ngen += rd->fNtries;
      nfiles++;
    } else {
      bad_file_list.insert( chEl->GetTitle());
    }
  }

  cout << "number of generated events = " << ngen << endl;
  
  set<int> list_of_nodes_ecal;
  map<int, set<int> > cells_logic_sums_ecal; //mapping between node numbers and cell numbers
  map<int, double> logic_mean_ecal; //mean peak positions by node number
  map<int, double> logic_sigma_ecal; //peak width by node number
  map<int, double> threshold_ecal; //threshold by node number
  map<std::pair<int,int>, int > cell_rowcol_ecal; //cell numbers mapped by unique row and column pairs
  map<int,set<int> > nodes_cells_ecal; //mapping of nodes by cell number:
  map<int,int> rows_cells_ecal;
  map<int,int> cols_cells_ecal;
  map<int,double> xcells_ecal;
  map<int,double> ycells_ecal;
  
  //keep track of min and max x by row number:
  double ycellmin,ycellmax;
  map<int,double> ycell_rows;
  map<int,double> cellsize_rows;
  map<int,double> xcellmin_rows;
  map<int,double> xcellmax_rows;
  
  int minrow=1000,maxrow=-1;
  
  set<int> rows_ecal;
  map<int,set<int> > columns_rows_ecal;
  
  map<int,double> elastic_peak_new_ecal;
  map<int,double> sigma_new_ecal;
  map<int,double> threshold_new_ecal;
  
  ifstream logicfile_ecal(logicfilename_ecal);
  //ifstream thresholdfile(thresholdfilename);

  TString currentline;
  
  int current_node = 1;

  bool first_cell = true;
  
  while( currentline.ReadLine( logicfile_ecal ) ){
    if( !currentline.BeginsWith( "#" ) ){
      
      TObjArray *tokens = currentline.Tokenize(" ");
      int ntokens = tokens->GetEntries();
      if( ntokens >= 11 ){
	cout << currentline.Data() << ", ntokens = " << ntokens << endl;
	
	TString snode = ( (TObjString*) (*tokens)[0] )->GetString();
	int nodenumber = snode.Atoi();
	
	TString scell = ( (TObjString*) (*tokens)[1] )->GetString();
	int cellnumber = scell.Atoi();
	
	TString speakpos = ( (TObjString*) (*tokens)[8] )->GetString();
	double mean = speakpos.Atof();
	
	TString ssigma = ( (TObjString*) (*tokens)[9] )->GetString();
	double sigma = ssigma.Atof();

	TString sthreshold = ( (TObjString*) (*tokens)[10] )->GetString();
	double threshold = sthreshold.Atof();

	TString srow = ( (TObjString*) (*tokens)[2] )->GetString();
	TString scol = ( (TObjString*) (*tokens)[3] )->GetString();

	std::pair<int,int> rowcoltemp( srow.Atoi(), scol.Atoi() );

	cell_rowcol_ecal[rowcoltemp] = cellnumber;
	
	list_of_nodes_ecal.insert( nodenumber );

	cells_logic_sums_ecal[nodenumber].insert( cellnumber );

	logic_mean_ecal[nodenumber] = mean;
	logic_sigma_ecal[nodenumber] = sigma;
	threshold_ecal[nodenumber] = threshold;

	nodes_cells_ecal[ cellnumber ].insert(nodenumber);

	TString sxcell = ( (TObjString*) (*tokens)[4] )->GetString(); 
	TString sycell = ( (TObjString*) (*tokens)[5] )->GetString(); 

	cols_cells_ecal[cellnumber] = scol.Atoi(); 
	rows_cells_ecal[cellnumber] = srow.Atoi();

	xcells_ecal[cellnumber] = sxcell.Atof()/1000.0; //convert to m
	ycells_ecal[cellnumber] = sycell.Atof()/1000.0; //convert to m

	if( ycell_rows.empty() || sycell.Atof()/1000.0 < ycellmin ) ycellmin = sycell.Atof()/1000.0;
	if( ycell_rows.empty() || sycell.Atof()/1000.0 > ycellmax ) ycellmax = sycell.Atof()/1000.0;
	
	ycell_rows[srow.Atoi()] = sycell.Atof()/1000.0;
	TString ssize = ( (TObjString*) (*tokens)[6] )->GetString();
	double size = ssize.Atof();

	cellsize_rows[srow.Atoi()] = size/1000.0; 
	
	if( xcellmin_rows.empty() || sxcell.Atof()/1000.0 < xcellmin_rows[srow.Atoi()] ){
	  xcellmin_rows[srow.Atoi()] = sxcell.Atof()/1000.0;
	}
	if( xcellmax_rows.empty() || sxcell.Atof()/1000.0 > xcellmax_rows[srow.Atoi()] ){
	  xcellmax_rows[srow.Atoi()] = sxcell.Atof()/1000.0;
	}
	
      }
    }
  }

  set<int> list_of_nodes_hcal;
  map<int, set<int> > cells_logic_sums_hcal; //mapping between node numbers and cell numbers
  map<int, double> logic_mean_hcal; //mean peak positions by node number
  map<int, double> logic_sigma_hcal; //peak width by node number
  map<int, double> threshold_hcal; //threshold by node number
  map<std::pair<int,int>, int > cell_rowcol_hcal; //cell numbers mapped by unique row and column pairs
  map<int,set<int> > nodes_cells_hcal; //mapping of nodes by cell number:

  ifstream logicfile_hcal(logicfilename_hcal);

  current_node = 1;
  //  bool first_cell = true;

  while( currentline.ReadLine(logicfile_hcal) ){
    if( !currentline.BeginsWith("#") ){
      TObjArray *tokens = currentline.Tokenize(" ");
      int ntokens = tokens->GetEntries();
      if( ntokens >= 11 ){
	cout << currentline.Data() << ", ntokens = " << ntokens << endl;

	TString snode = ( (TObjString*) (*tokens)[0] )->GetString();
	int nodenumber = snode.Atoi();
	
	TString scell = ( (TObjString*) (*tokens)[1] )->GetString();
	int cellnumber = scell.Atoi();
	
	TString speakpos = ( (TObjString*) (*tokens)[8] )->GetString();
	double mean = speakpos.Atof();
	
	TString ssigma = ( (TObjString*) (*tokens)[9] )->GetString();
	double sigma = ssigma.Atof();

	TString sthreshold = ( (TObjString*) (*tokens)[10] )->GetString();
	double threshold = sthreshold.Atof();

	TString srow = ( (TObjString*) (*tokens)[2] )->GetString();
	TString scol = ( (TObjString*) (*tokens)[3] )->GetString();

	std::pair<int,int> rowcoltemp( srow.Atoi(), scol.Atoi() );

	cell_rowcol_hcal[rowcoltemp] = cellnumber;
	
	list_of_nodes_hcal.insert( nodenumber );

	cells_logic_sums_hcal[nodenumber].insert( cellnumber );

	logic_mean_hcal[nodenumber] = mean;
	logic_sigma_hcal[nodenumber] = sigma;
	threshold_hcal[nodenumber] = threshold;

	nodes_cells_hcal[ cellnumber ].insert(nodenumber);
	
      }
    }
  }
  
  TH1D::SetDefaultSumw2();

  //double PI = TMath::Pi();

  //Photoelectron statistics:
  double phe_per_GeV_ECAL = 1000.0/1.33; //~ 750 pe/GeV
  double phe_per_GeV_HCAL = 1000.0/0.30; //~ 3,333 pe/GeV (but sampling fraction is small)

  //read in alternate threshold:
  ifstream thresholdfile_ecal(thresholdfilename_ecal);
  if( thresholdfile_ecal ){
    int node;
    double mean,sigma;
    while( thresholdfile_ecal >> node >> mean >> sigma ){
      if( list_of_nodes_ecal.find( node ) != list_of_nodes_ecal.end() ){
	logic_mean_ecal[ node ] = mean;
	logic_sigma_ecal[ node ] = sigma;
      }
    }
  }

  //read in alternate threshold:
  ifstream thresholdfile_hcal(thresholdfilename_hcal);
  if( thresholdfile_hcal ){
    int node;
    double mean,sigma;
    while( thresholdfile_hcal >> node >> mean >> sigma ){
      if( list_of_nodes_hcal.find( node ) != list_of_nodes_hcal.end() ){
	logic_mean_hcal[ node ] = mean;
	logic_sigma_hcal[ node ] = sigma;
      }
    }
  }

  ifstream assocfile( assocfilename );

  bool use_ECAL_HCAL_associations=false;
  map<int, set<int> > ECAL_nodes_HCAL;
  if( assocfile ){
    while( !assocfile.eof() ){
      int hcalnode, N;
      assocfile >> hcalnode >> N;
      for( int i=0; i<N; i++ ){
	int ecalnode;
	assocfile >> ecalnode;

	ECAL_nodes_HCAL[hcalnode].insert(ecalnode);
      }
    }
  }
  
  fout->cd();

  // TH1D *hrate_vs_threshold_ECAL = new TH1D("hrate_vs_threshold_ECAL","",30,0.0,1.5);
  // //TH1D *hnum_logic_sums_fired_vs_threshold = new TH1D("hnum_logic_sums_fired_vs_threshold

  // TH1D *hrate_vs_threshold_HCAL = new TH1D("hrate_vs_threshold_HCAL","",40,0.0,2.0);

  //TH2D *htrue_coincidence_rate_vs_threshold_ECAL_HCAL = new TH2D("htrue_coincidence_rate_vs_threshold_ECAL_HCAL","",40,0,2.0,30,0,1.5);
  
  TH2D *hnphesum_vs_node_ECAL_all = new TH2D("hnphesum_vs_node_ECAL_all","",list_of_nodes_ecal.size(),0.5,list_of_nodes_ecal.size()+0.5,100,0.0,5000.0);
  TH2D *hnphesum_vs_node_HCAL_all = new TH2D("hnphesum_vs_node_HCAL_all","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,100,0.0,3500.0);

  //TH2D *hnphesum_vs_node_ECAL_FTcut = new TH2D("hnphesum_vs_node_ECAL_FTcut","",list_of_nodes_ecal.size(),0.5,list_of_nodes_ecal.size()+0.5,100,0.0,5000.0);
  TH2D *hnphesum_vs_node_HCAL_FTcut = new TH2D("hnphesum_vs_node_HCAL_FTcut","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,100,0.0,3500.0);
  TH2D *hnphesum_vs_node_HCAL_FPP1cut = new TH2D("hnphesum_vs_node_HCAL_FPP1cut","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,100,0.0,3500.0);
  TH2D *hnphesum_vs_node_HCAL_FPP2cut = new TH2D("hnphesum_vs_node_HCAL_FPP2cut","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,100,0.0,3500.0);
  TH2D *hnphesum_vs_node_HCAL_FPPbothcut = new TH2D("hnphesum_vs_node_HCAL_FPPbothcut","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,100,0.0,3500.0);
  TH2D *hnphesum_vs_node_HCAL_FPPeithercut = new TH2D("hnphesum_vs_node_HCAL_FPPeithercut","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,100,0.0,3500.0);

  TH2D *hnphesum_vs_node_HCALmax_all = new TH2D("hnphesum_vs_node_HCALmax_all","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,100,0.0,3500.0);
  TH2D *hnphesum_vs_node_HCALmax_FTcut = new TH2D("hnphesum_vs_node_HCALmax_FTcut","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,100,0.0,3500.0);
  TH2D *hnphesum_vs_node_HCALmax_FPP1cut = new TH2D("hnphesum_vs_node_HCALmax_FPP1cut","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,100,0.0,3500.0);
  TH2D *hnphesum_vs_node_HCALmax_FPP2cut = new TH2D("hnphesum_vs_node_HCALmax_FPP2cut","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,100,0.0,3500.0);
  TH2D *hnphesum_vs_node_HCALmax_FPPbothcut = new TH2D("hnphesum_vs_node_HCALmax_FPPbothcut","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,100,0.0,3500.0);
  TH2D *hnphesum_vs_node_HCALmax_FPPeithercut = new TH2D("hnphesum_vs_node_HCALmax_FPPeithercut","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,100,0.0,3500.0);
  
  
  TH2D *hmaxnode_ECAL_vs_HCAL = new TH2D("hmaxnode_ECAL_vs_HCAL","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,list_of_nodes_ecal.size(),0.5,list_of_nodes_ecal.size()+0.5);
  TH2D *hallnodes_ECAL_vs_HCAL = new TH2D("hallnodes_ECAL_vs_HCAL","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,list_of_nodes_ecal.size(),0.5,list_of_nodes_ecal.size()+0.5);

  TH1D *hshouldhit_vs_threshold_ECAL = new TH1D("hshouldhit_vs_threshold_ECAL","",30,0.025,1.525);
  TH1D *hefficiency_vs_threshold_ECAL = new TH1D("hefficiency_vs_threshold_ECAL","",30,0.025,1.525);
  TH1D *hshouldhit_vs_threshold_ECAL_FTcut = new TH1D("hshouldhit_vs_threshold_ECAL_FTcut","",30,0.025,1.525);
  TH1D *hefficiency_vs_threshold_ECAL_FTcut = new TH1D("hefficiency_vs_threshold_ECAL_FTcut","",30,0.025,1.525);
  
  TH1D *hefficiency_vs_threshold_HCAL_FTcut = new TH1D("hefficiency_vs_threshold_HCAL_FTcut","",30,0.025,1.525);
  TH1D *hefficiency_vs_threshold_HCAL_FPP1cut = new TH1D("hefficiency_vs_threshold_HCAL_FPP1cut","",30,0.025,1.525);
  TH1D *hefficiency_vs_threshold_HCAL_FPP2cut = new TH1D("hefficiency_vs_threshold_HCAL_FPP2cut","",30,0.025,1.525);

  TH2D *hefficiency_vs_threshold_ECAL_HCAL_coincidence_FTcut = new TH2D("hefficiency_vs_threshold_ECAL_HCAL_coincidence_FTcut","",30,0.025,1.525,30,0.025,1.525);
  TH2D *hshouldhit_vs_threshold_ECAL_HCAL_coincidence_FTcut = new TH2D("hshouldhit_vs_threshold_ECAL_HCAL_coincidence_FTcut","",30,0.025,1.525,30,0.025,1.525);

  TH2D *hefficiency_vs_threshold_ECAL_HCAL_coincidence_FPP1cut = new TH2D("hefficiency_vs_threshold_ECAL_HCAL_coincidence_FPP1cut","",30,0.025,1.525,30,0.025,1.525);
  TH2D *hshouldhit_vs_threshold_ECAL_HCAL_coincidence_FPP1cut = new TH2D("hshouldhit_vs_threshold_ECAL_HCAL_coincidence_FPP1cut","",30,0.025,1.525,30,0.025,1.525);

  TH2D *hefficiency_vs_threshold_ECAL_HCAL_coincidence_FPP2cut = new TH2D("hefficiency_vs_threshold_ECAL_HCAL_coincidence_FPP2cut","",30,0.025,1.525,30,0.025,1.525);
  TH2D *hshouldhit_vs_threshold_ECAL_HCAL_coincidence_FPP2cut = new TH2D("hshouldhit_vs_threshold_ECAL_HCAL_coincidence_FPP2cut","",30,0.025,1.525,30,0.025,1.525);
  
  TH1D *hshouldhit_HCAL_FTcut = new TH1D("hshouldhit_HCAL_FTcut","",30,0.025,1.525);
  TH1D *hshouldhit_HCAL_FPP1cut = new TH1D("hshouldhit_HCAL_FPP1cut","",30,0.025,1.525);
  TH1D *hshouldhit_HCAL_FPP2cut = new TH1D("hshouldhit_HCAL_FPP2cut","",30,0.025,1.525);
  
  TH2D *hnphe_vs_sum_edep_ECAL = new TH2D("hnphe_vs_sum_edep_ECAL","",125,0.0,5.0,125,0.0,5000.0 );
  TH2D *hnphe_vs_sum_edep_HCAL = new TH2D("hnphe_vs_sum_edep_HCAL","",125,0.0,0.75,125,0.0,2500.0 );

  TH1D *hthetaFPP1 = new TH1D("hthetaFPP1","",120,0.0,12.0);
  TH1D *hthetaFPP2 = new TH1D("hthetaFPP2","",120,0.0,12.0);

  TH1D *hthetaFPP1_cointrig = new TH1D("hthetaFPP1_cointrig","",120,0.0,12.0);
  TH1D *hthetaFPP2_cointrig = new TH1D("hthetaFPP2_cointrig","",120,0.0,12.0);

  TH1D *hshouldhit_vs_Q2_ECAL_FTcut = new TH1D("hshouldhit_vs_Q2_ECAL_FTcut","",100,8.0,16.0);
  TH1D *hefficiency_vs_Q2_ECAL_FTcut = new TH1D("hefficiency_vs_Q2_ECAL_FTcut","",100,8.0,16.0);

  
  
  double Ibeam = 75.0e-6; //Amps
  double Ltarget = 40.0; //cm
  double e = 1.602e-19; //electron charge;
  double rho_target = 0.072; //g/cm^3
  double N_A = 6.022e23; //atoms/mol:
  double Mmol_H = 1.008; //g/mol
  double Lumi = rho_target * Ltarget * N_A / Mmol_H * Ibeam/e; //~ 8e38;
  
  TRandom3 num(0);

  cout << "Entering event loop " << endl;
  
  long nevent=0;
  for( nevent=0; nevent<C->GetEntries(); ++nevent ){
    T->GetEntry(nevent);

    double weight;
    //cross section is given in mb: 1 mb = 1e-3 * 1e-24 = 1e-27 cm^2
    // if (pythia6flag != 0 ){
    //   weight = Lumi * T->primaries_Sigma * 1.0e-27/ double(ngen); //luminosity times cross section / number of events generated.
    // } else {
    weight = T->ev_rate / double(nfiles);

    if( Q2cut == 0 || (T->ev_Q2 >= 10.5 && T->ev_Q2 <= 14.0) ){
    
      bool FTtrack = false;
      int itrack_FT=-1;
      for( int itrack=0; itrack<T->Harm_FT_Track_ntracks; itrack++ ){
	if( (*(T->Harm_FT_Track_MID))[itrack] == 0 &&
	    (*(T->Harm_FT_Track_PID))[itrack] == 2212 ){ //primary elastically scattered proton track in FT:
	  FTtrack = true;
	  itrack_FT = itrack;
	}
      }

      TVector3 nhat_FT, nhat_FPP1, nhat_FPP2;
      if( FTtrack ){
	nhat_FT.SetXYZ( (*(T->Harm_FT_Track_Xp))[itrack_FT],
			(*(T->Harm_FT_Track_Yp))[itrack_FT],
			1.0 );
	nhat_FT = nhat_FT.Unit();
      }

      double thetaFPP1, thetaFPP2, pFPP1, pFPP2;
      bool FPP1track = false, FPP2track = false;
      //    if( FTtrack )
      if( T->Harm_FPP1_Track_ntracks > 0 && FTtrack ){
	for( int itrack=0; itrack<T->Harm_FPP1_Track_ntracks; itrack++ ){
	  if( (*(T->Harm_FPP1_Track_MID))[itrack] == 0 ){
	    nhat_FPP1.SetXYZ( (*(T->Harm_FPP1_Track_Xp))[itrack],
			      (*(T->Harm_FPP1_Track_Yp))[itrack],
			      1.0 );
	    nhat_FPP1 = nhat_FPP1.Unit();
	    thetaFPP1 = acos( nhat_FPP1.Dot( nhat_FT ) );
	    pFPP1 = (*(T->Harm_FPP1_Track_P))[itrack];
	    FPP1track = thetaFPP1 < 12.0*PI/180.0 && pFPP1 >= 0.5*T->ev_np;
	    if( FPP1track ) hthetaFPP1->Fill(thetaFPP1*180.0/PI,weight);
	  }
	}
      }

      if( T->Harm_FPP2_Track_ntracks > 0 && FTtrack && FPP1track){
	for( int itrack=0; itrack<T->Harm_FPP2_Track_ntracks; itrack++ ){
	  if( (*(T->Harm_FPP2_Track_MID))[itrack] == 0 ){
	    nhat_FPP2.SetXYZ( (*(T->Harm_FPP2_Track_Xp))[itrack],
			      (*(T->Harm_FPP2_Track_Yp))[itrack],
			      1.0 );
	    nhat_FPP2 = nhat_FPP2.Unit();
	    thetaFPP2 = acos( nhat_FPP2.Dot( nhat_FPP1 ) );
	    pFPP2 = (*(T->Harm_FPP2_Track_P))[itrack];
	    //FPP2track = thetaFPP2 < 24.0*PI/180.0 && pFPP2/T->ev_np > 0.5;
	    FPP2track = thetaFPP2 < 12.0*PI/180.0 && pFPP2/T->ev_np > 0.5;
	    if( FPP2track ) hthetaFPP2->Fill(thetaFPP2*180.0/PI,weight);
	  }
	}
      }
      
      double nu = T->ev_Q2 / 2.0 / 0.938272;
      double pp_elastic = sqrt(pow(nu,2)+2.0*.938272*nu);
    
   
      //}

      double R = T->gen_dbb;
      double thetacal = T->gen_thbb;
    
      //ECAL is on beam left:
      TVector3 nhat_e( sin( T->ev_th )*cos( T->ev_ph ), sin(T->ev_th)*sin(T->ev_ph), cos(T->ev_th) );
      TVector3 vertex( T->ev_vx, T->ev_vy, T->ev_vz );
      TVector3 ecal_z( sin(thetacal), 0, cos(thetacal) );
      TVector3 ecal_y(0,1,0);
      TVector3 ecal_x = (ecal_y.Cross(ecal_z)).Unit();

      TVector3 Rcalo = R * ecal_z;
      //ecal_z dot (vertex + s * nhat_e - Rcalo ) = 0;
      double s = (Rcalo - vertex).Dot( ecal_z )/ ( nhat_e.Dot( ecal_z ) );

      TVector3 pos_calo = vertex + s * nhat_e;

      double xcalo = (pos_calo - Rcalo).Dot( ecal_x );
      double ycalo = (pos_calo - Rcalo).Dot( ecal_y ); //
    
      if( (nevent+1) % 1000 == 0 ){ cout << "Event number " << nevent+1 << ", event weight = " << weight << endl; }
    
      map<int,double> node_sums; //initialize all node sums to zero:
      for( set<int>::iterator inode = list_of_nodes_ecal.begin(); inode != list_of_nodes_ecal.end(); ++inode ){
	node_sums[ *inode ] = 0.0;
      }

      bool should_hit_ECAL = false;

      if( ycalo >= ycellmin && ycalo <= ycellmax ){
	//make an initial guess at which row: (row runs from 1 to N):
	int closest_row = int( (ycalo - ycellmin)/4.0 ) + 1;

	map<int,double>::iterator rowguess = ycell_rows.find( closest_row );

	while( rowguess != ycell_rows.end() && ycalo > ycell_rows[rowguess->first] + 0.5*cellsize_rows[rowguess->first] ){ ++rowguess; }
	while( rowguess != ycell_rows.end() && ycalo < ycell_rows[rowguess->first] - 0.5*cellsize_rows[rowguess->first] ){ --rowguess; }

	if( rowguess != ycell_rows.end() ){
	  closest_row = rowguess->first;
	  if( xcalo >= xcellmin_rows[closest_row] + 0.5*cellsize_rows[closest_row] &&
	      xcalo <= xcellmax_rows[closest_row] - 0.5*cellsize_rows[closest_row] &&
	      ycalo >= ycellmin + 0.5*cellsize_rows[closest_row] && ycalo <= ycellmax - 0.5*cellsize_rows[closest_row] ){
	    should_hit_ECAL = true;
	  }
	}
      }

      int nphe = 0;
    
      if( pheflag == 0 ){
	for( int ihit = 0; ihit<T->Earm_ECalTF1_hit_nhits; ihit++ ){
	  int rowhit = ( *(T->Earm_ECalTF1_hit_row))[ihit]+1;
	  int colhit = ( *(T->Earm_ECalTF1_hit_col))[ihit]+1;
	  std::pair<int,int> rowcolhit( rowhit,colhit );
	
	  int cellhit = cell_rowcol_ecal[rowcolhit];
	
	  //int trigger_group = nodes_cells_ecal[cellhit];
	
	  double edep = (*(T->Earm_ECalTF1_hit_sumedep))[ihit];

	  double mean = 752.2*edep;
	  double sigma = 52.0*sqrt(edep) + 20.76*edep;

	  nphe = TMath::Max(0,TMath::Nint(num.Gaus(mean,sigma)));
	
	  for( set<int>::iterator inode = nodes_cells_ecal[cellhit].begin(); inode != nodes_cells_ecal[cellhit].end(); ++inode ){
	    node_sums[ *inode ] += double(nphe);
	  }
	
	}
      } else {
	for( int ihit = 0; ihit<T->Earm_ECAL_hit_nhits; ihit++){
	  int rowhit = ( *(T->Earm_ECAL_hit_row))[ihit]+1;
	  int colhit = ( *(T->Earm_ECAL_hit_col))[ihit]+1;
	  std::pair<int,int> rowcolhit( rowhit,colhit );
	
	  int cellhit = cell_rowcol_ecal[rowcolhit];
	
	  //int trigger_group = nodes_cells_ecal[cellhit];
	
	  //	double edep = (*(T->Earm_ECalTF1_hit_sumedep))[ihit];

	  int nphe = (*(T->Earm_ECAL_hit_NumPhotoelectrons))[ihit];
	
	  for( set<int>::iterator inode = nodes_cells_ecal[cellhit].begin(); inode != nodes_cells_ecal[cellhit].end(); ++inode ){
	    node_sums[ *inode ] += double(nphe);
	  }
	  for( int jhit=0; jhit<T->Earm_ECalTF1_hit_nhits; jhit++ ){
	    if( (*(T->Earm_ECalTF1_hit_row))[jhit]+1 == rowhit &&
		(*(T->Earm_ECalTF1_hit_col))[jhit]+1 == colhit &&
		fabs( (*(T->Earm_ECAL_hit_Time_avg))[ihit]-(*(T->Earm_ECalTF1_hit_tavg))[jhit]-2.5)<=10.0 ){
	      hnphe_vs_sum_edep_ECAL->Fill( (*(T->Earm_ECalTF1_hit_sumedep))[jhit], nphe );
	    }   
	  }
	}
      
	//node_sums[ trigger_group ] += double(nphe);
      }

      vector<int> trigger_nodes_fired(hefficiency_vs_threshold_ECAL->GetNbinsX());
      for( int ithr=0; ithr<hefficiency_vs_threshold_ECAL->GetNbinsX(); ithr++ ){
	trigger_nodes_fired[ithr] = 0;
      }

      int maxnode_ECAL=-1;
      int maxnode_HCAL=-1;
      double maxsum_ECAL = 0.0;
      double maxsum_HCAL = 0.0;

      bool ECALtrig_nominal = false;
    
      int nominal_threshold_bin_HCAL = hefficiency_vs_threshold_HCAL_FTcut->FindBin(nominal_threshold_HCAL);
      int nominal_threshold_bin_ECAL = hefficiency_vs_threshold_ECAL->FindBin(nominal_threshold_ECAL);
    
      for( set<int>::iterator inode = list_of_nodes_ecal.begin(); inode != list_of_nodes_ecal.end(); ++inode ){
	for( int bin=1; bin<=hefficiency_vs_threshold_ECAL->GetNbinsX(); bin++ ){
	  if( node_sums[*inode]/logic_mean_ecal[*inode] > hefficiency_vs_threshold_ECAL->GetBinCenter(bin) ){
	    //cout << "node above threshold, nphe, peak position = " << node_sums[*inode] << ", " << logic_mean_ecal[*inode] << endl;
	    trigger_nodes_fired[bin-1]++;
	    if( bin == nominal_threshold_bin_ECAL ) ECALtrig_nominal = true;
	  }
	
	}
	if( node_sums[*inode] > maxsum_ECAL ) {
	  maxsum_ECAL = node_sums[*inode];
	  maxnode_ECAL = *inode;
	}
      
	if( node_sums[*inode] > 0.0 ) hnphesum_vs_node_ECAL_all->Fill( *inode, node_sums[*inode], weight );
      }

      if( should_hit_ECAL ){
	for( int ithr=0; ithr<hefficiency_vs_threshold_ECAL->GetNbinsX(); ithr++ ){
	  hshouldhit_vs_threshold_ECAL->Fill( hefficiency_vs_threshold_ECAL->GetBinCenter(ithr+1), weight );
	  if( trigger_nodes_fired[ithr] > 0 ){
	    hefficiency_vs_threshold_ECAL->Fill( hefficiency_vs_threshold_ECAL->GetBinCenter(ithr+1), weight );
	  }
	  if( FTtrack ){
	    hshouldhit_vs_threshold_ECAL_FTcut->Fill( hefficiency_vs_threshold_ECAL->GetBinCenter(ithr+1), weight );
	    if( trigger_nodes_fired[ithr] > 0 ){
	      hefficiency_vs_threshold_ECAL_FTcut->Fill( hefficiency_vs_threshold_ECAL->GetBinCenter(ithr+1), weight );
	    }
	  }
	}
      }

      if( FTtrack ){
	hshouldhit_vs_Q2_ECAL_FTcut->Fill( T->ev_Q2, weight );
	if( ECALtrig_nominal ){
	  hefficiency_vs_Q2_ECAL_FTcut->Fill( T->ev_Q2, weight );
	}
      }
    
      map<int,double> node_sums_hcal;
      for( set<int>::iterator inode = list_of_nodes_hcal.begin(); inode != list_of_nodes_hcal.end(); ++inode ){
	node_sums_hcal[*inode] = 0.0;
      }

      //int nphe = 0;
    
      if( pheflag == 0 ){
	for( int ihit=0; ihit<T->Harm_HCalScint_hit_nhits; ihit++ ){
	  int rowhit = (*(T->Harm_HCalScint_hit_row))[ihit]+1;
	  int colhit = (*(T->Harm_HCalScint_hit_col))[ihit]+1;
	  std::pair<int,int> rowcolhit(rowhit,colhit);
	  int cellhit = cell_rowcol_hcal[rowcolhit];
	  //int trigger_group = nodes_cells_hcal[cellhit];
	  double edep = (*(T->Harm_HCalScint_hit_sumedep))[ihit];
	  //nphe = num.Poisson( phe_per_GeV_HCAL * edep );
	  double mean = 2981.0*edep;
	  double sigma = 69.54*sqrt(edep) + 155.3*edep;

	  nphe = TMath::Max(0,TMath::Nint(num.Gaus(mean,sigma)));
	
	  //cout << "HCAL hit " << ihit+1 << " node, edep, nphe = " << trigger_group << ", " << edep << ", " << nphe << endl;
	  //node_sums_hcal[trigger_group] += double(nphe);
	  for( set<int>::iterator inode = nodes_cells_hcal[cellhit].begin(); inode != nodes_cells_hcal[cellhit].end(); ++inode ){
	  
	    node_sums_hcal[*inode] += double(nphe);
	  
	  }
	}
      } else {
	for( int jhit=0; jhit<T->Harm_HCal_hit_nhits; jhit++ ){
	  int rowhit = (*(T->Harm_HCal_hit_row))[jhit]+1;
	  int colhit = (*(T->Harm_HCal_hit_col))[jhit]+1;
	  std::pair<int,int> rowcolhit(rowhit,colhit);
	  int cellhit = cell_rowcol_hcal[rowcolhit];
	  nphe = (*(T->Harm_HCal_hit_NumPhotoelectrons))[jhit];
	  for( set<int>::iterator inode = nodes_cells_hcal[cellhit].begin(); inode != nodes_cells_hcal[cellhit].end(); ++inode ){
	  
	    node_sums_hcal[*inode] += double(nphe);
	  
	  }

	  for( int khit=0; khit<T->Harm_HCalScint_hit_nhits; khit++ ){
	    if( (*(T->Harm_HCalScint_hit_row))[khit]+1 == rowhit &&
		(*(T->Harm_HCalScint_hit_col))[khit]+1 == colhit &&
		fabs( (*(T->Harm_HCal_hit_Time_avg))[jhit]-(*(T->Harm_HCalScint_hit_tavg))[khit] - 8.6 )<=15.0 ){
	      hnphe_vs_sum_edep_HCAL->Fill( (*(T->Harm_HCalScint_hit_sumedep))[khit], nphe );
	    }
	  }
	
	}
      }
    
      vector<int> trigger_nodes_fired_hcal(hefficiency_vs_threshold_HCAL_FTcut->GetNbinsX());
      for( int ithr=0; ithr<hefficiency_vs_threshold_HCAL_FTcut->GetNbinsX(); ithr++ ){
	trigger_nodes_fired_hcal[ithr] = 0;
      }

      vector<int> coin_trigger_fired( hefficiency_vs_threshold_HCAL_FTcut->GetNbinsX()*hefficiency_vs_threshold_ECAL->GetNbinsX() );
      for( int ithr=0; ithr<coin_trigger_fired.size(); ithr++ ){
	coin_trigger_fired[ithr] = 0;
      }

    

      bool cointrig_nominal_threshold = false;
    
      for( set<int>::iterator inode = list_of_nodes_hcal.begin(); inode != list_of_nodes_hcal.end(); ++inode ){
	for( int bin=1; bin<=hefficiency_vs_threshold_HCAL_FTcut->GetNbinsX(); bin++ ){
	  if( node_sums_hcal[*inode]/logic_mean_hcal[*inode] > hefficiency_vs_threshold_HCAL_FTcut->GetBinCenter(bin) ){ //this HCAL sum fired:
	    trigger_nodes_fired_hcal[bin-1]++;
	    for( set<int>::iterator enode = list_of_nodes_ecal.begin(); enode != list_of_nodes_ecal.end(); ++enode ){
	      if( ECAL_nodes_HCAL[*inode].find(*enode) != ECAL_nodes_HCAL[*inode].end() ){ //Check associated ECAL trigger sums:
		for( int ebin=1; ebin<=hefficiency_vs_threshold_ECAL->GetNbinsX(); ebin++ ){ //check ECAL sums:
		  if( node_sums[ *enode ]/logic_mean_ecal[*enode] > hefficiency_vs_threshold_ECAL->GetBinCenter(ebin) ){ //this ECAL sum fired:
		    coin_trigger_fired[ (ebin-1) + (bin-1)*hefficiency_vs_threshold_ECAL->GetNbinsX() ]++;
		    if( ebin == nominal_threshold_bin_ECAL && bin == nominal_threshold_bin_HCAL ){
		      cointrig_nominal_threshold = true;
		    }
		  }
		}
	      } 
	    }
	  }
	}
	if( node_sums_hcal[*inode] > maxsum_HCAL ) {
	  maxsum_HCAL = node_sums_hcal[*inode];
	  maxnode_HCAL = *inode;
	}

	hnphesum_vs_node_HCAL_all->Fill( *inode, node_sums_hcal[*inode], weight );
	if( FTtrack ){
	  hnphesum_vs_node_HCAL_FTcut->Fill( *inode, node_sums_hcal[*inode], weight );
	  if( FPP1track ) hnphesum_vs_node_HCAL_FPP1cut->Fill( *inode, node_sums_hcal[*inode], weight );
	  if( FPP2track ) hnphesum_vs_node_HCAL_FPP2cut->Fill( *inode, node_sums_hcal[*inode], weight );
	  if( FPP1track && FPP2track ) hnphesum_vs_node_HCAL_FPPbothcut->Fill( *inode, node_sums_hcal[*inode], weight );
	  if( FPP1track || FPP2track ) hnphesum_vs_node_HCAL_FPPeithercut->Fill( *inode, node_sums_hcal[*inode], weight );
	}
      }

      if( cointrig_nominal_threshold ){
	if( FPP1track ) hthetaFPP1_cointrig->Fill(thetaFPP1*180.0/PI,weight);
	if( FPP2track ) hthetaFPP2_cointrig->Fill(thetaFPP2*180.0/PI,weight);
      }
    
      for( int bin=1; bin<=hefficiency_vs_threshold_HCAL_FTcut->GetNbinsX(); bin++ ){
	if( FTtrack ) hshouldhit_HCAL_FTcut->Fill( hefficiency_vs_threshold_HCAL_FTcut->GetBinCenter(bin), weight );
	if( FTtrack && FPP1track ) hshouldhit_HCAL_FPP1cut->Fill( hefficiency_vs_threshold_HCAL_FTcut->GetBinCenter(bin), weight );
	if( FTtrack && FPP2track ) hshouldhit_HCAL_FPP2cut->Fill( hefficiency_vs_threshold_HCAL_FTcut->GetBinCenter(bin), weight );
	if( trigger_nodes_fired_hcal[bin-1] > 0 ){
	  if( FTtrack ){
	    hefficiency_vs_threshold_HCAL_FTcut->Fill( hefficiency_vs_threshold_HCAL_FTcut->GetBinCenter(bin), weight );
	    if( FPP1track ) hefficiency_vs_threshold_HCAL_FPP1cut->Fill( hefficiency_vs_threshold_HCAL_FTcut->GetBinCenter(bin), weight );
	    if( FPP2track ) hefficiency_vs_threshold_HCAL_FPP2cut->Fill( hefficiency_vs_threshold_HCAL_FTcut->GetBinCenter(bin), weight );
	  }
	}
      }

      for( int ithr=0; ithr<coin_trigger_fired.size(); ithr++ ){
	int bin_e = ithr%(hefficiency_vs_threshold_ECAL->GetNbinsX())+1;
	int bin_h = ithr/(hefficiency_vs_threshold_HCAL_FTcut->GetNbinsX())+1;
	double thr_e = hefficiency_vs_threshold_ECAL_HCAL_coincidence_FTcut->GetYaxis()->GetBinCenter(bin_e);
	double thr_h = hefficiency_vs_threshold_ECAL_HCAL_coincidence_FTcut->GetXaxis()->GetBinCenter(bin_h);
	if( FTtrack ) hshouldhit_vs_threshold_ECAL_HCAL_coincidence_FTcut->Fill( thr_h, thr_e, weight );
	if( FTtrack && FPP1track ) hshouldhit_vs_threshold_ECAL_HCAL_coincidence_FPP1cut->Fill( thr_h, thr_e, weight );
	if( FTtrack && FPP2track ) hshouldhit_vs_threshold_ECAL_HCAL_coincidence_FPP2cut->Fill( thr_h, thr_e, weight );
	if( coin_trigger_fired[ithr] > 0 ){
	  if( FTtrack ) hefficiency_vs_threshold_ECAL_HCAL_coincidence_FTcut->Fill( thr_h, thr_e, weight );
	  if( FTtrack && FPP1track ) hefficiency_vs_threshold_ECAL_HCAL_coincidence_FPP1cut->Fill( thr_h, thr_e, weight );
	  if( FTtrack && FPP2track ) hefficiency_vs_threshold_ECAL_HCAL_coincidence_FPP2cut->Fill( thr_h, thr_e, weight );
	}
      }
    
      hnphesum_vs_node_HCALmax_all->Fill( maxnode_HCAL, node_sums_hcal[maxnode_HCAL], weight );
      if( FTtrack ){
	hnphesum_vs_node_HCALmax_FTcut->Fill( maxnode_HCAL, node_sums_hcal[maxnode_HCAL], weight );
	if( FPP1track ) hnphesum_vs_node_HCALmax_FPP1cut->Fill( maxnode_HCAL, node_sums_hcal[maxnode_HCAL], weight );
	if( FPP2track ) hnphesum_vs_node_HCALmax_FPP2cut->Fill( maxnode_HCAL, node_sums_hcal[maxnode_HCAL], weight );
	if( FPP1track && FPP2track ) hnphesum_vs_node_HCALmax_FPPbothcut->Fill( maxnode_HCAL, node_sums_hcal[maxnode_HCAL], weight );
	if( FPP1track || FPP2track ) hnphesum_vs_node_HCALmax_FPPeithercut->Fill( maxnode_HCAL, node_sums_hcal[maxnode_HCAL], weight );
      }
    
      // for( int ithr=0; ithr<hefficiency_vs_threshold_HCAL_FTcut->GetNbinsX(); ithr++ ){
      //   if( trigger_nodes_fired_hcal[ithr] > 0 ) hefficiency_vs_threshold_HCAL_FTcut->Fill( hefficiency_vs_threshold_HCAL_FTcut->GetBinCenter(ithr+1),weight );
      //   for( int jthr=0; jthr<hefficiency_vs_threshold_ECAL->GetNbinsX(); jthr++ ){
      // 	if( trigger_nodes_fired[jthr] > 0 && trigger_nodes_fired_hcal[ithr] > 0 ){
      // 	  //htrue_coincidence_rate_vs_threshold_ECAL_HCAL->Fill( hefficiency_vs_threshold_HCAL_FTcut->GetBinCenter(ithr+1),hefficiency_vs_threshold_ECAL->GetBinCenter(jthr+1),weight );
      // 	}
      //   }
      // }

      // for( set<int>::iterator inode = list_of_nodes_ecal.begin(); inode != list_of_nodes_ecal.end(); ++inode ){
      //   for( set<int>::iterator jnode = list_of_nodes_hcal.begin(); jnode != list_of_nodes_hcal.end(); ++jnode ){
      // 	//Fill the correlation histogram for all true coincidence events for which ECAL and HCAL node are both above threshold:
      // 	if( node_sums[*inode] >= nominal_threshold_ECAL*logic_mean_ecal[*inode] && node_sums_hcal[*jnode] >= nominal_threshold_HCAL*logic_mean_hcal[*jnode] ){
      // 	  hallnodes_ECAL_vs_HCAL->Fill( *jnode, *inode, weight );
      // 	}
      //   }
      // }
      //if( maxsum_ECAL >= nominal_threshold_ECAL*logic_mean_ecal[maxnode_ECAL] && maxsum_HCAL >= nominal_threshold_HCAL*logic_mean_hcal[maxnode_HCAL] ){
      if( FTtrack && FPP2track) {
	hmaxnode_ECAL_vs_HCAL->Fill( maxnode_HCAL, maxnode_ECAL, weight );
      }
      //}
    }
  }

  hefficiency_vs_threshold_HCAL_FTcut->Divide( hshouldhit_HCAL_FTcut );
  hefficiency_vs_threshold_HCAL_FPP1cut->Divide( hshouldhit_HCAL_FPP1cut );
  hefficiency_vs_threshold_HCAL_FPP2cut->Divide( hshouldhit_HCAL_FPP2cut );

  hefficiency_vs_threshold_ECAL_HCAL_coincidence_FTcut->Divide( hshouldhit_vs_threshold_ECAL_HCAL_coincidence_FTcut );
  hefficiency_vs_threshold_ECAL_HCAL_coincidence_FPP1cut->Divide( hshouldhit_vs_threshold_ECAL_HCAL_coincidence_FPP1cut );
  hefficiency_vs_threshold_ECAL_HCAL_coincidence_FPP2cut->Divide( hshouldhit_vs_threshold_ECAL_HCAL_coincidence_FPP2cut );
  
  // TCanvas *c1 = new TCanvas("c1","c1",1200,900);
  
  // c1->Divide(2,1);

  // c1->cd(1)->SetLogy();
  // hefficiency_vs_threshold_ECAL->SetMarkerStyle(20);
  // hefficiency_vs_threshold_ECAL->Draw();
  
  // c1->cd(2)->SetLogy();
  // hefficiency_vs_threshold_HCAL_FTcut->SetMarkerStyle(20);
  // hefficiency_vs_threshold_HCAL_FTcut->Draw();

  hefficiency_vs_threshold_ECAL->Divide( hshouldhit_vs_threshold_ECAL );
  hefficiency_vs_threshold_ECAL_FTcut->Divide(hshouldhit_vs_threshold_ECAL_FTcut );
  
  hefficiency_vs_threshold_HCAL_FTcut->SetMarkerStyle(20);
  hefficiency_vs_threshold_ECAL->SetMarkerStyle(20);

  hefficiency_vs_Q2_ECAL_FTcut->Divide(hshouldhit_vs_Q2_ECAL_FTcut);
  
  fout->Write();
  fout->Close();
}
Example #27
0
KVTGID* KVTGID::ReadFromAsciiFile(const Char_t* name, ifstream& gridfile)
{
   // Read parameters of LTG fit in file (which must have been written with
   // current version of KVTGID::WriteToAsciiFile)

   KVTGID* LTGfit = 0;
   Int_t Ftyp, Flite, FZorA, Fmass;
   FZorA = Fmass = Ftyp = Flite = 0;

   KVString line;
   line.ReadLine(gridfile);
   TString buff = GetValue(line, '=');
   Ftyp = buff.Atoi();
   line.ReadLine(gridfile);
   buff = GetValue(line, '=');
   Flite = buff.Atoi();
   line.ReadLine(gridfile);
   buff = GetValue(line, '=');
   FZorA = buff.Atoi();
   if (FZorA) {
      line.ReadLine(gridfile);
      buff = GetValue(line, '=');
      Fmass = buff.Atoi();
   }

   LTGfit = MakeTGID(name, Ftyp, Flite, FZorA, Fmass);

   line.ReadLine(gridfile); // skip "Functional=" line : name of functional not used
   line.ReadLine(gridfile);
   LTGfit->SetValidRuns(KVNumberList(GetValue(line, '=').Data()));
   line.ReadLine(gridfile);
   LTGfit->SetStringTelescopes(GetValue(line, '='));
   line.ReadLine(gridfile);
   line.Remove(0, 6);
   line.Remove(KVString::kBoth, ' ');
   LTGfit->SetVarX(line.Data());
   line.ReadLine(gridfile);
   line.Remove(0, 6);
   line.Remove(KVString::kBoth, ' ');
   LTGfit->SetVarY(line.Data());
   line.ReadLine(gridfile);
   Int_t zmin, zmax;
   sscanf(line.Data(), "ZMIN=%d ZMAX=%d", &zmin, &zmax);
   LTGfit->SetIDmin(zmin);
   LTGfit->SetIDmax(zmax);
   Bool_t type1 = (Ftyp == 1);
   line.ReadLine(gridfile);
   buff = GetValue(line, '=');
   LTGfit->SetLambda(buff.Atof());
   if (type1) {
      line.ReadLine(gridfile);
      buff = GetValue(line, '=');
      LTGfit->SetAlpha(buff.Atof());
      line.ReadLine(gridfile);
      buff = GetValue(line, '=');
      LTGfit->SetBeta(buff.Atof());
   }
   line.ReadLine(gridfile);
   buff = GetValue(line, '=');
   LTGfit->SetMu(buff.Atof());
   if (type1) {
      line.ReadLine(gridfile);
      buff = GetValue(line, '=');
      LTGfit->SetNu(buff.Atof());
      line.ReadLine(gridfile);
      buff = GetValue(line, '=');
      LTGfit->SetXi(buff.Atof());
   }
   line.ReadLine(gridfile);
   buff = GetValue(line, '=');
   LTGfit->SetG(buff.Atof());
   line.ReadLine(gridfile);
   buff = GetValue(line, '=');
   LTGfit->SetPdx(buff.Atof());
   line.ReadLine(gridfile);
   buff = GetValue(line, '=');
   LTGfit->SetPdy(buff.Atof());
   if (Flite == 1) {
      line.ReadLine(gridfile);
      buff = GetValue(line, '=');
      LTGfit->SetEta(buff.Atof());
   }
   line.ReadLine(gridfile);
   return LTGfit;
}