コード例 #1
0
ファイル: prevector_tests.cpp プロジェクト: titcoin/titcoin
 void test() {
     const pretype& const_pre_vector = pre_vector;
     local_check_equal(real_vector.size(), pre_vector.size());
     local_check_equal(real_vector.empty(), pre_vector.empty());
     for (Size s = 0; s < real_vector.size(); s++) {
          local_check(real_vector[s] == pre_vector[s]);
          local_check(&(pre_vector[s]) == &(pre_vector.begin()[s]));
          local_check(&(pre_vector[s]) == &*(pre_vector.begin() + s));
          local_check(&(pre_vector[s]) == &*((pre_vector.end() + s) - real_vector.size()));
     }
     // local_check(realtype(pre_vector) == real_vector);
     local_check(pretype(real_vector.begin(), real_vector.end()) == pre_vector);
     local_check(pretype(pre_vector.begin(), pre_vector.end()) == pre_vector);
     size_t pos = 0;
     for (const T& v : pre_vector) {
          local_check(v == real_vector[pos++]);
     }
     for (const T& v : reverse_iterate(pre_vector)) {
          local_check(v == real_vector[--pos]);
     }
     for (const T& v : const_pre_vector) {
          local_check(v == real_vector[pos++]);
     }
     for (const T& v : reverse_iterate(const_pre_vector)) {
          local_check(v == real_vector[--pos]);
     }
     CDataStream ss1(SER_DISK, 0);
     CDataStream ss2(SER_DISK, 0);
     ss1 << real_vector;
     ss2 << pre_vector;
     local_check_equal(ss1.size(), ss2.size());
     for (Size s = 0; s < ss1.size(); s++) {
         local_check_equal(ss1[s], ss2[s]);
     }
 }
コード例 #2
0
ファイル: quadObj.cpp プロジェクト: Nand-e/2to3d
/* Load Quad from file
 *
 * **********************************************************/
bool QuadObj::loadFromFile(std::ifstream & inputstream) {
    std::string str;
    float x,y,z;
    char v;
    // read position
    std::getline(inputstream, str );
    std::stringstream ss(str);
    ss >> x;    ss >> v;    ss >> y;    ss >> v;    ss >> z;
    qDebug() << x << "," << y << ";" << z;
    pos = QVector3D(x,y,z);
    // read rotmatrix
    for ( int i=0; i < 3; i++) {
        std::getline(inputstream, str );
        std::stringstream ss(str);
        ss >> x;    ss >> v;    ss >> y;    ss >> v;    ss >> z;
        this->rotation.setColumn(i,QVector3D (x,y,z));
    }
    // read scale
    std::getline(inputstream, str );
    std::stringstream ss1(str);
    ss1 >> x;    ss1 >> v;    ss1 >> y;    ss1 >> v;    ss1 >> z;
    scale = QVector3D (x,y,z);
    // read verticies
    vertices.clear();
    for ( int i=0; i < 4; i++) {
        std::getline(inputstream, str );
        std::stringstream ss(str);
        ss >> x;    ss >> v;    ss >> y;    ss >> v;    ss >> z;
        vertices.append(QVector3D (x,y,z));
    }


    return true;
}
コード例 #3
0
bool CMessageCrypter::Encrypt(const string& vchPubKey, const string& vchPlaintext, string& vchCiphertext)
{
    try
    {
        AutoSeededRandomPool prng;
        StringSource ss(vchPubKey, true);
		ECIES<ECP>::Encryptor encryptor;

        //curve used is secp256k1
        encryptor.AccessKey().AccessGroupParameters().Initialize(ASN1::secp256k1());

        //get point on the used curve
        ECP::Point point;
        encryptor.GetKey().GetGroupParameters().GetCurve().DecodePoint(point, ss, ss.MaxRetrievable());

        //set encryptor's public element
        encryptor.AccessKey().SetPublicElement(point);

        //check whether the encryptor's access key thus formed is valid or not
        encryptor.AccessKey().ThrowIfInvalid(prng, 3);

        // encrypted message
        StringSource ss1(vchPlaintext, true, new PK_EncryptorFilter(prng, encryptor, new StringSink(vchCiphertext) ) );
    }
    catch(const CryptoPP::Exception& ex)
    {
		return false;
    }

	return true;
}
コード例 #4
0
void Tablero::cargarTablero()
{
	Archivos archivo;
	string texto=archivo.LeerArchivo("tablero.txt");
        string bufferi="",bufferj="";
        int k=0;
        bufferi=texto.substr(k,texto.find("\n")-k);
        texto=texto.substr(texto.find("\n")+1);
        bufferj=texto.substr(k,texto.find("\n")-k);
        texto=texto.substr(texto.find("\n")+1);
        stringstream ss(bufferi);
        ss>>tami;
        stringstream ss1(bufferj);
        ss1>>tamj;
        
        crearTablero(tami,tamj);
        
	for(int i=0;i<tami;i++)
        {
            string linea=texto.substr(0,texto.find("\n")+1);
            cout<<"En Linea "<<i<<" "<<linea<<endl;
            for(int j=0;j<tamj;j++)
            {
                agregarElemento(linea.substr(0,linea.find("#")),i,j);
                linea=linea.substr(linea.find("#")+1);
            }
            
            texto=texto.substr(texto.find("\n")+1);
        }
}
コード例 #5
0
ファイル: subtractBackground.C プロジェクト: ikrav/usercode
void subtractBackground(const TString conf){

  std::cout << "conf=" << conf << "\n";

  // Read from configuration file only the location of the root files
  TString inputDir;
  Double_t lumi;
  Bool_t doWeight;
  ifstream ifs;
  ifs.open(conf.Data());
  if (!ifs.is_open()) {
    std::cout << "failed to open file <" << conf << ">\n";
    assert(ifs.is_open());
  }

  string line;
  vector<TString>  snamev;    // sample name (for output file)
  vector<CSample*> samplev;   // data/MC samples
  Int_t state=0;
  while(getline(ifs,line)) {
    if(line[0]=='#') continue;
    if(line[0]=='%') { 
      state++; 
      continue; 
    }
    if(line[0]=='$') {
      samplev.push_back(new CSample());
      stringstream ss(line);
      string chr;
      string sname;
      Int_t color;
      ss >> chr >> sname >> color;
      string label = line.substr(line.find('@')+1);
      snamev.push_back(sname);
      samplev.back()->label = label;
      samplev.back()->color = color;
      continue;
    }
    
    if(state==0) {  // general settings
      stringstream ss1(line); ss1 >> lumi;
      getline(ifs,line);
      stringstream ss2(line); ss2 >> doWeight;
      getline(ifs,line);
      inputDir = TString(line);
      getline(ifs,line);
      // backwards compatibility for the input file
      if (line.size()>3) {  // escale is defined
	TString escaleTag_loc=TString(line);
	getline(ifs,line);
	// check that it was correct to use this work-around
	if (line.find('%')!=std::string::npos) {
	  std::cout << "backwards-compatibility code failure\n";
	  return;
	}
      }
      TString format_loc = TString(line);
      
    } else if(state==1) {  // define data sample
コード例 #6
0
int CAddrInfo::GetBucketPosition(const uint256 &nKey, bool fNew, int nBucket) const
{
    CDataStream ss1(SER_GETHASH, 0);
    std::vector<unsigned char> vchKey = GetKey();
    ss1 << nKey << (fNew ? 'N' : 'K') << nBucket << vchKey;
    uint64_t hash1 = Hash(ss1.begin(), ss1.end()).GetLow64();
    return hash1 % ADDRMAN_BUCKET_SIZE;
}
コード例 #7
0
void selectEleBDTGWithIPInfoEffTP(const TString conf,              // input file
                      const TString outputDir,         // output directory
		      const Bool_t  matchGen = kFALSE  // match to generator muons
) {
  gBenchmark->Start("selectEleLHEffTP");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //============================================================================================================== 

  //*****************************************************************************************
  //Setup MVA
  //*****************************************************************************************
  mithep::ElectronIDMVA *electronIDMVAWithIPInfo = new mithep::ElectronIDMVA();
  electronIDMVAWithIPInfo->Initialize("BDTG method",
                              "/home/sixie/CMSSW_analysis/src/MitPhysics/data/ElectronMVAWeights/Subdet0LowPt_WithIPInfo_BDTG.weights.xml", 
                              "/home/sixie/CMSSW_analysis/src/MitPhysics/data/ElectronMVAWeights/Subdet1LowPt_WithIPInfo_BDTG.weights.xml", 
                              "/home/sixie/CMSSW_analysis/src/MitPhysics/data/ElectronMVAWeights/Subdet2LowPt_WithIPInfo_BDTG.weights.xml", 
                              "/home/sixie/CMSSW_analysis/src/MitPhysics/data/ElectronMVAWeights/Subdet0HighPt_WithIPInfo_BDTG.weights.xml", 
                              "/home/sixie/CMSSW_analysis/src/MitPhysics/data/ElectronMVAWeights/Subdet1HighPt_WithIPInfo_BDTG.weights.xml", 
                              "/home/sixie/CMSSW_analysis/src/MitPhysics/data/ElectronMVAWeights/Subdet2HighPt_WithIPInfo_BDTG.weights.xml",
                              mithep::ElectronIDMVA::kWithIPInfo);

  // mass region
  Double_t massLo;
  Double_t massHi;

  Double_t lumi;              // luminosity (pb^-1)
  
  vector<TString>  fnamev;    // sample files
  vector<Int_t>    typev;     // dataset type 
  vector<Double_t> xsecv;     // per file cross section
  vector<TString>  jsonv;     // per file JSON file

  //
  // parse .conf file
  //
  ifstream ifs;
  ifs.open(conf.Data());
  assert(ifs.is_open());
  string line;
  Int_t state=0;
  while(getline(ifs,line)) {
    if(line[0]=='#') continue;
    if(line[0]=='%') { 
      state++; 
      continue; 
    }
    
    if(state==0) {  // general settings
      stringstream ss1(line); ss1 >> lumi;
      getline(ifs,line);
      stringstream ss2(line); ss2 >> massLo >> massHi; 
      
    } else if(state==1) {  // define data sample
コード例 #8
0
void AtomRadiiTable::fromString(const string& s)
{
    // create deblanked string
    string s1;
    remove_copy_if(s.begin(), s.end(), back_inserter(s1), ::isspace);
    // replace commas with space so we can use the split function
    replace(s1.begin(), s1.end(), ',', ' ');
    istringstream ss1(s1);
    CustomRadiiStorage rds;
    for (string w; ss1 >> w;)
    {
コード例 #9
0
TString subtractBackground(const TString conf,
		   DYTools::TSystematicsStudy_t runMode=DYTools::NORMAL,
			   const TString plotsDirExtraTag="",
			   int performPUReweight=1){


  std::cout << "\n\nRun mode: " << SystematicsStudyName(runMode) << "\n";
  switch(runMode) {
  case DYTools::NORMAL:
  case DYTools::ESCALE_STUDY:
  case DYTools::ESCALE_STUDY_RND:
    break;
  default:
    std::cout << "subtractBackground is not ready for runMode=" << SystematicsStudyName(runMode) << "\n";
    throw 2;
  }
 
  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================

  // Read from configuration file only the location of the root files
  TString inputDir;
  Double_t lumi;
  Bool_t doWeight;
  Bool_t hasData=false;

  ifstream ifs;
  ifs.open(conf.Data());
  assert(ifs.is_open());
  string line;
  int state=0;
  while(getline(ifs,line)) {
    if(line[0]=='#') continue;
    if(line[0]=='%') { 
      state++; 
      continue; 
    }
    if(state==0) {
      stringstream ss1(line); ss1 >> lumi;
      getline(ifs,line);
      stringstream ss2(line); ss2 >> doWeight;
      getline(ifs,line);
      inputDir = TString(line);
      TString escaleTag_loc,format_loc;
      getline(ifs,line);
      stringstream ss3(line); ss3 >> escaleTag_loc;
      getline(ifs,line);
      format_loc = TString(line);
      state++;
    }
    else if (state==1) {
コード例 #10
0
int CAddrInfo::GetTriedBucket(const uint256& nKey) const
{
    CDataStream ss1(SER_GETHASH, 0);
    std::vector<unsigned char> vchKey = GetKey();
    ss1 << nKey << vchKey;
    uint64_t hash1 = Hash(ss1.begin(), ss1.end()).GetLow64();

    CDataStream ss2(SER_GETHASH, 0);
    std::vector<unsigned char> vchGroupKey = GetGroup();
    ss2 << nKey << vchGroupKey << (hash1 % ADDRMAN_TRIED_BUCKETS_PER_GROUP);
    uint64_t hash2 = Hash(ss2.begin(), ss2.end()).GetLow64();
    return hash2 % ADDRMAN_TRIED_BUCKET_COUNT;
}
コード例 #11
0
int CAddrInfo::GetNewBucket(const uint256& nKey, const CNetAddr& src) const
{
    CDataStream ss1(SER_GETHASH, 0);
    std::vector<unsigned char> vchGroupKey = GetGroup();
    std::vector<unsigned char> vchSourceGroupKey = src.GetGroup();
    ss1 << nKey << vchGroupKey << vchSourceGroupKey;
    uint64_t hash1 = Hash(ss1.begin(), ss1.end()).GetLow64();

    CDataStream ss2(SER_GETHASH, 0);
    ss2 << nKey << vchSourceGroupKey << (hash1 % ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP);
    uint64_t hash2 = Hash(ss2.begin(), ss2.end()).GetLow64();
    return hash2 % ADDRMAN_NEW_BUCKET_COUNT;
}
コード例 #12
0
ファイル: Chunk.cpp プロジェクト: Cmdu76/Map
bool Chunk::load()
{
    std::ifstream file(getPathFromCoords(mCoords));
    if (!file)
    {
        return false;
    }

    std::string line;
    std::size_t layerCount;
    std::getline(file,line);
    {
        std::istringstream iss(line);
        iss >> layerCount;
    }
    for (std::size_t i = 0; i < layerCount; i++)
    {
        addLayer();
    }

    sf::Vector2i coords = sf::Vector2i();
    int z = 0;
    while (std::getline(file,line))
    {
        std::stringstream ss1(line);
        std::string temp1;
        coords.x = 0;
        while (std::getline(ss1,temp1,';'))
        {
            std::stringstream ss2(temp1);
            std::string temp2;
            z = 0;
            while (std::getline(ss2,temp2,'-'))
            {
                int id;
                {
                    std::istringstream iss(temp2);
                    iss >> id;
                }
                setTileId(coords,z,id);
                z++;
            }
            coords.x++;
        }
        coords.y++;
    }
    file.close();
    mNeedSave = false;
    return true;
}
void verticesGraph::buildGraph(char * fileName)
{
    milesTraveled = 0;
    std::string firstLine,lines;
    std::string itemArray[20][20];
    int m=0,quantity=0;
    std::ifstream inFile;
    inFile.open(fileName);
    if(inFile.good())
    {
        getline(inFile,firstLine);
        std::stringstream ss1(firstLine);
        std::string items1;
        while(getline(ss1,items1,','))
        {
            quantity+=1;
        }
        quantity-=1;
        while(getline(inFile,lines))
        {
            int n=0;
            std::stringstream ss2(lines);
            std::string items2;
            while(getline(ss2,items2,','))
            {
                itemArray[m][n]=items2;
                n+=1;
            }
            m+=1;
        }
    }

    for(int m=0;m<quantity;m++)
    {
        addVertex(itemArray[m][0]);
    }

    for(int m=0;m<quantity;m++)
    {
        for(int n=0;n<quantity;n++)
        {
            if(itemArray[m][n+1]!="-1"&&itemArray[m][n+1]!="0")
            {
                addEdge(itemArray[m][0],itemArray[n][0],atoi(itemArray[m][n+1].c_str()));
            }
        }
    }
}
コード例 #14
0
	void SDTestObject::test<3>()
		// construction via scalar values
		// tests both constructor and initialize forms
	{
		SDCleanupCheck check;
		
		LLSD b1(true);	ensureTypeAndValue("construct boolean", b1, true);
		LLSD b2 = true;	ensureTypeAndValue("initialize  boolean", b2, true);
		LLSD i1(42);	ensureTypeAndValue("construct int", i1, 42);
		LLSD i2 =42;	ensureTypeAndValue("initialize  int", i2, 42);
		LLSD d1(1.2);	ensureTypeAndValue("construct double", d1, 1.2);
		LLSD d2 = 1.2;	ensureTypeAndValue("initialize double", d2, 1.2);
		
		LLUUID newUUID;
		newUUID.generate();
		LLSD u1(newUUID);
						ensureTypeAndValue("construct UUID", u1, newUUID);
		LLSD u2 = newUUID;
						ensureTypeAndValue("initialize UUID", u2, newUUID);
		
		LLSD ss1(std::string("abc"));
						ensureTypeAndValue("construct std::string", ss1, "abc");
		LLSD ss2 = std::string("abc");
						ensureTypeAndValue("initialize std::string",ss2, "abc");
		LLSD sl1(std::string("def"));
						ensureTypeAndValue("construct std::string", sl1, "def");
		LLSD sl2 = std::string("def");
						ensureTypeAndValue("initialize std::string", sl2, "def");
		LLSD sc1("ghi");
						ensureTypeAndValue("construct const char*", sc1, "ghi");
		LLSD sc2 = "ghi";
						ensureTypeAndValue("initialize const char*",sc2, "ghi");

		LLDate aDay("2001-10-22T10:11:12.00Z");
		LLSD t1(aDay);	ensureTypeAndValue("construct LLDate", t1, aDay);
		LLSD t2 = aDay;	ensureTypeAndValue("initialize LLDate", t2, aDay);

		LLURI path("http://slurl.com/secondlife/Ambleside/57/104/26/");
		LLSD p1(path);	ensureTypeAndValue("construct LLURI", p1, path);
		LLSD p2 = path;	ensureTypeAndValue("initialize LLURI", p2, path);

		const char source[] = "once in a blue moon";
		std::vector<U8> data;
		copy(&source[0], &source[sizeof(source)], back_inserter(data));
		LLSD x1(data);	ensureTypeAndValue("construct vector<U8>", x1, data);
		LLSD x2 = data;	ensureTypeAndValue("initialize vector<U8>", x2, data);
	}
コード例 #15
0
ファイル: fileCryptopp.cpp プロジェクト: kleopatra999/seifrng
/**
 * @brief Encrypts input string stream using AES in GCM mode for
 *        confidentiality and authenticity.
 *
 * @param message const reference to a string stream with data.
 * @param cipherData reference to a byte vector to hold encrypted data.
 * @param key const reference to a byte vector with an encryption key.
 *
 * @return true, if encryption is successful.
 */
bool FileCryptopp::encrypt(
    const std::stringstream& message,
    std::vector<uint8_t>& cipherData,
    const std::vector<uint8_t>& key
) {

    // Initial Vector (IV) for AES to XOR.
    std::vector<uint8_t> iv(CryptoPP::AES::BLOCKSIZE);

    std::string plaintext = message.str(); // store message
    std::string ciphertext; // store encrypted message


    try {
        // Initialize AES.
        CryptoPP::GCM<AES>::Encryption e;

        // Set AES Key and load IV.
        e.SetKeyWithIV(key.data(), key.size(), iv.data());

        /* Load plain text into string source, then encrypt stream using
         * a transformation filter. Dump the transformation using a
         * string sink into ciphertext.
         */
        StringSource ss1(plaintext,
            true,
            new CryptoPP::AuthenticatedEncryptionFilter(
                e,
                new StringSink(ciphertext)
            ) // StreamTransformationFilter
        ); // StringSource

    } catch (const CryptoPP::Exception& e) {
        // Failed Encryption.
        std::cerr << "Error encrypting file: " << e.what() << std::endl;
        return false;
    }

    // Append cipherData with bytes from ciphertext.
    for (int i = 0; i < ciphertext.size(); i++) {
        cipherData.push_back(
            0xFF & static_cast<uint8_t>(ciphertext[i])
        );
    }

    return true;
}
コード例 #16
0
void selectSingleMuTrigEffTP(const TString conf,              // input file
                         const TString outputDir,         // output directory
                         Int_t RunRange = 0,              // Run Range
		         const Bool_t  matchGen = kFALSE  // match to generator muons
) {
  gBenchmark->Start("selectSingleMuEffTP");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //============================================================================================================== 
  
  // mass region
  Double_t massLo;
  Double_t massHi;

  Double_t lumi;              // luminosity (pb^-1)
  
  vector<TString>  fnamev;    // sample files 
  vector<Int_t>    typev;     // dataset type 
  vector<Double_t> xsecv;     // per file cross section
  vector<TString>  jsonv;     // per file JSON file

  //
  // parse .conf file
  //
  ifstream ifs;
  ifs.open(conf.Data());
  assert(ifs.is_open());
  string line;
  Int_t state=0;
  while(getline(ifs,line)) {
    if(line[0]=='#') continue;
    if(line[0]=='%') { 
      state++; 
      continue; 
    }
    
    if(state==0) {  // general settings
      stringstream ss1(line); ss1 >> lumi;
      getline(ifs,line);
      stringstream ss2(line); ss2 >> massLo >> massHi; 
      
    } else if(state==1) {  // define data sample
コード例 #17
0
ファイル: Test.cpp プロジェクト: irinalesina/ITStepProjects
void Test::LoadAnswers()
{
	std::string buffer, number;
	std::ifstream file;

	file.open("../Data/Answers.csv");
	if (!file.is_open())
		throw std::exception("Error: file(Question.csv) is not opened!\n");

	int question_num;
	while (!file.eof())
	{
		std::getline(file, buffer);
		std::vector<std::string> data = ParseCSVString(buffer);
		if (!data.size())
			break;

		number = data[0];
		std::stringstream ss(number);
		ss >> question_num;

		Answer answer(data[1]);
		for (auto it = data.begin() + 2; it != data.end(); it++)
		{
			// read trait number
			int trait_, score_;
			number = *it;
			std::stringstream ss1(number);
			ss1 >> trait_;

			//read score
			it++;

			number = *it;
			std::stringstream ss2(number);
			ss2 >> score_;
			answer.AddPoint(trait_, score_);
		}
		questions[question_num].answers.push_back(answer);
	}
	file.close();
}
コード例 #18
0
TEST_F(LoadPlanningModelsPr2, StateSpaces)
{
  ompl_interface::ModelBasedStateSpaceSpecification spec1(kmodel_, "right_arm");
  ompl_interface::ModelBasedStateSpace ss1(spec1);
  ss1.setup();

  ompl_interface::ModelBasedStateSpaceSpecification spec2(kmodel_, "left_arm");
  ompl_interface::ModelBasedStateSpace ss2(spec2);
  ss2.setup();

  ompl_interface::ModelBasedStateSpaceSpecification spec3(kmodel_, "whole_body");
  ompl_interface::ModelBasedStateSpace ss3(spec3);
  ss3.setup();

  ompl_interface::ModelBasedStateSpaceSpecification spec4(kmodel_, "arms");
  ompl_interface::ModelBasedStateSpace ss4(spec4);
  ss4.setup();
  
  std::ofstream fout("ompl_interface_test_state_space_diagram2.dot");
  ompl::base::StateSpace::Diagram(fout);
}
コード例 #19
0
    int compareVersion(string version1, string version2) {

      vector<int> v1, v2;
      int x;
      for (int i = 0; i < version1.size(); i++)
        if (version1[i] == '.') version1[i] = ' ';

      for (int i = 0; i < version2.size(); i++)
        if (version2[i] == '.') version2[i] = ' ';

      stringstream ss1(version1), ss2(version2);
      while (ss1 >> x) {
        v1.push_back(x);
      }
      while (ss2 >> x) {
        v2.push_back(x);
      }
      while (v1.size() > 0 && v1[v1.size() - 1] == 0 ) {
        if (v1[v1.size() - 1] == 0)
          v1.erase(v1.end() - 1);
      }
      while (v2.size() > 0 && v2[v2.size() - 1] == 0) {
        if (v2[v2.size() - 1] == 0)
          v2.erase(v2.end() - 1);
      }
      int i = 0, j = 0;
      for (; i < v1.size() && j < v2.size(); i++, j++) {
        if (v1[i] > v2[i])
          return 1;
        if (v2[i] > v1[i])
          return -1;
      }
      if (i < v1.size())
        return 1;
      if (j < v2.size())
        return -1;
      return 0;
    }
コード例 #20
0
int main(int argc, char *argv[])
{
	if( argc < 5 )
	{
		cerr << "Lack of args: need three args!" << endl;
		return -1;
	}

	ADDRINT nSizePower;
	stringstream ss(argv[1]);
	ss >> nSizePower;	
	cerr << "Memory Size (in bytes):\t" << hex << (1<<nSizePower) << dec << endl;	

	string szFile = argv[2];

	ADDRINT nLineSizeShift;
	stringstream ss1(argv[3]);
	ss1 >> nLineSizeShift;

	bool bStackAllocator = true;
	stringstream ss2(argv[4]);
	ss2 >> bStackAllocator;	

	
	

	CAllocator *allocator;

if(bStackAllocator)
	allocator = new CStackAllocator(nSizePower, nLineSizeShift, szFile);
else
	allocator = new CHeapAllocator(nSizePower, nLineSizeShift, szFile);


	allocator->run();
	return 0;
}
コード例 #21
0
/*  Constructs both the graph and the hash table. See the readme for a complete description of how this works.
    If flag is true, textIn is the name of a string. If false, it's used as a file name.
    Pre conditions: textIn cannot be "" or, if it's a filename, the name of a nonexistent file. If it is, the code
    will run, but various strange errors occur.
    Post conditions: Graph (not a class, so no name) and hash table (hashTable) constructed.
*/
void MarkovChain::add(std::string textIn, bool flag)
{
    if(!flag) //textIn is a filename
    {
        //The first word shouldn't be given an edge to itself, this bool allows it not to.
        bool firstword = true;
        Word *w;
        std::ifstream inFile(textIn);
        std::string line;
        std::string parsedWord;

        //Reads in the file line by line, and an inner getline() reads the line in word by word.
        while(getline(inFile, line))
        {
            if(isVerbose)
            {
                std::cout << "line: " << std::endl;
                std::cout << line << std::endl;
            }
            std::replace_if(line.begin(), line.end(), isNotAlpha, ' '); //Replaces all non alphabetical characters with spaces.
            std::istringstream ss(line);
            while(std::getline(ss, parsedWord, ' ')) //Parses lines into individual words.
            {
                //If word is not a space (resolved issue with seg fault on double spaces)
                if(parsedWord.compare(""))
                {
                    w = addWordToHashtable(parsedWord);
                    if(!firstword)
                    {
                        addEdge(w);
                    }
                    else
                    {
                        firstword = false;
                    }
                    currentWord = w;
                }
            }
        }

        if(isVerbose)
        {
            std::cout << "Finished reading in string" << std::endl;
        }
    }
    else //textIn is a string
    {
        //The first word shouldn't be given an edge to itself, this bool allows it not to.
        bool firstword = true;
        Word *w;
        std::string line;
        std::string parsedWord;
        std::istringstream ss1(textIn);
        int i = 0;

        //Parses the string line by line (artifact of previous code. We know there's a better way to do this.)
        while(std::getline(ss1, line, '\n'))
        {
            if(isVerbose)
            {
                std::cout << "Line: " << line << std::endl;
            }
            std::replace_if(line.begin(), line.end(), isNotAlpha, ' '); //Replaces all non alphabetical characters with spaces.
            std::istringstream ss2(line);
            //Parses each line word by word
            while(std::getline(ss2, parsedWord, ' '))
            {
                //If word is not a space (resolved issue with seg fault on double spaces)
                if(parsedWord.compare(""))
                {
                    w = addWordToHashtable(parsedWord);

                    if(!firstword)
                    {
                        addEdge(w);
                    }
                    else //change firstWord to false the first time through
                    {
                        firstword = false;
                    }
                    currentWord = w;
                }
            }
        }
        if(isVerbose)
        {
            std::cout << "Finished reading in string" << std::endl;
        }
    }
}
コード例 #22
0
// -------------------------------------------------------------------------- //
//
void Test_Specswap::testAccept()
{
    // Setup a specswap object with many different data sets.
    std::string path("./testfiles/testlibLarge");
    int sample = 12;
    Mlrnd rand;
    rand.set_seed(39);
    Specswap ss1(sample, rand, path);

    // Mean scalar.
    std::string scalarname("VP-Volume");
    double target = 0.5;
    double sigma = 1.0;
    ss1.add_scalar_mean(scalarname, target, sigma);
    sigma = 0.0012;
    ss1.add_scalar_mean(scalarname, target, sigma);

    // Value scalar.
    scalarname = "VP-Area";
    double value_low = 0.5;
    double value_high = 1.0;
    double fraction = 0.6;
    sigma = 0.0001;
    ss1.add_scalar_value(scalarname, value_low, value_high, fraction, sigma);
    fraction = 0.1;
    sigma = 0.0001;
    ss1.add_scalar_value(scalarname, value_low, value_high, fraction, sigma);
    value_low = 0.0;
    value_high = 1.3;
    fraction = 0.99;
    sigma = 0.01;
    ss1.add_scalar_value(scalarname, value_low, value_high, fraction, sigma);

    // Scalar distribution.
    scalarname = "VP-Volume";
    std::string filename("./testfiles/vvol_ref.data");
    sigma = 0.0002;
    ss1.add_scalar_distribution(scalarname, filename, sigma);
    sigma = 0.0099;
    ss1.add_scalar_distribution(scalarname, filename, sigma);

    // Curve.
    std::string curve_name("bas");
    filename = "./testfiles/exafs_ref.data";
    sigma = 0.0002;
    bool area_renorm = true;
    ss1.add_curve(sigma, area_renorm, curve_name, filename);
    area_renorm = false;
    ss1.add_curve(sigma, area_renorm, curve_name, filename);

    // Setup input for adding a pcf.
    double rmin = 0.0;
    double rmax = 5.0;
    double dr = 0.02;
    double numberdensity = 0.4;
    std::pair<double,double> fit_interval(1.3, 3.0);
    int nbins = 250;
    std::pair<int,int> partial(0,1);
    std::string ref_path("./testfiles/gr_ref.data");
    sigma = 0.01;
    ss1.add_pcf(rmin, rmax, dr, sigma, numberdensity, fit_interval, nbins, partial, ref_path);
    sigma = 0.0123;
    ss1.add_pcf(rmin, rmax, dr, sigma, numberdensity, fit_interval, nbins, partial, ref_path);

    // Setup.
    ss1.setup();
    // Move.
    ss1.move();

    // Check what slot and indices will be swapped.
    CPPUNIT_ASSERT_EQUAL( ss1.from_sample_, 583);
    CPPUNIT_ASSERT_EQUAL( ss1.from_basis_, 2354);
    CPPUNIT_ASSERT_EQUAL( ss1.slot_, 11);

    // Check that the sample set is correct.
    CPPUNIT_ASSERT_EQUAL( ss1.sampleset_.index_at(ss1.slot_), ss1.from_sample_);

    // Notify.
    ss1.notify();

    // Check the chi2 value.
    double diff = 7.2603029936e+08 - 6.5624713898e-04 - ss1.chi2_;
    CPPUNIT_ASSERT_DOUBLES_EQUAL( diff, 0.0, 1.0e-10 );

    // Check that the chi2_new value has been updated.
    diff = 7.4256423439e+08 + 1.9059181213e-03 - ss1.chi2_new_;
    CPPUNIT_ASSERT_DOUBLES_EQUAL( diff, 0.0, 1.0e-10 );

    // Call the accept and make sure Chi2 has been accepted.
    ss1.accept();
    CPPUNIT_ASSERT_DOUBLES_EQUAL( ss1.chi2_, ss1.chi2_new_, 1.0e-10 );

    // Check that the sample set is correct.
    CPPUNIT_ASSERT_EQUAL( ss1.sampleset_.index_at(ss1.slot_), ss1.from_basis_);
}
コード例 #23
0
// -------------------------------------------------------------------------- //
//
void Test_Specswap::testNotify()
{
    // Setup a specswap object with many different data sets.
    std::string path("./testfiles/testlibLarge");
    int sample = 12;
    Mlrnd rand;
    rand.set_seed(39);
    Specswap ss1(sample, rand, path);

    // Mean scalar.
    std::string scalarname("VP-Volume");
    double target = 0.5;
    double sigma = 1.0;
    ss1.add_scalar_mean(scalarname, target, sigma);
    sigma = 0.0012;
    ss1.add_scalar_mean(scalarname, target, sigma);

    // Value scalar.
    scalarname = "VP-Area";
    double value_low = 0.5;
    double value_high = 1.0;
    double fraction = 0.6;
    sigma = 0.0001;
    ss1.add_scalar_value(scalarname, value_low, value_high, fraction, sigma);
    fraction = 0.1;
    sigma = 0.0001;
    ss1.add_scalar_value(scalarname, value_low, value_high, fraction, sigma);
    value_low = 0.0;
    value_high = 1.3;
    fraction = 0.99;
    sigma = 0.01;
    ss1.add_scalar_value(scalarname, value_low, value_high, fraction, sigma);

    // Scalar distribution.
    scalarname = "VP-Volume";
    std::string filename("./testfiles/vvol_ref.data");
    sigma = 0.0002;
    ss1.add_scalar_distribution(scalarname, filename, sigma);
    sigma = 0.0099;
    ss1.add_scalar_distribution(scalarname, filename, sigma);

    // Curve.
    std::string curve_name("bas");
    filename = "./testfiles/exafs_ref.data";
    sigma = 0.0002;
    bool area_renorm = true;
    ss1.add_curve(sigma, area_renorm, curve_name, filename);
    area_renorm = false;
    ss1.add_curve(sigma, area_renorm, curve_name, filename);

    // Setup input for adding a pcf.
    double rmin = 0.0;
    double rmax = 5.0;
    double dr = 0.02;
    double numberdensity = 0.4;
    std::pair<double,double> fit_interval(1.3, 3.0);
    int nbins = 250;
    std::pair<int,int> partial(0,1);
    std::string ref_path("./testfiles/gr_ref.data");
    sigma = 0.01;
    ss1.add_pcf(rmin, rmax, dr, sigma, numberdensity, fit_interval, nbins, partial, ref_path);
    sigma = 0.0123;
    ss1.add_pcf(rmin, rmax, dr, sigma, numberdensity, fit_interval, nbins, partial, ref_path);


    // Set the initial chi2_ value to some thing unreasonable.
    ss1.chi2_new_ = -1.123;
    // Call the setup function.
    ss1.from_sample_ = 0;
    ss1.from_basis_ = 12;
    ss1.setup();
    // Call notify.
    ss1.notify();

    // Check that the chi2 value has been updated.
    CPPUNIT_ASSERT_DOUBLES_EQUAL(735129583.538380026817, ss1.chi2_new_, 1.0e-8);
}
コード例 #24
0
void Evaluation::loadData(std::string filename) {
    pairs.clear();
    
    tinyxml2::XMLDocument doc;
    if (tinyxml2::XML_NO_ERROR != doc.LoadFile(filename.c_str())) {
        std::cerr << "Cannot open " << filename << std::endl;
    }
    
    // Load parameters
    tinyxml2::XMLElement *root = doc.FirstChildElement("data");
    tinyxml2::XMLElement *params = root->FirstChildElement("parameters");
    
    double f = atof(params->FirstChildElement("f")->GetText());
    IncidentVector::setF(f);
    double f0 = atof(params->FirstChildElement("f0")->GetText());
    IncidentVector::setF0(f0);
    
    cv::Size2i img_size;
    std::stringstream ss(params->FirstChildElement("img_size")->GetText());
    std::string elem;
    ss >> elem;
    img_size.width = atoi(elem.c_str());
    ss >> elem;
    img_size.height = atoi(elem.c_str());
    IncidentVector::setImgSize(img_size);
    
    cv::Point2d center;
    std::stringstream ss1(params->FirstChildElement("center")->GetText());
    ss1 >> elem;
    center.x = atof(elem.c_str());
    ss1 >> elem;
    center.y = atof(elem.c_str());
    IncidentVector::setCenter(center);
    
    std::vector<double> a;
    std::stringstream ss2(params->FirstChildElement("a")->GetText());
    while (ss2 >> elem) {
        a.push_back(atof(elem.c_str()));
    }
    IncidentVector::setA(a);
    
    std::string projection = params->FirstChildElement("projection")->GetText();
    IncidentVector::setProjection(projection);
    
    // Load lines
    std::stringstream ssdata;
    tinyxml2::XMLElement *pair = root->FirstChildElement("pairs")->FirstChildElement("pair");
    
    while (pair != NULL) {
        Pair tmp;
        
        // edge1
        tinyxml2::XMLElement *lines1 = pair->FirstChildElement("lines1");
        tinyxml2::XMLElement *line = lines1->FirstChildElement("line");
        while (line != NULL) {
            std::vector<IncidentVector *> points; // One line
            tinyxml2::XMLElement *p = line->FirstChildElement("p");
            while (p != NULL) {
                cv::Point2d point;
                ssdata.str(p->GetText());
                ssdata >> point.x;
                ssdata >> point.y;
                switch (IncidentVector::getProjection()) {
                    case 0:
                        points.push_back(new StereographicProjection(point));
                        break;
                    case 1:
                        //TODO add Perspective projection
                        break;
                    case 2:
                        points.push_back(new EquidistanceProjection(point));
                        break;
                    case 3:
                        points.push_back(new EquisolidAngleProjection(point));
                        break;
                }
                ssdata.clear();
                p = p->NextSiblingElement("p");
            }
            tmp.edge[0].push_back(points);
            line = line->NextSiblingElement("line");
        }
        
        // edge2
        tinyxml2::XMLElement *lines2 = pair->FirstChildElement("lines2");
        line = lines2->FirstChildElement("line");
        while (line != NULL) {
            std::vector<IncidentVector *> points; // One line
            tinyxml2::XMLElement *p = line->FirstChildElement("p");
            while (p != NULL) {
                cv::Point2d point;
                ssdata.str(p->GetText());
                ssdata >> point.x;
                ssdata >> point.y;
                switch (IncidentVector::getProjection()) {
                    case 0:
                        points.push_back(new StereographicProjection(point));
                        break;
                    case 1:
                        //TODO add Perspective projection
                        break;
                    case 2:
                        points.push_back(new EquidistanceProjection(point));
                        break;
                    case 3:
                        points.push_back(new EquisolidAngleProjection(point));
                        break;
                }
                ssdata.clear();
                p = p->NextSiblingElement("p");
            }
            tmp.edge[1].push_back(points);
            line = line->NextSiblingElement("line");
        }
        
        pairs.push_back(tmp);
        pair = pair->NextSiblingElement("pair");
    }
    
    doc.Clear();
}
コード例 #25
0
ファイル: main.cpp プロジェクト: NicGanon/coolCompiler
//-------------------------------------------------------------------------------------------------------------------------------
//                                           中间语言翻译
void translate(LinkQueue head,TransQueue &tr)
{
    int Num=100;   
	Tr_stack sq;
	sq.base=sq.top=NULL;

	word *ptr=head->front;
	
	while(ptr)
	{
		if(ptr->Class=="KEYWORD")//保留字
		{
			if(ptr->Name=="while"||ptr->Name=="if")
			{
				Tr_push(sq,ptr->Name);
			}
			ptr=ptr->next;
			continue;
		}
		else if(ptr->Class=="IDEN")//iden 标识符
		{
			string str1=ptr->Name;
			ptr=ptr->next;
			string ex=ptr->Name;
			int mark=Tr_judge(ex);//判断标识符下一字符为运算符或大小于跳转
            if(mark==1)
			{
				ptr=ptr->next;
				string str2=ptr->Name;
				trans_ptr temp=new trans;//判断条件为真跳转语句

				temp->num=Num++;
				temp->name.exp1="j";
				temp->name.exp1.append(ex);
				temp->name.exp2=str1;
				temp->name.exp3=str2;

				char *c=new char;
				itoa(Num+1,c,10);
				string svai(c);
				temp->name.exp4=svai;
				
				temp->next=NULL;
				temp->pre=NULL;

				addTrans(tr,temp);//讲四元式结点加入到四元式链表中
			
				trans_ptr next=new trans;//判断条件为假跳转语句
				next->num=Num++;
				next->name.exp1="j";
				next->name.exp2="_";
				next->name.exp3="_";
				next->name.exp4=sq.top->keyword;
				
				next->next=NULL;
				next->pre=NULL;
				addTrans(tr,next);
				
			}
			else if(mark==2)
			{
				ptr=ptr->next;
				if(ptr->next->Name==";")//表达式为赋值语句
				{
					trans_ptr temp=new trans;
				    temp->num=Num++;
					temp->name.exp1=ex;
					temp->name.exp2=ptr->Name;
					temp->name.exp3="_";
					temp->name.exp4=str1;
					temp->next=NULL;
					temp->pre=NULL;
					addTrans(tr,temp);
					continue;
				}

				//运算语句
				Tr_stack s1,s2;
				s1.base=s1.top=NULL;
				s2.base=s2.top=NULL;
				while(ptr->Name!=";")//讲运算符和标识符分别入栈
				{
					if(ptr->Class=="IDEN")
					{
						Tr_push(s1,ptr->Name);
					
					}
					else
					{
						Tr_push(s2,ptr->Name);
					 
					}
					ptr=ptr->next;
				}
				while(s2.top)//运算符栈为空 则运算结束
				{
					
					string vai1=Tr_pop(s2);

					string vai2=Tr_pop(s1);
					string vai3=Tr_pop(s1);

					trans_ptr temp=new trans;
				    temp->num=Num++;
					temp->name.exp1=vai1;
					temp->name.exp2=vai3;
					temp->name.exp3=vai2;
					temp->name.exp4="t";
					temp->pre=NULL;
					temp->next=NULL;
					addTrans(tr,temp);
				}
				trans_ptr temp=new trans;//运算结果赋值
				temp->num=Num++;
				temp->name.exp1=ex;
				temp->name.exp2="t";
				temp->name.exp3="_";
				temp->name.exp4=str1;
				temp->pre=NULL;
				temp->next=NULL;
				addTrans(tr,temp);
			}
			ptr=ptr->next;
			continue;
		}
		else if(ptr->Name=="}")//遇到作用域结束,即if或while结束 回填条件为假跳转地址
		{
			if(!sq.top)
			{
				ptr=ptr->next;
				continue;
			}

			string str=Tr_pop(sq);
			trans_ptr temp=tr.rear;
			while(temp->name.exp4!=str)//想上找条件为假语句位置
			{
				temp=temp->pre;
			}
			if(str=="if")//if语句 只回填当前位置到 条件为假语句
			{
				char *c=new char;
				itoa(Num,c,10);
				string s(c);

				temp->name.exp4=s;
			}
			else          //while还包括 添加一条跳回判断条件的语句
			{
				char *ch=new char;
				
				trans_ptr ret=new trans;
				ret->num=Num++;
				ret->name.exp1="j";
				ret->name.exp2=ret->name.exp3="_";
				itoa(temp->pre->num,ch,10);
				string ss(ch);
				ret->name.exp4=ss;

				itoa(Num,ch,10);
				string ss1(ch);
				temp->name.exp4=ss1;
				ret->next=NULL;
				ret->pre=NULL;
				addTrans(tr,ret);
			}
		}
		ptr=ptr->next;
	}
}
コード例 #26
0
ファイル: efficiency.cpp プロジェクト: piberger/pixelScripts
int efficiency(char* path0) {
	char the_path[256];
    getcwd(the_path, 255);

    std::string path(path0);


  	unsigned found = path.find_last_of("/\\", path.size()-2);

    std::string dataPath(path.substr(0,found));
    std::string measurementFolder(path.substr(found+1));

	std::stringstream ss1(measurementFolder);
    std::string moduleName;
    std::getline(ss1, moduleName, '_');

	std::string rootFileName("commander_HREfficiency.root");
	std::string maskFileName("defaultMaskFile.dat");

	const bool FIDUCIAL_ONLY = true;
	const bool VERBOSE = true;

	int nTrigPerPixel = 50;
	int nPixels = 4160;
	int nTrig = nTrigPerPixel * nPixels;
	float pixelArea = 0.01 * 0.015; // cm^2
	float triggerDuration = 25e-9; //s

	int nRocs = 16;
	
	//search for XrarSpectrum folders in elComandante folder structure
    TSystemDirectory dir(path.c_str(), path.c_str());
    TList *files = dir.GetListOfFiles();
    std::vector<std::string> directoryList;
    if (files) {
      TSystemFile *file;
      TString fname;
      TIter next(files);
      while (file=(TSystemFile*)next()) {
         fname = file->GetName();
         if (file->IsDirectory()) {
         	std::string dirname(fname.Data());
         	if (dirname.find("HREfficiency") != std::string::npos) {
         		directoryList.push_back(dirname);
         	}
         }
      }
    }

    std::vector< std::vector< std::pair< int,int > > > maskedPixels;

    //sort!
	std::sort(directoryList.begin(), directoryList.end());

	std::vector< std::vector< double > > efficiencies;
	std::vector< std::vector< double > > efficiencyErrors;
	std::vector< std::vector< double > > rates;
	std::vector< std::vector< double > > rateErrors;


	for (int i=0;i<nRocs;i++) {
		std::vector< double > empty;
		efficiencies.push_back(empty);
		efficiencyErrors.push_back(empty);
		rates.push_back(empty);
		rateErrors.push_back(empty);
	}

	// loop over all commander_HREfficiency.root root files
	for (int i=0;i<directoryList.size();++i) {
		chdir(path.c_str());
		std::cout << "looking in directory <" << directoryList[i] << ">" << std::endl;

		std::ifstream testParameters(Form("%s/testParameters.dat", directoryList[i].c_str()));
		std::string line2;
		while (getline(testParameters, line2)) {
			std::transform(line2.begin(), line2.end(), line2.begin(), ::tolower);
			if (line2.find("highrate") != std::string::npos) {
				while (getline(testParameters, line2)) {
					if (line2.size() < 1) break;
					std::transform(line2.begin(), line2.end(), line2.begin(), ::tolower);
					size_t pos = line2.find("ntrig");
					if (pos != std::string::npos) {
						nTrigPerPixel = atoi(line2.substr(pos+6).c_str());
						nTrig = nTrigPerPixel * nPixels;
						std::cout << ">" << line2 << "< pos:" << pos << std::endl;
						std::cout << "number of triggers per pixel: " << nTrigPerPixel << std::endl;
					}
				}

			}
		}
		testParameters.close();


		// read masked pixels
	    maskedPixels.clear();
		for (int j=0;j<nRocs;j++) {
			std::vector< std::pair<int,int> > rocMaskedPixels;
			maskedPixels.push_back(rocMaskedPixels);
		}
		std::ifstream maskFile;
		char maskFilePath[256];
		sprintf(maskFilePath, "%s/%s/%s", path.c_str(), directoryList[i].c_str(), maskFileName.c_str());
		maskFile.open(maskFilePath, std::ifstream::in);
		if (!maskFile) {
			std::cout << "ERROR: mask file <" << maskFilePath << "> can't be opened!"<<std::endl;
		}
		std::string line;
		std::vector< std::string > tokens;
		while(getline(maskFile, line)) {
			if (line[0] != '#') {
				std::stringstream ss(line); 
	    		std::string buf;
	    		tokens.clear();
				while (ss >> buf) {
					tokens.push_back(buf);
				}
				std::cout << "tok0 <" << tokens[0] << "> ";
				if (tokens[0] == "pix" && tokens.size() >= 4) {
					int roc = atoi(tokens[1].c_str());
					int col = atoi(tokens[2].c_str());
					int row = atoi(tokens[3].c_str());
					std::cout << "mask pixel " << roc << " " << col << " " << row << std::endl;
					maskedPixels[roc].push_back(make_pair(col, row));
				}
			}
		}
		maskFile.close();

		chdir(directoryList[i].c_str());
		
		TFile f(rootFileName.c_str());
		if (f.IsZombie()) {
			std::cout << "could not read: " << rootFileName << " .";
			exit(0);
		}
		std::cout << "list keys:" << std::endl;
		TIter next(f.GetListOfKeys());
		bool highRateFound = false;


		while (TKey *obj = (TKey*)next()) {
			if (strcmp(obj->GetTitle(),"HighRate") == 0) highRateFound = true;
			if (VERBOSE) {
				std::cout << obj->GetTitle() << std::endl;
			}
		}
		if (highRateFound) {
			std::cout << "highRate test found, reading data..." << std::endl;
			TH2D* xraymap;
			TH2D* calmap;
			char calmapName[256];
			char xraymapName[256];
			std::ofstream output;

			for (int iRoc=0;iRoc<nRocs;iRoc++) {

				std::cout << "ROC" << iRoc << std::endl;
				sprintf(xraymapName, "HighRate/highRate_xraymap_C%d_V0;1", iRoc);
				f.GetObject(xraymapName, xraymap);
				if (xraymap == 0) {
					std::cout << "ERROR: x-ray hitmap not found!" << std::endl;
				}
				int nBinsX = xraymap->GetXaxis()->GetNbins();
				int nBinsY = xraymap->GetYaxis()->GetNbins();

				sprintf(calmapName, "HighRate/highRate_C%d_V0;1", iRoc);
				f.GetObject(calmapName, calmap);
				if (calmap == 0) {
					sprintf(calmapName, "HighRate/highRate_calmap_C%d_V0;1", iRoc);
					f.GetObject(calmapName, calmap);
					if (calmap == 0) {
						std::cout << "ERROR: calibration hitmap not found!" << std::endl;
					}
				}

				//std::cout << nBinsX << "x" << nBinsY << std::endl;
				float rate, efficiency;

				for (int doubleColumn = 1; doubleColumn < 25; doubleColumn++) {
					//std::cout << "reading dc " << doubleColumn << std::endl;

					std::vector<double> hits;
					std::vector<double> xray_hits;

					for (int y = 0; y < 160; y++) {

						bool masked = false;

						for (int iMaskedPixels=0; iMaskedPixels < maskedPixels[iRoc].size(); iMaskedPixels++) {
							if (maskedPixels[iRoc][iMaskedPixels].first == doubleColumn * 2 + (int)(y / 80) && maskedPixels[iRoc][iMaskedPixels].second == (y % 80)) {
								masked = true;
								break;
							}
						}

						if ((!FIDUCIAL_ONLY || ((y % 80) > 0 && (y % 80) < 79)) && !masked) {
							//std::cout << " get " << (doubleColumn * 2 + (int)(y / 80) + 1) << " / " <<  ((y % 80) + 1) << std::endl;

							hits.push_back( calmap->GetBinContent(doubleColumn * 2 + (int)(y / 80) + 1, (y % 80) + 1) );
							xray_hits.push_back( xraymap->GetBinContent(doubleColumn * 2 + (int)(y / 80) + 1, (y % 80) + 1) );

						}
					}
					//std::cout << "calculating rates and efficiencies" << std::endl;

					int nPixelsDC = hits.size();
					if (nPixelsDC < 1) nPixelsDC = 1;
					double rate = TMath::Mean(nPixelsDC, &xray_hits[0]) / (nTrig * triggerDuration * pixelArea) * 1.0e-6;
					double efficiency = TMath::Mean(nPixelsDC, &hits[0]) / nTrigPerPixel;
					double rateError = TMath::RMS(nPixelsDC, &xray_hits[0]) / std::sqrt(nPixelsDC) / (nTrig * triggerDuration * pixelArea) * 1.0e-6;
					double efficiencyError = TMath::RMS(nPixelsDC, &hits[0]) / std::sqrt(nPixelsDC) / nTrigPerPixel;

					
						efficiencies[iRoc].push_back(efficiency);
						efficiencyErrors[iRoc].push_back(efficiencyError);
						rates[iRoc].push_back(rate);
						rateErrors[iRoc].push_back(rateError);
					

					if (VERBOSE) {
						std::cout << "dc " << doubleColumn << " nPixelsDC: " << nPixelsDC << " rate: " << rate << " " << efficiency << std::endl;
					}
				}
			}



	  		//output.open (Form("%s/output_%d.txt",the_path,i), std::ofstream::out);
			//output.close();

		} else {
			std::cout << "high rate test not found";
			return 1;
		}
	}
コード例 #27
0
ファイル: svd.hpp プロジェクト: 10imaging/viennacl
      void svd_qr_shift(MatrixType & vcl_u,
                        MatrixType & vcl_v,
                        CPU_VectorType & q,
                        CPU_VectorType & e)
      {
        typedef typename MatrixType::value_type                                   ScalarType;
        typedef typename viennacl::result_of::cpu_value_type<ScalarType>::type    CPU_ScalarType;

        vcl_size_t n = q.size();
        int m = static_cast<int>(vcl_u.size1());

        detail::transpose(vcl_u);
        detail::transpose(vcl_v);

        std::vector<CPU_ScalarType> signs_v(n, 1);
        std::vector<CPU_ScalarType> cs1(n), ss1(n), cs2(n), ss2(n);

        viennacl::vector<CPU_ScalarType> tmp1(n, viennacl::traits::context(vcl_u)), tmp2(n, viennacl::traits::context(vcl_u));

        bool goto_test_conv = false;

        for (int k = static_cast<int>(n) - 1; k >= 0; k--)
        {
          // std::cout << "K = " << k << std::endl;

          vcl_size_t iter = 0;
          for (iter = 0; iter < detail::ITER_MAX; iter++)
          {
            // test for split
            int l;
            for (l = k; l >= 0; l--)
            {
              goto_test_conv = false;
              if (std::fabs(e[vcl_size_t(l)]) <= detail::EPS)
              {
                // set it
                goto_test_conv = true;
                break;
              }

              if (std::fabs(q[vcl_size_t(l) - 1]) <= detail::EPS)
              {
                // goto
                break;
              }
            }

            if (!goto_test_conv)
            {
              CPU_ScalarType c = 0.0;
              CPU_ScalarType s = 1.0;

              //int l1 = l - 1;
              //int l2 = k;

              for (int i = l; i <= k; i++)
              {
                CPU_ScalarType f = s * e[vcl_size_t(i)];
                e[vcl_size_t(i)] = c * e[vcl_size_t(i)];

                if (std::fabs(f) <= detail::EPS)
                {
                  //l2 = i - 1;
                  break;
                }

                CPU_ScalarType g = q[vcl_size_t(i)];
                CPU_ScalarType h = detail::pythag(f, g);
                q[vcl_size_t(i)] = h;
                c = g / h;
                s = -f / h;

                cs1[vcl_size_t(i)] = c;
                ss1[vcl_size_t(i)] = s;
              }

              // std::cout << "Hitted!" << l1 << " " << l2 << "\n";

              // for (int i = l; i <= l2; i++)
              // {
              //   for (int j = 0; j < m; j++)
              //   {
              //     CPU_ScalarType y = u(j, l1);
              //     CPU_ScalarType z = u(j, i);
              //     u(j, l1) = y * cs1[i] + z * ss1[i];
              //     u(j, i) = -y * ss1[i] + z * cs1[i];
              //   }
              // }
            }

            CPU_ScalarType z = q[vcl_size_t(k)];

            if (l == k)
            {
              if (z < 0)
              {
                q[vcl_size_t(k)] = -z;

                signs_v[vcl_size_t(k)] *= -1;
              }

              break;
            }

            if (iter >= detail::ITER_MAX - 1)
              break;

            CPU_ScalarType x = q[vcl_size_t(l)];
            CPU_ScalarType y = q[vcl_size_t(k) - 1];
            CPU_ScalarType g = e[vcl_size_t(k) - 1];
            CPU_ScalarType h = e[vcl_size_t(k)];
            CPU_ScalarType f = ((y - z) * (y + z) + (g - h) * (g + h)) / (2 * h * y);

            g = detail::pythag<CPU_ScalarType>(f, 1);

            if (f < 0) {
              f = ((x - z) * (x + z) + h * (y / (f - g) - h)) / x;
            } else {
              f = ((x - z) * (x + z) + h * (y / (f + g) - h)) / x;
            }

            CPU_ScalarType c = 1;
            CPU_ScalarType s = 1;

            for (vcl_size_t i = static_cast<vcl_size_t>(l) + 1; i <= static_cast<vcl_size_t>(k); i++)
            {
              g = e[i];
              y = q[i];
              h = s * g;
              g = c * g;
              CPU_ScalarType z2 = detail::pythag(f, h);
              e[i - 1] = z2;
              c = f / z2;
              s = h / z2;
              f = x * c + g * s;
              g = -x * s + g * c;
              h = y * s;
              y = y * c;

              cs1[i] = c;
              ss1[i] = s;

              z2 = detail::pythag(f, h);
              q[i - 1] = z2;
              c = f / z2;
              s = h / z2;
              f = c * g + s * y;
              x = -s * g + c * y;

              cs2[i] = c;
              ss2[i] = s;
            }

            {
              viennacl::copy(cs1, tmp1);
              viennacl::copy(ss1, tmp2);

              givens_prev(vcl_v, tmp1, tmp2, static_cast<int>(n), l, k);
            }

            {
              viennacl::copy(cs2, tmp1);
              viennacl::copy(ss2, tmp2);

              givens_prev(vcl_u, tmp1, tmp2, m, l, k);
            }

            e[vcl_size_t(l)] = 0.0;
            e[vcl_size_t(k)] = f;
            q[vcl_size_t(k)] = x;
          }

        }


        viennacl::copy(signs_v, tmp1);
        change_signs(vcl_v, tmp1, static_cast<int>(n));

        // transpose singular matrices again
        detail::transpose(vcl_u);
        detail::transpose(vcl_v);
      }
コード例 #28
0
ファイル: plotRecoEffTP.C プロジェクト: sixie/EWKAna
void plotRecoEffTP(const TString conf      = "zee.conf",      // input file
                   const TString outputDir = "foobar",  // output directory
	           const TString format    = "png"            // plot format
) {
  gBenchmark->Start("plotRecoEffTP");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //============================================================================================================== 
  
  // trigger requirement
  const UInt_t trigger = kHLT_Ele15_LW_L1R;
 
  // histogram ranges
  const Double_t elePtMin  = 20;
  const Double_t elePtMax  = 200;
  const Double_t eleEtaMin = -2.5;
  const Double_t eleEtaMax = 2.5;
  
  // mass region
  const Double_t massLo = 60;
  const Double_t massHi = 120;
  
  // cuts for computing overall electron efficiency in smaller phase space
  const Double_t etCut  = 20;
  const Double_t etaCut = 2.5;
  
  // efficiency error calculation method
  // method: 0 -> Bayes Divide
  //         1 -> Feldman-Cousins 
  //         2 -> Clopper-Pearson  
  const Int_t method=0;

  Double_t lumi;              // luminosity (pb^-1)
  Bool_t   doWeight;          // weight events?  
  
  vector<TString>  fnamev;    // sample files 
  vector<Double_t> xsecv;     // per file cross section
  vector<TString>  jsonv;     // per file JSON file
  vector<Double_t> weightv;   // per file event weight

  //
  // parse .conf file
  //
  ifstream ifs;
  ifs.open(conf.Data());
  assert(ifs.is_open());
  string line;
  Int_t state=0;
  while(getline(ifs,line)) {
    if(line[0]=='#') continue;
    if(line[0]=='%') { 
      state++; 
      continue; 
    }
    
    if(state==0) {  // general settings
      stringstream ss1(line); ss1 >> lumi;
      getline(ifs,line);
      stringstream ss2(line); ss2 >> doWeight;
      
    } else if(state==1) {  // define data sample
コード例 #29
0
ファイル: param_io.cpp プロジェクト: Nuos/Image-Morphing
void parse_config_xml(Parameters &params, const std::string &fname)
{
    static bool initxml = false;
    if(!initxml)
    {
        xmlInitParser();
        xmlXPathInit();
        atexit(xmlCleanupParser);

        initxml = true;
    }

    xmlDoc *doc = NULL;
    xmlXPathContext *ctx = NULL;

    try
    {
        doc = xmlParseFile(fname.c_str());
        if(!doc)
            throw std::runtime_error("Syntax error in "+fname);

        if(!doc->children)
            throw std::runtime_error("Semantic error in "+fname);

        ctx = xmlXPathNewContext(doc);
        if(!ctx)
            throw std::runtime_error("Unable to create XPath context");

        params.fname0 = get_data(ctx, "//project/images/@image1",params.fname0);
        params.fname1 = get_data(ctx, "//project/images/@image2",params.fname1);

        // circumvent MdiEditor's notion that relative files must begin with '/'
        if(!params.fname0.empty() && (params.fname0[0] == '/' || params.fname0[0] == '\\'))
            params.fname0 = params.fname0.substr(1);
        if(!params.fname1.empty() && (params.fname1[0] == '/' || params.fname1[0]=='\\'))
            params.fname1 = params.fname1.substr(1);

	int slash = fname.find_last_of("/\\");
	std::string root_path;

	if(slash != fname.npos)
	{
	    root_path = fname.substr(0,slash+1); // root_path includes final slash
	    params.fname0 = root_path + params.fname0;
	    params.fname1 = root_path + params.fname1;
	}

        std::string base = "/project/layers";

        params.w_tps
            = get_data(ctx, base+"/l0/parameters/weight/@tps", params.w_tps);

        params.w_ssim
            = get_data(ctx, base+"/l0/parameters/weight/@ssim", params.w_ssim);

        params.w_ui
            = get_data(ctx, base+"/l0/parameters/weight/@ui", params.w_ui);

        params.ssim_clamp
            = 1-get_data(ctx, base+"/l0/parameters/weight/@ssimclamp", 1-params.ssim_clamp);

        int bound;
        switch(params.bcond)
        {
        case BCOND_NONE:
            bound = 0;
            break;
        case BCOND_CORNER:
            bound = 1;
            break;
        case BCOND_BORDER:
            bound = 2;
            break;
        }

        bound = get_data(ctx, base+"/l0/parameters/boundary/@lock", bound);

        switch(bound)
        {
        case 0:
            params.bcond = BCOND_NONE;
            break;
        case 1:
            params.bcond = BCOND_CORNER;
            break;
        case 2:
            params.bcond = BCOND_BORDER;
            break;
        default:
            throw std::runtime_error("Bad boundary value");
        }

        params.eps
            = get_data(ctx, base+"/l0/parameters/debug/@eps", params.eps);
        params.start_res
            = get_data(ctx, base+"/l0/parameters/debug/@startres", params.start_res);
        params.max_iter
            = get_data(ctx, base+"/l0/parameters/debug/@iternum", params.max_iter);
        params.max_iter_drop_factor
            = get_data(ctx, base+"/l0/parameters/debug/@dropfactor", params.max_iter_drop_factor);

        std::string pts0
            = get_data(ctx, base+"/l0/parameters/points/@image1", "");

        std::string pts1
            = get_data(ctx, base+"/l0/parameters/points/@image2", "");

        if(!pts0.empty())
        {
            params.ui_points.clear();

            std::istringstream ss0(pts0), ss1(pts1);

            while(ss0 && ss1)
            {
                ConstraintPoint cpt;

                float2 pt;
                ss0 >> pt.x >> pt.y;
                cpt.lp = make_double2(pt.x, pt.y);

                ss1 >> pt.x >> pt.y;
                cpt.rp = make_double2(pt.x, pt.y);

                if(ss0 && ss1)
                    params.ui_points.push_back(cpt);
            }

            if(ss0.eof() && !ss1.eof() || !ss0.eof() && ss1.eof())
                throw std::runtime_error("Control point parsing error");
        }

        xmlXPathFreeContext(ctx);
        xmlFreeDoc(doc);
    }
コード例 #30
0
ファイル: model.cpp プロジェクト: YIYAYIYAYOUCHENG/EFFORTS
Model::Model(const MODEL &mod)
{
    type = DEF;
    fast_reach = false; 
    fpfp_sim = false;
    op = false;
    cpus = 2;
    ci = false;
    bp = false;
    // variable list
    var_list = mod.var_list;
    // reserved variable list has been abandoned
    reserved_var_list = mod.reserved_var_list;
    // the parsed parameter list
    param_list = mod.param_list;
    // parameters for IMCR
    im_param_list = mod.im_param_list;
    // the parsed initial declaration
    init = mod.init;
    
    // param_list = known params + unknown params
    Param_list unknown_param_list;
    for (unsigned i = 0; i < param_list.params.size(); i++)
        if( param_list.params[i].op == "=")
            known_param_list.params.push_back(param_list.params[i]);
        else 
            unknown_param_list.params.push_back(param_list.params[i]);
    param_list = unknown_param_list;

    /** 
     * for now, let's focus on reachability analysis
     **/
    //build_param_list_im();

    for ( vector<AUTOMATON>::const_iterator it = 
	     mod.automaton_v.begin(); it != mod.automaton_v.end(); it ++) {
	Automaton *aton = new Automaton(*it);	
	string s1 = aton->name;
	for ( unsigned i = 0; i < aton->locations.size(); i++) {
	    string s2 = aton->locations[i]->name;
	    pair_ss ss1(s1, s2);
	    aton->locations[i]->is_bad = find(ss1, init.bads);
	    if( find(ss1, init.init))
		aton->init = aton->locations[i];
	} 
	automata.push_back(aton);
    }			
		
    //cout << "number of automata " << automata.size() << endl;
    //for (unsigned i = 0; i < automata.size(); i++) {
    //    cout << i << " automaton " << automata[i]->name << endl;
    //    automata[i]->print();
    //}
		
    // Bounded parametric synthesis
    bound = numeric_limits<int>::max();
    cout << "To composite ... ";
    com = automata.at(0);
    for (unsigned i = 1; i < automata.size(); i++) {
        com = composite(com, automata[i]);
    }
    cout << " Done!\n";
    //com->print();

    for (vector<Location*>::iterator it = com->locations.begin();
	  it != com->locations.end(); ++it) {
        (*it)->populate_signature();
	for (unsigned i = 0; i < (*it)->outgoing.size(); i++) {
	    (*it)->outgoing[i].index = UniqueIndex::get_next_index();
            //(*it)->outgoing[i].guard_cvx = guard_cvx( (*it)->outgoing[i] );
        }
        (*it)->time_elapse = time_elapse_cvx(*it);

        passed_map[(*it)->signature] = make_shared< list<shared_ptr<pair_sc> > > ();
        passing_map[(*it)->signature] = make_shared< list<shared_ptr<pair_sc> > > ();
        next_map[(*it)->signature] = make_shared< list<shared_ptr<pair_sc> > > ();
    }

    N = var_list.vars.size() / 2;
    /** 
     * for now, let's focus on reachability analysis
     **/
    //ff_poly = NNC_Polyhedron(0, EMPTY);
    //line = 0;
}