Exemple #1
0
TEST(Element, element_map) {
    Profiler::initialize();
    armadillo_setup();

    {
    TestElement ele({ "0 0 0", "1 0 0", "0 1 0", "0 0 1"});
    EXPECT_ARMA_EQ( arma::mat("1 0 0 0; 0 1 0 0; 0 0 1 0"), ele.element_map());
    EXPECT_ARMA_EQ( arma::vec("0.1 0.2 0.3 0.4"), ele.project_point( arma::vec3("0.1 0.2 0.3") ) );
    EXPECT_ARMA_EQ( arma::vec("0.5 0.5 0.5 -0.5"), ele.project_point( arma::vec3("0.5 0.5 0.5") ) );
    }

    {
    // trnaslated
    TestElement ele({ "1 2 3", "2 2 3", "1 3 3", "1 2 4"});
    EXPECT_ARMA_EQ( arma::mat("1 0 0 1; 0 1 0 2; 0 0 1 3"), ele.element_map());
    EXPECT_ARMA_EQ( arma::vec("0.1 0.2 0.3 0.4"), ele.project_point( arma::vec3("1.1 2.2 3.3") ) );
    EXPECT_ARMA_EQ( arma::vec("0.5 0.5 0.5 -0.5"), ele.project_point( arma::vec3("1.5 2.5 3.5") ) );
    }

    {
    // simplest cube element 7
    TestElement ele({ "-1 -1 1", "1 1 -1", "-1 -1 -1", "1 -1 -1"});
    EXPECT_ARMA_EQ( arma::mat("2 0 2 -1; 2 0 0 -1; -2 -2 -2 1"), ele.element_map());
    EXPECT_ARMA_EQ( arma::vec("0.25 0.25 0.25 0.25"), ele.project_point( arma::vec3("0 -0.5 -0.5") ) );
    //EXPECT_ARMA_EQ( arma::vec("0.1 0.2 0.3 0.4"), ele.project_point( arma::vec3("0.1 0.2 0.3") ) );
    }
}
Exemple #2
0
void iom_file::buildTagList()
{
	// for all links class--(attribute|role)
	IomIterator obji=new iom_iterator(ilibasket);
	IomObject obj;
	while(!(obj=obji->next_object()).isNull()){
		if(obj->getTag()==tags::get_iom04_metamodel_Table() || obj->getTag()==tags::get_iom04_metamodel_AssociationDef()){
			// get qualified name of class
			int classId=getQualifiedTypeName(obj);
			// add to tag list
			tagv_type::iterator tag=tagList.find(classId);
			if(tag==tagList.end()){
				// not found, add empty attr list
				attrv_type attrv;
				tagList[classId]=attrv;
			}else{
				// found, don't change
			}
		}else if(obj->getTag()==tags::get_iom04_metamodel_ViewableAttributesAndRoles()){
			// get class
			IomObject aclass=ilibasket->getObject(obj->getAttrObj(tags::get_viewable(),0)->getRefOid());
			// get qualified name of class
			int classId=getQualifiedTypeName(aclass);
			// get attribute or role
			IomObject leafref=obj->getAttrObj(tags::get_attributesAndRoles(),0);
			// get name
			IomObject leafele=ilibasket->getObject(leafref->getRefOid());
			const XMLCh *leafName=leafele->getAttrValue(tags::get_name());
			int attrId=ParserHandler::getTagId(leafName);
			// get element index
			int eleIdx=leafref->getRefOrderPos()-1;
			// add to tag list
			tagv_type::iterator tag=tagList.find(classId);
			if(tag==tagList.end()){
				// not found, add
				attrv_type attrv;
				std::pair<int,int> ele(eleIdx,attrId);
				attrv.push_back(ele);
				tagList[classId]=attrv;
			}else{
				// found, replace
				attrv_type attrv=tag->second;
				std::pair<int,int> ele(eleIdx,attrId);
				attrv.push_back(ele);
				tagList[classId]=attrv;
			}
		}
	}

	// in all classes sort attrs according to pos
	tagv_type::iterator tag=tagList.begin();
	for(;tag!=tagList.end();tag++){
		attrv_type attrv=tag->second;
		std::sort(attrv.begin(),attrv.end());
		tagList[tag->first]=attrv;		
	}
	
}
Exemple #3
0
void NavMap::readPolyFile() {
	std::ifstream poly("navMap.1.poly");
	std::ifstream node("navMap.1.node");
	std::ifstream ele("navMap.1.ele");

	std::string bufferLine;
	int i = 0;
	
	vertex.clear();
	while(std::getline(node, bufferLine)) {
		if(bufferLine[0] == '#') {
			i++;
			continue;
		}
		if(i == 0) {
			int sizeOf = std::atoi(bufferLine.substr(0, bufferLine.find(" ")).c_str());
			vertex.reserve(sizeOf);
			for(int i = 0; i < sizeOf; i++) vertex.push_back(Vector::ZERO);
		} else {
			int f = 0;
			int n = std::atoi(getNextValue(bufferLine, f).c_str()); 
			float x = static_cast<float>(std::atof(getNextValue(bufferLine, f).c_str()));
			float y = static_cast<float>(std::atof(getNextValue(bufferLine, f).c_str()));
			vertex[n - 1] = Vector(x, y);
		}
		i++;
	}
	poly.close();

	i = 0;
	lines.clear();
	meshes.clear();
	while(std::getline(ele, bufferLine)) {
		if(bufferLine[0] == '#') {
			i++;
			continue;
		}
		if(i == 0) {
			int sizeOf = std::atoi(bufferLine.substr(0, bufferLine.find(" ")).c_str());
			lines.reserve(sizeOf * 3);
			meshes.reserve(sizeOf);
			for(int i = 0; i < sizeOf * 3; i++) lines.push_back(line(Vector::ZERO, Vector::ZERO));
			for(int i = 0; i < sizeOf; i++) meshes.push_back(Triangle(0, 0, 0));
		} else {
			int f = 0;
			int n = (std::atoi(getNextValue(bufferLine, f).c_str()) - 1) * 3;
			unsigned int A = static_cast<unsigned int>(std::atoi(getNextValue(bufferLine, f).c_str()));
			unsigned int B = static_cast<unsigned int>(std::atoi(getNextValue(bufferLine, f).c_str()));
			unsigned int C = static_cast<unsigned int>(std::atoi(getNextValue(bufferLine, f).c_str()));
			Vector vecA = vertex[A - 1];
			Vector vecB = vertex[B - 1];
			Vector vecC = vertex[C - 1];
			lines[n + 0] = line(vecA, vecB);
			lines[n + 1] = line(vecB, vecC);
			lines[n + 2] = line(vecC, vecA);
			meshes[n / 3] = Triangle(vecA, vecB, vecC);
		}
		i++;
	} 
}
Exemple #4
0
vector<vector<int> > subsetsWithDup(const vector<int> &S) {
    vector<vector<int> > res;
    res.push_back(vector<int>{});
    int sz = S.size();
    if(sz == 0) {
        return res;
    }
    vector<int> num(S);
    sort(num.begin(), num.end());

    int start=0, i=start;

    while(i<sz) {
        while(i+1<sz && num[i] == num[i+1]) {
            i++;
        }

        vector<vector<int> > nextRes(res);
        for(auto &r: nextRes) {
            vector<int> ele(r);

            for(int j=start; j<=i; j++) {
                ele.push_back(num[j]);
                res.push_back(ele);
            }
        }
        start = i+1;
        i=start;
    }
    return res;
}
void SavegameManager::loadPokemonTeam() {
	ska::IniReader pkmnReader;
	unsigned int index = 0;

	const auto basePath = "./Data/Saves/" + m_pathname + "/Team/";

	do {
		const std::string& id = ska::StringUtils::intToStr(index);
		pkmnReader.load(basePath + id + ".ini");
		if(pkmnReader.isLoaded()) {


			const auto charId = pkmnReader.get<int>("Data id");
			const auto charExp = pkmnReader.get<unsigned int>("Data experience");
			const auto charHp = pkmnReader.get<unsigned int>("Stats hp");

			const auto pokemonDBPath = "./Data/Monsters/" + ska::StringUtils::intToStr(charId) + ".ini";
			ska::IniReader detailsReader(pokemonDBPath);
			EntityLoadEvent ele(detailsReader, charId, charHp);
			ele.stats->setExperience(charExp);
			m_ged.ska::Observable<EntityLoadEvent>::notifyObservers(ele);
		}
		index++;
	} while (pkmnReader.isLoaded());

}
Exemple #6
0
int min_cost_max_flow(int src, int dst) {
  int flow = 0;
  int fcost = 0;
  while (flow < dst - 1) {
    std::fill(dist, dist + dst + 1, INF);
    dist[src] = 0;
    std::priority_queue<ele> q;
    q.push(ele(src, 0));
    while (!q.empty()) {
      int u = q.top().to;
      int d = q.top().dist;
      q.pop();
      if (d != dist[u]) continue;
      for (int i = 0; i < int(ed[u].size()); ++i) {
        edge& e = ed[u][i];
        if (e.f < e.cap) {
          int v = e.to;
          int t = dist[u] + e.cost + pot[u] - pot[v];
          if (dist[v] > t) {
            dist[v] = t;
            pred_v[v] = u;
            pred_e[v] = i;
            q.push(ele(v, t));
          }
        }
      }
    }
    if (dist[dst] == INF) break;
    for (int i = src; i <= dst; ++i) {
      pot[i] += dist[i];
    }
    ++flow;
    for (int u = dst, v; u != src; u = v) {
      v = pred_v[u];
      edge& e = ed[v][pred_e[u]];
      ++e.f;
      --ed[u][e.rev].f;
      fcost += e.cost;
    }
  }
  return fcost;
}
Exemple #7
0
/** Get the idx'th element adjacent to element (e,etype) */
ElemID FEM_Mesh::e2e_getElem(int e, int idx, int etype){
  if (e == -1){
    ElemID ele(-1,-1);    
    return ele;
  }
  
  if(FEM_Is_ghost_index(e)){

	  FEM_IndexAttribute *eAdj;
	  FEM_IndexAttribute *eAdjType;

	  eAdj = (FEM_IndexAttribute *)elem[etype].getGhost()->lookup(FEM_ELEM_ELEM_ADJACENCY,"e2e_getElem");
	  AllocTable2d<int> &eAdjs = eAdj->get();
	  eAdjType = (FEM_IndexAttribute *)elem[etype].getGhost()->lookup(FEM_ELEM_ELEM_ADJ_TYPES,"e2e_getElem");
	  AllocTable2d<int> &eAdjTypes = eAdjType->get();

	  int t =  eAdjTypes[FEM_To_ghost_index(e)][idx];
	  int id =  eAdjs[FEM_To_ghost_index(e)][idx];
	  ElemID ele(t,id);

	  return ele;
  }
  else {

	  CkAssert(elem.has(etype) && e < elem[etype].size());

	  FEM_IndexAttribute *eAdj;
	  FEM_IndexAttribute *eAdjType;

	  eAdj = (FEM_IndexAttribute *)elem[etype].lookup(FEM_ELEM_ELEM_ADJACENCY,"e2e_getElem");
	  AllocTable2d<int> &eAdjs = eAdj->get();
	  eAdjType = (FEM_IndexAttribute *)elem[etype].lookup(FEM_ELEM_ELEM_ADJ_TYPES,"e2e_getElem");
	  AllocTable2d<int> &eAdjTypes = eAdjType->get();

	  int t =  eAdjTypes[e][idx];
	  int id =  eAdjs[e][idx];
	  ElemID ele(t,id);

	  return ele;
  }
  
}
void PopulateGraph(std::vector< std::set<ulong> > &Graph, std::vector< std::set<ulong> > &vertex_tri_hash) {

	std::set<ulong> myneighbors;
	// Populate the hash table which tells us which triangles are sharing a specific node.
	for (ulong i=0; i<nele; ++i) {
		for (int j=0; j<3; ++j)
			vertex_tri_hash[(ulong) (ele(i,j)-1)].insert(i+1);
	}
	std::set<ulong> tmpSet;
	std::queue<ulong> q;
	std::vector<long> edge_check (nele, White);
	bool endflag=false;
	ulong starte=1;
	while (!endflag) {
		q.push(starte);
		ulong dummyc=0;
		while (!q.empty()) {
			ulong u = q.front();
			myneighbors = FindNeighboringTriangles(u, vertex_tri_hash);
			for (std::set<ulong>::iterator it=myneighbors.begin(); it!=myneighbors.end(); ++it) {
				if (edge_check[(*it)-1]==Black) continue;
				if (u != *it) {
					ulong tempak = *it;
					tmpSet.clear();
					tmpSet = Graph[u-1];
					tmpSet.insert(*it);
					Graph[u-1] = tmpSet;

					tmpSet.clear();
					tmpSet = Graph[(*it)-1];
					tmpSet.insert(u);
					Graph[(*it)-1] = tmpSet;
					if (edge_check[(*it)-1] == White)
						q.push(*it);
					edge_check[(*it)-1] = edge_check[(*it)-1] + 1;
	// 				if (edge_check[(*it)-1]>=3)
	// 					edge_check[(*it)-1] = Black;
				}
					
			}
			edge_check[u-1] = Black;
			q.pop();
			dummyc++;
		}
		endflag=true;
		for (ulong i=0; i<nele; ++i) {
			if (edge_check[i]!=Black)  {
				starte = i+1;
				endflag=false;
				break;
			}
		}
	}
}
Exemple #9
0
int main() {
  freopen("distant.in", "r", stdin);
  freopen("distant.out", "w", stdout);
  //std::ios::sync_with_stdio(0);
  //std::cin.tie(0);
  int n, a, b;
  scanf("%d %d %d", &n, &a, &b);
  for (int i = 1; i <= n; ++i)
    scanf("%s", s[i] + 1);
  int ans = 0;
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= n; ++j) {
      memset(dp, -1, sizeof(dp));
      dp[i][j] = 0;
      std::queue<ele> que;
      que.push(ele(i, j, 0));
      while (!que.empty()) {
        ele t = que.front();
        que.pop();
        if (t.v != dp[t.x][t.y]) continue;
        for (int k = 0; k < 4; ++k) {
          int x = t.x + dx[k];
          int y = t.y + dy[k];
          if (1 <= x && x <= n)
            if (1 <= y && y <= n) {
              int v = dp[t.x][t.y] + (s[x][y] == s[t.x][t.y] ? a : b);
              if (dp[x][y] == -1 || dp[x][y] > v) {
                dp[x][y] = v;
                que.push(ele(x, y, v));
              }
            }
        }
      }
      for (int p = 1; p <= n; ++p)
        for (int q = 1; q <= n; ++q)
          if (ans < dp[p][q])
            ans = dp[p][q];          
    }
  printf("%d", ans);
}
Exemple #10
0
int main(){
  char s1[3],s2[3];
  int a,b,c,d,i,j,n;
  scanf("%d",&n);
  for(;n;n--){
    if(scanf("%s %s",s1,s2)<0)return 0;
    a=s1[0]-'a',b=s2[0]-'a';
    c=s1[1]-'1',d=s2[1]-'1';
    i=abs(a-b),j=abs(c-d);
    if(!i&&!j){puts("0 0 0 0");continue;}
    king(i,j);
    queen(i,j);
    luke(i,j);
    ele(i,j);
  }
}
// Searches all the triangles sharing a node with 'tri' in order to figure out
// the ones that share an edge. It then returns those triangles' IDs
std::set<ulong> FindNeighboringTriangles(ulong tri, std::vector< std::set<ulong> > &vertex_tri_hash ) {
	std::set<ulong> neighbours, ret;
	std::set<ulong>::iterator it;
	for (int i=0; i<3; ++i) {
		for (it=vertex_tri_hash[(ulong)(ele(tri-1,i))-1].begin(); it!=vertex_tri_hash[(ulong)(ele(tri-1,i))-1].end(); ++it) {
			if (*it != tri)
				neighbours.insert(*it);
		}
	}

	for (it=neighbours.begin(); it!=neighbours.end(); ++it) {
		if (ShareEdge(tri,*it)) {
			ret.insert(*it);
		}
	}
	return ret;
}
// If triangle u and v share an edge, it will return true, otherwise false
bool ShareEdge(ulong u, ulong v) {
	bool flag = false;
	ulong NV[3]={(ulong)(ele(v-1,0)), (ulong)(ele(v-1,1)), (ulong)(ele(v-1,2))};
	ulong NU[3]={(ulong)(ele(u-1,0)), (ulong)(ele(u-1,1)), (ulong)(ele(u-1,2))};
	ulong eu1, eu2, ev1, ev2;

	for (int i=0; i<3; ++i) {
		eu1 = NU[edge[i][0]]; eu2 = NU[edge[i][1]];
		for (int j=0; j<3; ++j) {
			ev1 = NV[edge[j][0]]; ev2 = NV[edge[j][1]];
			if ((eu1==ev1 && eu2==ev2) || (eu1==ev2 && eu2==ev1)) {
				return true;
			}
		}
	}
	return flag;
}
AbstractLinAlgPack::size_type
AbstractLinAlgPack::SparseVectorUtilityPack::SpVecIndexLookup<T_Element>::find_element(
  index_type index, bool is_sorted ) const
{
  typedef T_Element* itr_t;
  if(is_sorted) {
    const std::pair<itr_t,itr_t> p = std::equal_range( ele(), ele() + nz()
      , index - offset(), compare_element_indexes_less<element_type>() );
    // If p.second - p.first == 1 then the element exits
    if( p.second - p.first == 1 )
      return p.first - ele();	// zero based
    else
      return nz(); // zero based
  }
  else {
    const itr_t itr = std::find_if( ele(), ele() + nz()
      , compare_element_indexes_equal_to<element_type>(index - offset()) );
    return itr - ele();	// zero based
  }
}
void TestDenoiseStrategy2::denoise(const Mat& srcImg, Mat& desImg)
{
	cv::Mat ele(mArg, mArg, CV_8U,cv::Scalar(1));
	cv::morphologyEx(srcImg, desImg, cv::MORPH_CLOSE, ele);
}
//*************************************************************************************************
//Main part of the macro
//*************************************************************************************************
void NormalizeElectronNtuple(const string InputFilename, const string datasetName, 
                             const string OutputFilename, Int_t sampleType, 
                             const string normalizationFile = "") {


  Double_t normalizationWeight = 0;
  Bool_t useReweightFactor = kFALSE;
  TH2F *PtEtaReweightFactor = 0;
  Double_t overallWJetsNormalizationFactor = 0;

  //For Normalizing each sample individually
  if (sampleType == 0 || sampleType >= 10) {
    TTree* electronTree = getTreeFromFile(InputFilename.c_str());
    assert(electronTree);    
    MitNtupleElectron ele(electronTree);
    
    normalizationWeight = getNormalizationWeight(InputFilename, datasetName);
    //*************************************************************************************************
    //Create new normalized tree
    //*************************************************************************************************
    TFile *outputFile = new TFile(OutputFilename.c_str(), "RECREATE");
    outputFile->cd();    
    TTree *normalizedTree = electronTree->CloneTree(0);
    
    for (int n=0;n<electronTree->GetEntries();n++) { 
      ele.GetEntry(n);

      if (sampleType == 10) {
        if (ele.electron_branch_passedSelectionCut == 1) {
          if (datasetName == "s09-wwll10-mc3" || datasetName == "s09-ttbar-mc3") {
            //for mu-e there should be only 1 electron candidate
            ele.electron_branch_weight = normalizationWeight; 
            normalizedTree->Fill(); 
          } else if (datasetName == "s09-we-mc3" || datasetName == "s09-wm-mc3" || datasetName == "s09-wt-mc3") {
            //For the W->enu sample, fill only the fake electron candidates.
            ele.electron_branch_weight = normalizationWeight; 
            if (ele.electron_branch_electronType < 100) {
              normalizedTree->Fill(); 
            }
          } else {
            cout << "Warning: The specified dataset " << datasetName 
                 << " is not recognized to be one of the selection cut samples.\n";
          }
        }        
      } else {
        //For regular samples just fill all electrons
        ele.electron_branch_weight = normalizationWeight; 
        normalizedTree->Fill(); 
      }      
    }
    normalizedTree->Write();
    cout << "Original Tree Entries: " << electronTree->GetEntries() << "  Normalized Tree Entries: " << normalizedTree->GetEntries() << endl;
    outputFile->Close();     
  }
  //For Normalization of Background sample
  else if (sampleType == 1) {
    TTree* electronTree = getTreeFromFile(InputFilename.c_str(), kFALSE);
    assert(electronTree);     
    MitNtupleElectron ele(electronTree);

    //*************************************************************************************************
    //Create new reweighted tree
    //*************************************************************************************************
    TFile *outputFile = new TFile(OutputFilename.c_str(), "RECREATE");
    TTree *reweightedTree = electronTree->CloneTree(0);    

    if (normalizationFile == "") {
      //normalize according to total number of electrons expected in W+Jets/W+gamma bkg
      Double_t totalWeight = 0;
      for (int n=0;n<electronTree->GetEntries();n++) { 
        ele.GetEntry(n);
        totalWeight += ele.electron_branch_weight;
      }

      cout << "Input Bkg Ntuple Total Weight = " << totalWeight << endl;
      normalizationWeight = 1126.5 / totalWeight;
    } else {
      //do pt/eta Reweighting

      TFile *reweightInputFile = new TFile(normalizationFile.c_str(), "READ");
      assert(reweightInputFile);

      TH2F *WJetsFakeElectronPtEta = (TH2F*)reweightInputFile->Get("hWJetsFakeElectronPtEta");
      assert(WJetsFakeElectronPtEta);      
      WJetsFakeElectronPtEta = (TH2F*)(WJetsFakeElectronPtEta->Clone());
      WJetsFakeElectronPtEta->SetDirectory(0);
      reweightInputFile->Close();

      //Create histogram for reweighting factor
      PtEtaReweightFactor = (TH2F*)WJetsFakeElectronPtEta->Clone();
      PtEtaReweightFactor->SetName("PtEtaReweightFactor");
      PtEtaReweightFactor->SetDirectory(0);

      TH2F *BkgFakeElectronPtEta = new TH2F("BkgFakeElectronPtEta", ";Pt [GeV/c];#eta;" , WJetsFakeElectronPtEta->GetXaxis()->GetNbins(), WJetsFakeElectronPtEta->GetXaxis()->GetBinLowEdge(1), WJetsFakeElectronPtEta->GetXaxis()->GetBinUpEdge(WJetsFakeElectronPtEta->GetXaxis()->GetNbins()), WJetsFakeElectronPtEta->GetYaxis()->GetNbins(), WJetsFakeElectronPtEta->GetYaxis()->GetBinLowEdge(1), WJetsFakeElectronPtEta->GetYaxis()->GetBinUpEdge(WJetsFakeElectronPtEta->GetYaxis()->GetNbins()));
      BkgFakeElectronPtEta->SetDirectory(0);
      for (int n=0;n<electronTree->GetEntries();n++) { 
        ele.GetEntry(n);
        BkgFakeElectronPtEta->Fill(ele.electron_branch_pt, ele.electron_branch_eta, ele.electron_branch_weight);        
      }
      PtEtaReweightFactor->Divide(WJetsFakeElectronPtEta, BkgFakeElectronPtEta, 1.0,1.0,"B");

      useReweightFactor = kTRUE;    
    }

    cout << "Reweighting Background Ntuple\n";
    outputFile->cd();    

    //check Reweighting
    TH2F *ReweightedBkgFakeElectronPtEta = new TH2F("BkgFakeElectronPtEta", ";Pt [GeV/c];#eta;" , 200, 0, 200, 200, -3.0, 3.0);    
    ReweightedBkgFakeElectronPtEta->SetDirectory(0);
    for (int n=0;n<electronTree->GetEntries();n++) { 
      if (n%250000 == 0) cout << "Entry " << n << endl;
      ele.GetEntry(n);
      if (useReweightFactor) {
        Double_t reweightFactor = PtEtaReweightFactor->GetBinContent(PtEtaReweightFactor->GetXaxis()->FindFixBin(ele.electron_branch_pt),PtEtaReweightFactor->GetYaxis()->FindFixBin(ele.electron_branch_eta));
        ele.electron_branch_weight = ele.electron_branch_weight*reweightFactor;//*overallWJetsNormalizationFactor;
      } else {
        ele.electron_branch_weight = normalizationWeight;
      }
      reweightedTree->Fill(); 

      ReweightedBkgFakeElectronPtEta->Fill(ele.electron_branch_pt, ele.electron_branch_eta, ele.electron_branch_weight);
    }
    reweightedTree->Write();
    cout << "Original Tree Entries: " << electronTree->GetEntries() << "  Normalized Tree Entries: " << reweightedTree->GetEntries() << endl;
    outputFile->Close();
  
    TCanvas *cv = new TCanvas("BkgReweightedFakeElectronPtEta", "BkgReweightedFakeElectronPtEta", 0,0,800,600);
    ReweightedBkgFakeElectronPtEta->ProjectionX()->DrawCopy("E1");
    cv->SaveAs("BkgReweightedFakeElectronPt.gif");
    ReweightedBkgFakeElectronPtEta->ProjectionY()->DrawCopy("E1");
    cv->SaveAs("BkgReweightedFakeElectronEta.gif");
  } 
  
  //For Normalization of Signal sample
  else if (sampleType == 2) {
    TTree* electronTree = getTreeFromFile(InputFilename.c_str(), kFALSE);
    assert(electronTree);     
    MitNtupleElectron ele(electronTree);

    //*************************************************************************************************
    //Create new reweighted tree
    //*************************************************************************************************
    TFile *outputFile = new TFile(OutputFilename.c_str(), "RECREATE");
    TTree *reweightedTree = electronTree->CloneTree(0);    

    if (normalizationFile == "") {
      //normalize according to total number of electrons expected in WW -> ee nunu signal
      Double_t totalWeight = 0;
      for (int n=0;n<electronTree->GetEntries();n++) { 
        ele.GetEntry(n);
        totalWeight += ele.electron_branch_weight;
      }

      cout << "Input Bkg Ntuple Total Weight = " << totalWeight << endl;
      normalizationWeight = 1126.5 / totalWeight;
    } else {
      //do pt/eta Reweighting

      TFile *reweightInputFile = new TFile(normalizationFile.c_str(), "READ");
      assert(reweightInputFile);
      TH2F *WWSigElectronPtEta = (TH2F*)reweightInputFile->Get("hWWRealElectronPtEta");
      assert(WWSigElectronPtEta);      
      WWSigElectronPtEta = (TH2F*)(WWSigElectronPtEta->Clone());
      WWSigElectronPtEta->SetDirectory(0);
      reweightInputFile->Close();

      //Create histogram for reweighting factor
      PtEtaReweightFactor = (TH2F*)WWSigElectronPtEta->Clone();
      PtEtaReweightFactor->SetName("PtEtaReweightFactor");
      PtEtaReweightFactor->SetDirectory(0);

      TH2F *SigSampleElectronPtEta = new TH2F("SigSampleElectronPtEta", ";Pt [GeV/c];#eta;" , WWSigElectronPtEta->GetXaxis()->GetNbins(), WWSigElectronPtEta->GetXaxis()->GetBinLowEdge(1), WWSigElectronPtEta->GetXaxis()->GetBinUpEdge(WWSigElectronPtEta->GetXaxis()->GetNbins()), WWSigElectronPtEta->GetYaxis()->GetNbins(), WWSigElectronPtEta->GetYaxis()->GetBinLowEdge(1), WWSigElectronPtEta->GetYaxis()->GetBinUpEdge(WWSigElectronPtEta->GetYaxis()->GetNbins()));
      SigSampleElectronPtEta->SetDirectory(0);
      for (int n=0;n<electronTree->GetEntries();n++) { 
        ele.GetEntry(n);
        SigSampleElectronPtEta->Fill(ele.electron_branch_pt, ele.electron_branch_eta, ele.electron_branch_weight);        
      }
      PtEtaReweightFactor->Divide(WWSigElectronPtEta, SigSampleElectronPtEta, 1.0,1.0,"B");

      useReweightFactor = kTRUE;    
    }

    cout << "Reweighting Signal Ntuple\n";
    outputFile->cd();    

    //check Reweighting
    TH2F *ReweightedSigRealElectronPtEta = new TH2F("ReweightedSigRealElectronPtEta", ";Pt [GeV/c];#eta;" , 200, 0, 200, 200, -3.0, 3.0);    
    ReweightedSigRealElectronPtEta->SetDirectory(0);
    for (int n=0;n<electronTree->GetEntries();n++) { 
      if (n%250000 == 0) cout << "Entry " << n << endl;
      ele.GetEntry(n);
      if (useReweightFactor) {
        Double_t reweightFactor = PtEtaReweightFactor->GetBinContent(PtEtaReweightFactor->GetXaxis()->FindFixBin(ele.electron_branch_pt),PtEtaReweightFactor->GetYaxis()->FindFixBin(ele.electron_branch_eta));
        ele.electron_branch_weight = ele.electron_branch_weight*reweightFactor;//*overallWJetsNormalizationFactor;
      } else {
        ele.electron_branch_weight = normalizationWeight;
      }
      reweightedTree->Fill(); 
      ReweightedSigRealElectronPtEta->Fill(ele.electron_branch_pt, ele.electron_branch_eta, ele.electron_branch_weight);
    }
    reweightedTree->Write();
    cout << "Original Tree Entries: " << electronTree->GetEntries() << "  Normalized Tree Entries: " << reweightedTree->GetEntries() << endl;
    outputFile->Close();
  
    TCanvas *cv = new TCanvas("BkgReweightedFakeElectronPtEta", "BkgReweightedFakeElectronPtEta", 0,0,800,600);
    ReweightedSigRealElectronPtEta->ProjectionX()->DrawCopy("E1");
    cv->SaveAs("SigReweightedRealElectronPt.gif");
    ReweightedSigRealElectronPtEta->ProjectionY()->DrawCopy("E1");
    cv->SaveAs("SigReweightedRealElectronEta.gif");
  } 
  else {
    cout << "Warning: Specified sampleType " << sampleType << " is not recognized.\n";
  }



}
typename AbstractLinAlgPack::SparseVectorUtilityPack::SpVecIndexLookup<T_Element>::poss_type
AbstractLinAlgPack::SparseVectorUtilityPack::SpVecIndexLookup<T_Element>::binary_ele_search(
  index_type index, UpperLower uplow) const
{

  poss_type poss_returned;

  size_type lower_poss = 0, upper_poss = nz_ - 1;

  // Look at the end points first then perform the binary search
  
  typename T_Element::index_type lower_index = ele()[lower_poss].index() + offset();
  if(index <= lower_index) {	// before or inc. first ele.
    if(index == lower_index)	poss_returned.rel = EQUAL_TO_ELE;
    else						poss_returned.rel = BEFORE_ELE;
    poss_returned.poss = lower_poss;
    return poss_returned;
  }

  typename T_Element::index_type upper_index = ele()[upper_poss].index() + offset();
  if(index >= upper_index) { // after or inc. last ele.
    if(index == upper_index)	poss_returned.rel = EQUAL_TO_ELE;
    else						poss_returned.rel = AFTER_ELE;
    poss_returned.poss = upper_poss;
    return poss_returned;
  }

  // Perform the binary search
  for(;;) {

    if(upper_poss == lower_poss + 1) {
      // This is a zero element that is between these two nonzero elements
      if(uplow == LOWER_ELE) {
        poss_returned.rel = BEFORE_ELE;
        poss_returned.poss = upper_poss;
        return poss_returned;	
      }
      else {
        poss_returned.rel = AFTER_ELE;
        poss_returned.poss = lower_poss;
        return poss_returned;
      }
    }

    // Bisect the region
    size_type mid_poss = (upper_poss - lower_poss) / 2 + lower_poss;
    typename T_Element::index_type mid_index = ele()[mid_poss].index() + offset();

    if(mid_index == index) {	 // The nonzero element exists
      poss_returned.rel = EQUAL_TO_ELE;
      poss_returned.poss = mid_poss;
      return poss_returned;
    }

    // update binary search region
    if(index < mid_index) {
      upper_poss = mid_poss;
      upper_index = mid_index;
    }
    else {
      // mid_index < index
      lower_poss = mid_poss;
      lower_index = mid_index;
    }
  }
}
void
AbstractLinAlgPack::SparseVectorUtilityPack::SpVecIndexLookup<T_Element>::validate_state() const
{
  TEUCHOS_TEST_FOR_EXCEPTION( ele() && ele()->index() + offset() < 1, NoSpVecSetException,
    "SpVecIndexLookup<T_Element>::validate_state(): Error, ele()->index() + offset() < 1");
}