Example #1
0
void FilesGrouper::mergeSortedFiles(string fs1, string fs2, string output_file) {
	ofstream merged_file(output_file);  
 	string s1, s2; 
 	ifstream ifs1(fs1);
 	ifstream ifs2(fs2);

 	getline(ifs1, s1); 
 	getline(ifs2, s2); 

 	while (ifs1.good() && ifs2.good()) {
 		if (s1 < s2) {
 			merged_file << s1; 
 			getline(ifs1, s1); 
 		} else {
 			merged_file << s2; 
 			getline(ifs2, s2);
 		}
 		merged_file << "\n"; 
 	}

 	// finish off the remaining of each file and appending the previously read file name 

 	if (ifs1.good()) {
 		merged_file << s1 << "\n"; 
 		while (getline(ifs1, s1))
 			merged_file << s1 << "\n";
 	} else {
 		merged_file << s2 << "\n"; 
 		while (getline(ifs2, s2))
 			merged_file << s2 << "\n"; 
 	}
 	merged_file.close(); 
}
Example #2
0
// A helper function which compares a content of two files
bool  compareFiles( const std::string &     fileName1,
                    const std::string &     fileName2 )
{
    ifstream       ifs1( fileName1.c_str() ), ifs2( fileName2.c_str() );

    return NcbiStreamCompare(ifs1, ifs2);
}
int main(int argc, char** argv)
{
	if (argc < 3)
	{
		std::cout << "Usage: combustion-vineyard FRAME1 FRAME2" << std::endl;
		exit(0);
	}
	
	int size0, nc0;
	int size1, nc1;

	std::cout << "Reading: " << argv[1] << std::endl;
	std::ifstream ifs0(argv[1], std::ios::binary);
	std::cout << "Reading: " << argv[2] << std::endl;
	std::ifstream ifs1(argv[2], std::ios::binary);

	if (!ifs0 || !ifs1)
	{
		std::cout << "Could not open the frames" << std::endl;
		exit(0);
	}

	read(ifs0, size0); read(ifs0, nc0);
	read(ifs1, size1); read(ifs1, nc1);

	assert(size0 == size1); assert(nc0 == nc1);
	assert(size0 == xsize*ysize);
	
	Grid2D g0(xsize, ysize), g1(xsize, ysize);
	
	for (int y = 0; y < ysize; ++y)
		for (int x = 0; x < xsize; ++x)
			for (int d = 0; d < nc0; ++d)
			{
				float val0, val1;
				read(ifs0, val0);
				read(ifs1, val1);
				if (d == var)
				{
					g0(x,y) = val0;
					g1(x,y) = val1;
				}
			}
	std::cout << "Grids read" << std::endl;
	
	// Generate filtration and compute pairing
	Grid2DVineyard v(&g0);
	std::cout << "Filtration generated, size: " << v.filtration()->size() << std::endl;
	v.compute_pairing();
	std::cout << "Pairing computed" << std::endl;
	
	// Compute vineyard
	v.compute_vineyard(&g1, true);
	std::cout << "Vineyard computed" << std::endl;

	v.vineyard()->save_edges("combustion");
}
Example #4
0
void read_file(std::string input1,std::string input2,std::string input3){
  std::ifstream ifs1(input1.c_str());
  std::ifstream ifs2(input2.c_str());
  std::ifstream ifs3(input3.c_str());
  float label1;
  ifs1 >> input1;
  ifs1 >> label1;
  ifs1 >> label1;
  ifs2 >> input2;
  ifs2 >> label1;
  ifs2 >> label1;
  ifs3 >> input3;
  ifs3 >> label1;
  ifs3 >> label1;
  int num=0;
  int pos[3]={0};
  int neg[3]={0};
  int other;
  float label2,label3;
  while(!ifs1.eof()){
    ifs1 >> label1;
    ifs2 >> label2;
    ifs3 >> label3;
    ifs1 >> label1;
    ifs2 >> label2;
    ifs3 >> label3;
    if(label1 < OTHER && label2 < OTHER && label3 <OTHER)
      other++;
    if(label1>label2){
      if(label1>label3)
	pos[0]++;
      else
	pos[2]++;
    }
    else if(label1<label2){
      if(label2>label3)
	pos[1]++;
      else
	pos[2]++;
    }
    ifs1 >> label1;
    ifs2 >> label2;
    ifs3 >> label3;
    num++;
  }
  for(int i=1;i<=3;i++){
    std::cout << i << ":" << (float)pos[i-1]/num*100 << " ";
  }
  std::cout << other << ":" <<(float)other/num*100 << " ";
  std::cout << "\n";
}
Example #5
0
int main(int argc, char **argv) {

    Vocab3 vocab;
    Splitter s(vocab,3,true);
    s.load_vocab(argv[1]);
    s.go();
    NgramCounter unigrams(1);
    ifstream ifs1(argv[1]);
    LineTokenizer lt1(ifs1);
    while(lt1.next()){
        Tokenizer tok(lt1.token(),' ');
        while(tok.next()){
            int wid = vocab.Add(tok.token());
            unigrams.increase_count(&wid,1);
        }
    }

    ifstream ifs(argv[1]);
    LineTokenizer lt(ifs);
    NgramCounter ng(2);
    while(lt.next()){
        Tokenizer tok(lt.token(),' ');
        while(tok.next()){
            int wid = vocab.Add(tok.token());
            int clid = s.get_class(wid);
            if (clid < 0 || unigrams.get_count(&wid) > 100 ){
                clid = wid;
            }
            else {
                string cl = "-" + s.class_set.Get(clid).str();
                clid = vocab.Add(LString(cl));
            }

            int key[2] = {clid,wid};
            ng.increase_count(key,1);
            cout << vocab.Get(clid) << " "; 
        }
        cout << endl;
    }
    BtreeIterator it = ng.iterator();
    ofstream ofs("my.classes");
    while(it.next()){
         ofs << vocab.Get(it.key()[1]) << "\t" << vocab.Get(it.key()[0]) << "\t" << (int)it.double_value()[0] << endl;
    }
    ofstream ofs2("my.classmap");
    it = s.class_map.iterator();
    while (it.next()){

         ofs2 << vocab.Get(it.key()[0]) << "\t" << s.class_set.Get(it.key()[1]) << endl;
    }
}
Example #6
0
void Draw(){

  gSystem->Load("../AnalysisLib/lib/libAnalysisLib.so");

  IDHandler* handler = new IDHandler();
  CsIImage* image    = new CsIImage(handler);
  TH1D* hisResidual = new TH1D("his","",80,-0.2,0.2);
  
  std::ifstream ifs("CalibrationData/OldCalibrationData/CalibrationFactor_8.dat");
  if( !ifs.is_open() ) return;
  Double_t gainList[2716]= {1};
  Double_t gainListSpec[2716]={1};

  while( !ifs.eof() ){
    int ID;
    double gain;
    ifs >> ID >> gain;
    std::cout << ID << " : " <<  gain << std::endl;
    gainList[ID] = gain;
  }

  std::ifstream ifs1("Data/calibConstKe3.dat");
  while( !ifs1.eof()){
    int ID;
    double gain;
    ifs1 >> ID >> gain;
    gainListSpec[ID] = gain;
  }

  TGraph*gr = new TGraph();
  for( int i = 0; i<2716; i++){
    image->Fill(i,gainList[i]);    
    gr->SetPoint(gr->GetN(), gainList[i],gainListSpec[i]);
    if( !gainList[i]==0){
      hisResidual->Fill((gainList[i]-gainListSpec[i])/gainList[i]);
    }
  }


  TCanvas* can = new TCanvas("can","",800,800);
  //gr->Draw("AP");
  //image->DrawWithRange("colz",0.8,1.2);
  hisResidual->Fit("gaus","","",-0.03,0.06);
  hisResidual->Draw();
  //image->Draw();
}
Example #7
0
void testResult(){
  
  std::ifstream ifs0("simGain.txt");
  std::ifstream ifs1("CalibrationN.txt");
  if( !ifs0.is_open() ){return;}
  if( !ifs1.is_open() ){return;}

  TH1D* hisGain = new TH1D("test","",200,0,2);
  TH1D* hisInit = new TH1D("test1","",200,0,2);
  double cal0;
  double cal1;
  double calfactor0[2716]={0};
  double calfactor1[2716]={0};
  
  Int_t  N;
  Int_t ID;
  while( !ifs0.eof() ){
    ifs0 >> ID >> cal0;
    calfactor0[ID] = cal0;
    std::cout<< ID << std::endl;
  }

  while( !ifs1.eof() ){
    ifs1 >> ID >> cal1 >> N;
    std::cout<< ID << std::endl;
    calfactor1[ID] = cal1;
  }
  
  for( int i = 0; i< 2716; i++){
    if(calfactor0[i] ==0 || calfactor1[i] ==0){
      continue;
    }
    hisGain->Fill(calfactor0[i]/calfactor1[i]);
    hisInit->Fill(calfactor0[i]);
  }
  hisGain->Draw();
  hisInit->SetLineColor(2);
  hisInit->Draw("same");

  std::cout<< hisGain->GetRMS()/hisGain->GetMean() << "\t"
	   << hisInit->GetRMS()/hisInit->GetMean() << std::endl;
}
Example #8
0
void Vocabulary::loadPretrainedVector(const std::string& file){
  std::ifstream ifs1(file.c_str());
  std::ifstream ifs2((file+".score").c_str());

  assert(ifs1 && ifs2);

  for (std::string line; std::getline(ifs1, line); ){
    std::vector<std::string> res;

    boost::split(res, line, boost::is_space());

    std::unordered_map<std::string, int>::iterator it = this->nounIndices.find(res[0]);

    if (it != this->nounIndices.end()){
      for (int i = 0; i < this->wordDim; ++i){
	this->nounVector.coeffRef(i, it->second) = atof(res[i+1].c_str());
      }
    }

    it = this->contextIndices.find(res[0]);

    if (it != this->contextIndices.end()){
      for (int i = 0; i < this->wordDim; ++i){
	this->contextVector.coeffRef(i, it->second) = atof(res[i+1].c_str());
      }
    }
  }
  
  for (std::string line; std::getline(ifs2, line); ){
    std::vector<std::string> res;

    boost::split(res, line, boost::is_space());

    std::unordered_map<std::string, int>::iterator it = this->contextIndices.find(res[0]);

    if (it != this->contextIndices.end()){
      for (int i = 0; i < this->wordDim; ++i){
	this->scoreVector.coeffRef(i, it->second) = atof(res[i+1].c_str());
      }
    }
  }
}
Example #9
0
int main(int argc, char* argv[])
{
    std::string     filename1, filename2;

    po::options_description hidden("Hidden options");
    hidden.add_options()
        ("input-file1",  po::value<std::string>(&filename1), "The first collection of persistence diagrams")
        ("input-file2",  po::value<std::string>(&filename2), "The second collection of persistence diagrams");

    po::positional_options_description p;
    p.add("input-file1", 1);
    p.add("input-file2", 2);
    
    po::options_description all; all.add(hidden);

    po::variables_map vm;
    po::store(po::command_line_parser(argc, argv).
                  options(all).positional(p).run(), vm);
    po::notify(vm);

    if (!vm.count("input-file1") || !vm.count("input-file2"))
    { 
        std::cout << "Usage: " << argv[0] << " input-file1 input-file2" << std::endl;
        std::cout << hidden << std::endl; 
        return 1; 
    }

    std::ifstream ifs1(filename1.c_str()), ifs2(filename2.c_str());
    boost::archive::binary_iarchive ia1(ifs1), ia2(ifs2);

    std::map<Dimension, PDgm>       dgms1, dgms2;

    ia1 >> dgms1;
    ia2 >> dgms2;

    std::cout << "Distance between dimension 0: " << bottleneck_distance(dgms1[0], dgms2[0]) << std::endl;
    std::cout << "Distance between dimension 1: " << bottleneck_distance(dgms1[1], dgms2[1]) << std::endl;
    std::cout << "Distance between dimension 2: " << bottleneck_distance(dgms1[2], dgms2[2]) << std::endl;
}
CheckerGame::CheckerGame() : GameBase(8,8) {
	ifstream ifs1(theGame);
	if (!ifs1){
		ofstream ofs(theGame);
		ofs << "NO DATA" << endl;
	}
	ifstream ifs(theGame);
	string data;
	getline(ifs, data);
	if (data == "NO DATA"){
		string display;
		ifstream defaultFile("checker0");
		if (defaultFile){
			GamePiece GameP;
			while (getline(defaultFile, display)){
				istringstream Iss(display);
				for (int i = 0; i < 8; ++i){
					Iss >> GameP.display;
					XorO.push_back(GamePiece(Black, "emptyName", GameP.display));
				}
			}
		}
		else{
			throw noSudokuFile;
void XMLScannerTest::run()
{
		//create a dummy map with a fakie f*****g modulewhateverinfo....
	std::vector<std::pair<std::string, std::string> > outs(1);
	std::vector<std::pair<std::string, std::string> > ins(0);
	std::pair<std::string, std::string> outpair("typ_string", "String");
	outs[0] = outpair;
	
	//Xpm dummy(dummyXpm, strlen(dummyXpm)+1);
	ModuleInfo* mi = new ModuleInfo("mod_stringModule", "String", 
								    ins, outs, true);

	
	std::vector<std::pair<std::string, std::string> > outs2(0);
	std::vector<std::pair<std::string, std::string> > ins2(1);
	std::pair<std::string, std::string> inpair("typ_framebuffer", "Bild");
	ins2[0] = inpair; 
	ModuleInfo* mi2 = new ModuleInfo("mod_glOutputModule", "GLoutput" , 
								    ins, outs, false);

	std::vector<std::pair<std::string, std::string> > outs3(1);
	std::vector<std::pair<std::string, std::string> > ins3(3);
	
	std::pair<std::string, std::string> inpair2("typ_number","Zahl");
	
	ins3[0] = inpair2; 
	ins3[1] = inpair2;
	ins3[2] = inpair;

	outs3[0] = inpair;

	ModuleInfo* mi3 = new ModuleInfo("mod_tunnelModule", "Tunnel" , 
								    ins, outs, false);

	
	std::map<int, ModuleInfo*> mi_map;
	mi_map[0] = mi;
	mi_map[1] = mi2;	
	mi_map[2] = mi3;

	//create storage room for the listener
	std::map<std::string, int> infos;
	std::map<std::string, std::pair<int,int> > nodes;
	std::map<int, std::string>  nodeIDs;
	std::map<std::string, std::pair<int,int> > controls;
	std::map<int, std::string> controlIDs;
	std::map<std::pair<int,int>, std::pair<int,int> > conns;
	std::map<std::pair<int,int>, std::pair<int,int> > ctrlconns;

	//create an xmlListener with that dummyinfo
	XMLTokenListener horcher(mi_map, infos, nodes, nodeIDs, controls, controlIDs, conns, ctrlconns);
	XMLFileScanner gucker(horcher);
	std::ifstream ifs("testCorrect.graph");
	if(ifs==0)
		std::cout<<"File not found \n";
	std::string testTextCorrect;	

	char tmp;
	while(ifs.get(tmp))
	{
		testTextCorrect += tmp;
	}

	gucker.scan(testTextCorrect);


	//eine datei ohne <model>
	//std::cout<<"Processing incorrect file 1...\n";
	std::ifstream ifs1("testInCorrect1.graph");
	if(ifs1==0)
		std::cout<<"File not found \n";
	std::string testTextInCorrect1;	
	while(ifs.get(tmp))
	{
		testTextInCorrect1 += tmp;
	}

	try
	{
		gucker.scan(testTextInCorrect1);
	}
	catch(std::runtime_error err)
	{
		//if(err.what() !=  "This is no Ge-Phex Graph file...go f**k your dog!!!")
		//	throw std::runtime_error(err.what());
		//std::cout<<err.what()<<std::endl;
		
	}


	//eine datei ohne </model>, ja, ich weiss, kreativ...
	//std::cout<<"Processing incorrect file 2...\n";
	std::ifstream ifs2("testInCorrect2.graph");
	if(ifs2==0)
		std::cout<<"File not found \n";
	std::string testTextInCorrect2;	
	while(ifs2.get(tmp))
	{
		testTextInCorrect2 += tmp;
	}

	try
	{
		gucker.scan(testTextInCorrect2);
	}
	catch(std::runtime_error err)
	{
		//if(err.what() !=  "File has a wrong finishing tag...wrong format")
		//	throw std::runtime_error(err.what());
		
		//std::cout<<err.what()<<std::endl;
	}

	//eine datei mit fehlender node section
	//std::cout<<"Processing incorrect file 3...\n";
	std::ifstream ifs3("testInCorrect3.graph");
	if(ifs3==0)
		std::cout<<"File not found \n";
	std::string testTextInCorrect3;	


	while(ifs3.get(tmp))
	{
		testTextInCorrect3 += tmp;
	}
	
	try
	{
		gucker.scan(testTextInCorrect3);	
	}
	catch(std::runtime_error err)
	{
		//if(err.what() !=  "File has wrong format...section nodes")
		//	throw std::runtime_error(err.what());
		
		//std::cout<<err.what()<<std::endl;
	}		
}
Example #12
0
  static bool eval(int argc, char **argv) {
    static const MeCab::Option long_options[] = {
      { "level",  'l',  "0 -1",    "STR",    "set level of evaluations" },
      { "output", 'o',  0,         "FILE",   "set the output file name" },
      { "version",  'v',  0,   0,    "show the version and exit"   },
      { "help",  'h',  0,   0,    "show this help and exit."   },
      { 0, 0, 0, 0 }
    };

    MeCab::Param param;
    param.open(argc, argv, long_options);

    if (!param.open(argc, argv, long_options)) {
      std::cout << param.what() << "\n\n" <<  COPYRIGHT
                << "\ntry '--help' for more information." << std::endl;
      return -1;
    }

    if (!param.help_version()) return 0;

    const std::vector<std::string> &files = param.rest_args();
    if (files.size() < 2) {
      std::cout << "Usage: " <<
          param.program_name() << " output answer" << std::endl;
      return -1;
    }

    std::string output = param.get<std::string>("output");
    if (output.empty()) output = "-";
    MeCab::ostream_wrapper ofs(output.c_str());
    CHECK_DIE(*ofs) << "no such file or directory: " << output;

    const std::string system = files[0];
    const std::string answer = files[1];

    const std::string level_str = param.get<std::string>("level");

    std::ifstream ifs1(files[0].c_str());
    std::ifstream ifs2(files[1].c_str());

    CHECK_DIE(ifs1) << "no such file or directory: " << files[0].c_str();
    CHECK_DIE(ifs2) << "no such file or directory: " << files[0].c_str();
    CHECK_DIE(!level_str.empty()) << "level_str is NULL";

    std::vector<int> level;
    parseLevel(level_str.c_str(), &level);
    CHECK_DIE(level.size()) << "level_str is empty: " << level_str;
    std::vector<size_t> result_tbl(level.size());
    std::fill(result_tbl.begin(), result_tbl.end(), 0);

    size_t prec = 0;
    size_t recall = 0;

    std::vector<std::vector<std::string> > r1;
    std::vector<std::vector<std::string> > r2;

    while (true) {
      if (!read(&ifs1, &r1, level) || !read(&ifs2, &r2, level))
        break;

      size_t i1 = 0;
      size_t i2 = 0;
      size_t p1 = 0;
      size_t p2 = 0;

      while (i1 < r1.size() && i2 < r2.size()) {
        if (p1 == p2) {
          for (size_t i = 0; i < result_tbl.size(); ++i) {
            if (r1[i1][i] == r2[i2][i]) {
              result_tbl[i]++;
            }
          }
          p1 += r1[i1][0].size();
          p2 += r2[i2][0].size();
          ++i1;
          ++i2;
          ++prec;
          ++recall;
        } else if (p1 < p2) {
          p1 += r1[i1][0].size();
          ++i1;
          ++prec;
        } else {
          p2 += r2[i2][0].size();
          ++i2;
          ++recall;
        }
      }

      while (i1 < r1.size()) {
        ++prec;
        ++i1;
      }

      while (i2 < r2.size()) {
        ++recall;
        ++i2;
      }
    }

    *ofs <<  "              precision          recall         F"
         << std::endl;
    for (size_t i = 0; i < result_tbl.size(); ++i) {
      if (level[i] == -1) {
        *ofs << "LEVEL ALL: ";
      } else {
        *ofs << "LEVEL " << level[i] << ":    ";
      }
      printeval(&*ofs, result_tbl[i], prec, recall);
    }

    return true;
  }
Example #13
0
bool Read3DDataTest::ReadAndCompare( 
    const std::string& dcmInputNameEnd, 
    const std::string& vtkFileNameEnd,
    const TYPE& inputType ) const
{
	try
	{
        // Working directory of the test
        const std::string dcmInputName = std::string(CISTIB_TOOLKIT_FOLDER) + dcmInputNameEnd;
        const std::string vtkFileName = std::string(CISTIB_TOOLKIT_FOLDER) + vtkFileNameEnd;

         // Check if the vtk file exists
        std::ifstream ifs2( vtkFileName.c_str() );
        TSM_ASSERT( "The input VTK file does not exist.", !ifs2.fail() );
        if( ifs2.fail() ) return false;
        ifs2.close();

        // read input
        vtkSmartPointer<vtkImageData> vtkDicomImage;
        switch( inputType )
        {
            case FILE:
            {
                // Check if the dicom file exists
                std::ifstream ifs1( dcmInputName.c_str() );
                TSM_ASSERT( "The input DICOM file does not exist.", !ifs1.fail() );
                if( ifs1.fail() ) return false;
                ifs1.close();
                // Read using dcmAPI::ImageUtilities
                vtkDicomImage = dcmAPI::ImageUtilities::ReadVtkImageFromFile< unsigned short, 3 >( 
                    dcmInputName.c_str(), true );
            }
            break;
            
            case FOLDER:
            {
                // Check if the folder exists
                if ( !boost::filesystem::exists( dcmInputName ) ) return false;
                // create list of files
                std::vector< std::string > dcmFileNames;
                boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end
                for( boost::filesystem::directory_iterator itr( dcmInputName );
                    itr != end_itr; ++itr )
                {
                    if( is_regular_file(itr->status()) && itr->leaf() != "DICOMDIR")
                    {
                        dcmFileNames.push_back( dcmInputName + "/" + itr->leaf() );
                    }
                }
                // sort the files alphabetically
                std::sort(dcmFileNames.begin(), dcmFileNames.end());
                // Read using dcmAPI::ImageUtilities
                vtkDicomImage = dcmAPI::ImageUtilities::ReadMultiSliceVtkImageFromFiles< unsigned short, 3 >( 
                    dcmFileNames, true );
           }
            break;
            
            case DICOMDIR:
            {
		        // Data set
		        dcmAPI::DataSet::Pointer dcmData = dcmAPI::DataSet::New();
		        
		        // scan the current working folder for dicom files
		        dcmAPI::DataSetReader::Pointer reader = dcmAPI::DataSetReader::New( );
		        reader->SetDataSet( dcmData );
		        reader->ReadDicomDir( dcmInputName ); 
		        
		        // Patient
			    const dcmAPI::Patient::Pointer patient = dcmData->GetPatient( dcmData->GetPatientIds()->at(0) );
		        // Study
		        const dcmAPI::Study::Pointer study = patient->Study( patient->StudyIds()->at(0) );
		        // Serie
		        const dcmAPI::Series::Pointer series = study->Series( study->SeriesIds()->at(0) );
		        // TimePoint
		        const dcmAPI::TimePoint::Pointer timePoint = series->TimePoint( series->TimePointIds()->at(0) );
		        // Slice
		        const dcmAPI::SliceIdVectorPtr sliceIdVector = timePoint->SliceIds();
		        std::vector< std::string > dcmFileNames;
		        for( unsigned int i=0; i < sliceIdVector->size(); ++i)
		        {
			        const dcmAPI::Slice::Pointer slice = timePoint->Slice(sliceIdVector->at(i));
			        const std::string filePath = slice->GetTagAsText(dcmAPI::tags::SliceFilePath);
			        dcmFileNames.push_back( filePath );
			    }
                // Read using dcmAPI::ImageUtilities
                vtkDicomImage = dcmAPI::ImageUtilities::ReadMultiSliceVtkImageFromFiles< unsigned short, 3 >( 
                    dcmFileNames, true );
            }
            break;
            
            default:
            {
                TS_FAIL("Read3DDataTest::ReadAndCompare failed: unknwown case.");
		        return false;
            }
        }
        
        // Read using BaseLib
        vtkSmartPointer<vtkImageData> vtkImage = blImageUtils::LoadImageFromFileAsVTK( vtkFileName.c_str() );

        // Compare image content
        return blImageUtils::CompareImages( vtkDicomImage, vtkImage, 1e-5 );
	}
	catch(...)
	{
		TS_FAIL("Read3DDataTest::ReadAndCompare failed: thrown exception.");
		return false;
	}
}
Example #14
0
int main(int argc, char ** argv){
  
  // check input
  if(argc < 3){
    std::cout << "Usage: difference <file1.g2o> <file2.g2o>" << std::endl;
    return 0;
  }
  
  init();
  
   // allocate the optimizers
  g2o::SparseOptimizer * optimizer1 = new g2o::SparseOptimizer();
  g2o::SparseOptimizer * optimizer2 = new g2o::SparseOptimizer();
  SlamLinearSolver* linearSolver = new SlamLinearSolver();
  linearSolver->setBlockOrdering(false);
  SlamBlockSolver* blockSolver = new SlamBlockSolver(linearSolver);
  g2o::OptimizationAlgorithmGaussNewton* solver = new g2o::OptimizationAlgorithmGaussNewton(blockSolver);
  
  optimizer1->setAlgorithm(solver);
  optimizer2->setAlgorithm(solver);
  
  // load the graphs
  std::ifstream ifs1(argv[1]);
  std::ifstream ifs2(argv[2]);
  if(!ifs1){
    std::cout << "Cannot open file " << argv[1] << std::endl;
    return 1;
  }
  if(!ifs2){
    std::cout << "Cannot open file " << argv[2] << std::endl;
    return 1;
  }
  if(!optimizer1->load(ifs1)){
    std::cout << "Error loading graph #1" << std::endl;
    return 2;
  }
  if(!optimizer2->load(ifs2)){
    std::cout << "Error loading graph #2" << std::endl;
    return 2;
  }
  std::cout << "graph #1:";
  std::cout << "\tLoaded " << optimizer1->vertices().size() << " vertices" << std::endl;
  std::cout << "\tLoaded " << optimizer1->edges().size() << " edges" << std::endl;
  
  std::cout << "graph #2:";
  std::cout << "\tLoaded " << optimizer1->vertices().size() << " vertices" << std::endl;
  std::cout << "\tLoaded " << optimizer1->edges().size() << " edges" << std::endl;
  
  
  
  g2o::HyperGraph::VertexIDMap map1 = optimizer1->vertices();
  g2o::HyperGraph::VertexIDMap map2 = optimizer2->vertices();
  
  // safety checks
  
  std::cout << "safety checks...";
  if(optimizer1->vertices().size() != optimizer2->vertices().size()){
    std::cout << "!!! the two graphs don't have the same number of vertices !!!" << std::endl;
    return 3;
  }
  
  for(g2o::HyperGraph::VertexIDMap::iterator it=map1.begin(); it!=map1.end(); it++){
    
    g2o::OptimizableGraph::Vertex * v1 = (g2o::OptimizableGraph::Vertex *) it->second;
    
    int dim = v1->minimalEstimateDimension();
    
    if(dim!=3 & dim!=2){
      std::cerr << "Vertex #" << v1->id() << " has strange dimension: " << dim << std::endl;
      return 4;
    }
    
    // get the corresponding vertex in the other graph
    g2o::OptimizableGraph::Vertex * v2 = (g2o::OptimizableGraph::Vertex *) map2[v1->id()];
    assert(v2->id() == v1->id());
    if(v2->minimalEstimateDimension() != dim){
      std::cerr << "ERROR: vertex " << v2->id() << " has different dimension in the two graphs" << std::endl;
      return 5;
    }
  }
  
  std::cout << "done" << std::endl;
  
  std::vector<g2o::OptimizableGraph::Vertex*> vertices;
  
  for(g2o::HyperGraph::VertexIDMap::iterator it=map1.begin(); it!=map1.end(); it++){
    vertices.push_back((g2o::OptimizableGraph::Vertex *)it->second);
  }
  
  std::cout << "vertices vector filled" << std::endl;
  
  bool visited[vertices.size()];
  for(unsigned int i=0; i<vertices.size(); i++){
    visited[i] = false;
  }
  
  thread_struct t_struct;
  t_struct.map1 = &map1;
  t_struct.map2 = &map2;
  t_struct.vertices = &vertices;
  t_struct.visited = visited;
  
  pthread_t threads[_num_threads + 1];
  
  for(unsigned int i=0; i<_num_threads; i++){
    pthread_create(threads+i, NULL, launch_analyze, &t_struct);
  }
  
  visualizer_struct v_struct;
  v_struct.visited = visited;
  v_struct.size = vertices.size();
  
  pthread_create(threads+_num_threads, NULL, launch_visualize, &v_struct);

  std::cout << "threads launched" << std::endl;
  
  for(unsigned int i=0; i<_num_threads+1; i++){
    pthread_join(threads[i], NULL);
  }
  
  std::cout << "minimum error = " << _best_error;
}
Example #15
0
/* ********************************************
 *  reweighting and pmf calculation at room temperature  
 * ********************************************/
int main(int argc, char *argv[]){
// INPUT_PARAMETERS
// argv[1]: input parameter file
  if( argv[1]==NULL ){
    puts("No ARGUMEMTS");
    puts("USAGE: ./a.out (argv[1]: input parameter file)" );
    return 1;
  }
  cout<<"Your input-parameter file: "<<argv[1]<<endl;
  Inp_nishi inp1( argv[1] );

// ############# READ INPUT  ########################################
/* (1) 
 * 
 */
   cout<<endl<<"------- (1) load --------- \n";

   string infile = inp1.read("INFILE"); 
   string inprob = inp1.read("INPROB");  

   cout<<"# output"<<endl;
   string outpmf = inp1.read("OUTPMF");

   cout<<"#  settings"<<endl;
   int frame = atoi( inp1.read("NUMSTRUCTURE").c_str() );


/* DEFINITION OF VARIABLES
*/
   vector<long double> prob2; //probability of each data
   vector<long double> ene_prob, prob; //from inprob (Pc) Probability distribution function along potential energy
   int outlier = 0;  //num of data out of energy range


/*  OPEN FILE  
*/
  //float tmp;
  long double tmp;

  ifstream ifs1(infile.c_str());
  //ifstream ifs1(infile.c_str(),ifstream::in);
  if(ifs1.fail()){
    cerr<<"cannot open file "<<infile<<endl;
    //exit(1);
    return 1;
  }

  vector<float> c1, c2, pote;
  //while(!ifs.eof()){
  //while(ifs.good()){
  for(int ii=0;ii<frame;ii++){
    ifs1 >> tmp;
    c1.push_back(tmp);
    ifs1 >> tmp;
    c2.push_back(tmp);
    ifs1 >> tmp;
    pote.push_back(tmp);
  }

  ifs1.close();

  //cout<<"DEBUG: pote.size() = "<<pote.size()<<endl;
  //cout<<"DEBUG: pote[pote.size() -1] = "<<pote[pote.size() -1]<<endl;

/* (2)  assignment of probability
 *
 * */
// read file 
  ifstream test(inprob.c_str());
  //ifstream test(inprob.c_str(),ifstream::in);
  if(inprob == "NO") goto flag_noprob;  //assign probability
{ // goto flag_noprob 
  if(test.fail()){
    cerr<<"cannot open file "<<inprob<<endl;
    //exit(1);
    return 1;
  }

  //test.clear();
  //test.seekg(2);
  test >> tmp;  //why outside of while-loop? because of ifs.eof 
  //cerr<<"DEBUG: tmp of ene_prob = "<<tmp<<endl;
  //for(int ii=0;ii<2131;ii++){
  //while( true ){
  while( ! test.eof() ){
  //while(test.good()){
  //test >> tmp;
    //if( test.eof() ) break;
    //cerr<<"DEBUG: tmp of ene_prob = "<<tmp<<endl;
    ene_prob.push_back(tmp);
    test >> tmp;
    prob.push_back(tmp);
    test >> tmp;
  }

  test.close();

  //cout<<"DEBUG: ene_prob.size() = "<<ene_prob.size()<<endl;
  cout<<" reading input section end "<<endl;

  //cout<<"DEBUG: prob.size() = "<<prob.size()<<endl;
  //cout<<"DEBUG: prob[prob.size() -1] = "<<prob[prob.size() -1]<<endl;
  //cout<<"DEBUG: ene_prob.size() = "<<ene_prob.size()<<endl;
  //cout<<"DEBUG: ene_prob[ene_prob.size() -1] = "<<ene_prob[prob.size() -1]<<endl;

//ttp_v_mcmd input
   string inttpin = inp1.read("INTTPIN"); //ttp_v_mcmd.inp
   string inttpout = inp1.read("INTTPOUT"); //ttp_v_mcmd.out
   int interval = atoi( inp1.read("INTERVAL").c_str() );

  vector<float> tmpvec;
  ifstream ttpvinp(inttpin.c_str()); //ttp_v_mcmd.inp
  if( ttpvinp.fail() ){
    cerr<<"cannot open file "<<inttpin<<endl;
    return 1;
  }
  while( ttpvinp ){
    string tmpstr;
    ttpvinp >> tmpstr;
    //cout<< tmpstr<<endl;
    if( tmpstr[0] == ';' ){
      ttpvinp.ignore(100, '\n');
    }
    else{
      tmpvec.push_back( atof( tmpstr.c_str() ) );
    }
  }
  ttpvinp.close();
  /*for(unsigned int i;i<tmpvec.size();i++){
    cout<<tmpvec[i]<<endl;
  }*/
  int vst = tmpvec[0];
  int trans = tmpvec[1]; 
  vector<float> ttplimit;
  for(int i=1;i<=vst;i++){
    ttplimit.push_back( tmpvec[4*i-2] );
    ttplimit.push_back( tmpvec[4*i-1] );
  }
  /*for(unsigned int i;i<ttplimit.size();i++){
    cout<<ttplimit[i]<<endl;
  }*/
  tmpvec.clear(); 
    
  vector<int> currvst;
  ifstream ttpvout(inttpout.c_str()); //ttp_v_mcmd.out
  if( ttpvout.fail() ){
    cerr<<"cannot open file "<<inttpout<<endl;
    return 1;
  }
  while( ttpvout ){
    ttpvout >> tmp;
    ttpvout >> tmp;
    //cout<<tmp<<endl;
    currvst.push_back( tmp ); 
  }  
  /*for(unsigned int i;i<currvst.size();i++){
    cout<<currvst[i]<<endl;
  }*/
  ttpvout.close();

//
   cout<<endl<<"------- (2) assignment of probability --------- \n";
   
   int check_flat[ene_prob.size()];
   for(unsigned int i=0;i<ene_prob.size();i++){
      check_flat[i] = 0; //initializing by zero
   }
   //trans/interval
   int iii=0;
   for(int ii=0;ii<frame;ii++){ 
      int flag_1 = 0;
      unsigned int jj = 0;
      int vstnum = currvst[int(ii/20)];
      //cout<<int(ii/20)<<" "<<vstnum<<endl;
      if( pote[ii] < ttplimit[2*vstnum-2] || pote[ii]>=ttplimit[2*vstnum-1] ){
         prob2.push_back( 0 );
         outlier ++ ;
         continue;
      }
      else if( pote[ii] < ene_prob[0] || pote[ii] >= ene_prob[ene_prob.size() - 1]){ 
         prob2.push_back( 0 );
	 outlier ++ ;
	 continue;
      }
      else{
      for(jj=0;jj<ene_prob.size();jj++){
         if( pote[ii] < ene_prob[jj] ){
	    prob2.push_back( prob[jj] );
            if( vstnum == 1 || vstnum == vst ){
              check_flat[jj] ++ ;
            }
	    check_flat[jj] ++ ;
            flag_1 = 1;
	    break;
	 }
      }
      }
            //if(  jj==ene_prob.size() ){
      //if( pote[ii] >= ene_prob[ene_prob.size() - 1]){
            //if( flag_1 == 0 ){
         //cout<<"WARNING: pote["<<ii<<"] = "<<pote[ii]<<endl;
	 //prob2.push_back( prob[ jj - 1 ] );
	 //check_flat[jj - 1 ] ++ ;
      //}
   }
   if( prob2.size() != frame ){
      cout<<"ERROR: assignment of probability failed \n";
      cout<<"num of assigned = "<<prob2.size()<<endl;
      cout<<"num of structures = "<<frame<<endl;
      return 1;
   }
   else{
      cout<<"assignment of probability was ended successfully"<<endl;
      cout<<"num of outliers = "<<outlier<<endl;
   }

  string outcheck = inp1.read("OUTCHECK").c_str() ;
  if( outcheck != "NO" ){
     ofstream ofs2; //check_flat
     //ofs2.open( inp1.read("OUTCHECK").c_str() );
     ofs2.open( outcheck.c_str() );
     for(unsigned int i = 0;i<ene_prob.size();i++){
        ofs2<<ene_prob[i]<<"    "<<check_flat[i]<<"\n";
     }
  ofs2.close();
  cout<<endl<<outcheck<<" was output successfully"<<endl;
  }
} // end of goto flag_noprob 
flag_noprob:
   if(inprob == "NO"){
      for(int ii=0;ii<frame;ii++){
         prob2.push_back(1);
      }
   }
/*  OUTPUT FILE
*/
  ofstream ofs1;
  ofs1.open( inp1.read("OUTPROB").c_str() );
  for(unsigned int i = 0;i<prob2.size();i++){
     ofs1<<prob2[i]<<"\n";
  }
  ofs1.close();


/* (7) PMF calculation
 *
 * */
   cout<<endl<<"REPORT> (7) PMF calculation \n";
   float dcbound1 = atof( inp1.read("DCBOUND1").c_str() );
   float dcbound2 = atof( inp1.read("DCBOUND2").c_str() );

   //string pmfcalculation  = inp1.read("PMFCALCULATION");
   string pmfcalculation  = "YES";
   if( pmfcalculation == "YES" ){

   double length_bin = atof(inp1.read("BINSIZE").c_str());
   float emin = atof(inp1.read("MINCOORD").c_str());
   float temperature = atof(inp1.read("TEMPERATURE").c_str());
   int num_bin = atoi(inp1.read("NUMBIN").c_str());
   
   cout<<"Range: "<<emin<<" to "<<emin+length_bin*num_bin<<endl;
   cout<<"Num of Partitions = NUMBIN*NUMBIN = "<<num_bin*num_bin<<endl;

   //float pmf[num_bin][num_bin];
   double pmf[num_bin][num_bin];
   //long double pmf[num_bin][num_bin];
   for(int i=0;i<num_bin;i++){  //initialize array
      for(int j=0;j<num_bin;j++){
         pmf[j][i] = 0;
      }
   }
   int count_pmf = 0; long double normcons = 0;
   int count_valid = 0;
   for(unsigned int n=0;n<frame;n++){ //count
      int flag_2 = 0;
      for(int i=0;i<num_bin;i++){
         bool flag_3 = false;
         for(int j=0;j<num_bin;j++){
            if(c1[n] >= emin + length_bin * j 
 	    && c1[n] <  emin + length_bin * (j + 1) 
	    && c2[n] >= emin + length_bin * i
	    && c2[n] <  emin + length_bin * (i + 1)     ){
	       //pmf[j][i] ++ ;
	       if( prob2[n] > 0 ){
	          count_valid ++ ;
	       }
	       if( pote[n] < dcbound1 || pote[n] > dcbound2 ){
	         pmf[j][i] = pmf[j][i] + prob2[n]*2 ; //counting by probability
	         normcons = normcons + prob2[n]*2; //normalization constant
	       }
	       else{
	         pmf[j][i] = pmf[j][i] + prob2[n] ; //counting by probability
	         normcons = normcons + prob2[n]; //normalization constant
	       }
	       count_pmf ++ ; //counting 1 by 1
	       //goto NEXT_PMF;
               flag_3 = true;
               flag_2 = 1;
               break;
	    }
         }
         if( flag_3 ) break;
      }
      if( flag_2 == 0 ){
         cout<<"WARNING: structure "<<n<<" was not assigned into any bin of pmf\n";
         cout<<"c1[n] = "<<c1[n]<<", c2[n] = "<<c2[n]<<endl;
      }
   }

   cout<<"Normaliztion constant = "<<normcons<<endl;
   cout<<"The number of data whose probability is larger than zero = "<<count_valid<<endl;

   cout<<"count_pmf / frame = "<<count_pmf<<" / "<<frame<<endl;
   if( count_pmf != (int)frame )cout<<"WARNING: count_pmf != frame; "<<count_pmf<<" != "<<frame<<endl;
   double min_pmf = 999999, max_pmf = -999999; 
   for(int i=0;i<num_bin;i++){ //normalization
      for(int j=0;j<num_bin;j++){
         //pmf[j][i] = pmf[j][i] / frame;
         pmf[j][i] = pmf[j][i] / normcons;
         if( pmf[j][i] <= min_pmf ){
            min_pmf = pmf[j][i];
         }
         if( pmf[j][i] >= max_pmf ){
            max_pmf = pmf[j][i];
         }
      }
   }
   cout<<"Maximum Probability = "<<max_pmf<<endl;
   cout<<"Minimum Probability = "<<min_pmf<<endl;

   //double const_boltz = 1.380658e-23, pmf_temp = 300;
   min_pmf = 999999, max_pmf = -999999; 
   int min_pmf_n[2]; double min_pmf_c[2];
   min_pmf_n[0] = 0; min_pmf_n[1] = 0;
   int max_pmf_n[2]; double max_pmf_c[2];
   max_pmf_n[0] = 0; max_pmf_n[1] = 0;
   for(int i=0;i<num_bin;i++){ //PMF calculation
      for(int j=0;j<num_bin;j++){
         if( pmf[j][i] == 0 ){
	    //pmf[j][i] = 100;  
	    continue;
	 }
         pmf[j][i] = -1 * BOLTZMAN_CONST * temperature * log( pmf[j][i] );
         if( pmf[j][i] < min_pmf ){
            min_pmf = pmf[j][i];
            min_pmf_n[0] = j; min_pmf_n[1] = i;
         }
         if( pmf[j][i] > max_pmf ){
            max_pmf = pmf[j][i];
            max_pmf_n[0] = j; max_pmf_n[1] = i;
            //cout<<"DEBUG> max_pmf = "<<max_pmf<<", max_pmf_n[0], max_pmf_n[1] = "<<max_pmf_n[0]<<", "<<max_pmf_n[1]<<endl;
         }
      }
   }
   /*min_pmf_c[0] = emin + min_pmf_n[0] * length_bin + length_bin / 2;
   min_pmf_c[1] = emin + min_pmf_n[1] * length_bin + length_bin / 2;
   max_pmf_c[0] = emin + max_pmf_n[0] * length_bin + length_bin / 2;
   max_pmf_c[1] = emin + max_pmf_n[1] * length_bin + length_bin / 2;*/
   min_pmf_c[0] = emin + min_pmf_n[0] * length_bin ;
   min_pmf_c[1] = emin + min_pmf_n[1] * length_bin ;
   max_pmf_c[0] = emin + max_pmf_n[0] * length_bin ;
   max_pmf_c[1] = emin + max_pmf_n[1] * length_bin ;
   
   cout<<"Maximum PMF = "<<max_pmf-min_pmf<<" (J/mol) = "<<(max_pmf-min_pmf)/JOULE_CALORIE/1000<<" (kcal/mol)\n";
   cout<<"Minimum PMF = "<<min_pmf-min_pmf<<" (J/mol) = "<<(min_pmf-min_pmf)/JOULE_CALORIE/1000<<" (kcal/mol)\n";
   cout<<"(c1, c2) of Maximum PMF = ("<<max_pmf_c[0]<<", "<<max_pmf_c[1]<<")\n"; 
   cout<<"(c1, c2) of Minimum PMF = ("<<min_pmf_c[0]<<", "<<min_pmf_c[1]<<")\n"; 
   
   FILE *fout;
   
   string outpmf = inp1.read("OUTPMF");
   if((fout = fopen( outpmf.c_str(),"w" )) == NULL ){
      printf("cannot open output file: %s\n", outpmf.c_str() );
      return 1;
   }
   //for R format
   /*for(int i=0;i<num_bin;i++){
     fprintf(fout,"%12.3f  ", emin+ length_bin * i);
   }
   fprintf(fout,"\n");
   for(int i=0;i<num_bin;i++){
     fprintf(fout,"%12.3f  ",emin+ length_bin * i);
     for(int j=0;j<num_bin;j++){
         if( pmf[j][i] == 0L ){
         fprintf(fout,"%12.3f  ", 1000.0 );
         }
         else{
         fprintf(fout,"%12.3f  ", (pmf[j][i] - min_pmf) / JOULE_CALORIE /1000L );
         }
     }
     fprintf(fout,"\n");
   }*/

   //for gnuplot format
   for(int i=0;i<num_bin;i++){
      for(int j=0;j<num_bin;j++){
         if( pmf[j][i] == 0L ){
         fprintf(fout,"%12.3f%12.3f%12.3f \n", emin + length_bin * j , emin + length_bin * i , 1000.0 );
         }
         else{
         fprintf(fout,"%12.3f%12.3f%12.3lf \n", emin + length_bin * j , emin + length_bin * i , (pmf[j][i] - min_pmf) / JOULE_CALORIE /1000L );
         }
      }
      fprintf(fout,"\n");
   }
   fclose( fout );
   cout<<"output "<<outpmf<<endl;
//end:

/*  structure list
*/
   cout<<"\n\nWrite structure-number of minimum PMF bin \n";
   for(unsigned int n=0;n<frame;n++){ //count
            /*if(c1[n] >  min_pmf_c[0] - length_bin / 2 
 	    && c1[n] <= min_pmf_c[0] + length_bin / 2 
	    && c2[n] >  min_pmf_c[1] - length_bin / 2
	    && c2[n] <= min_pmf_c[1] + length_bin / 2    ){*/
            if(c1[n] >  min_pmf_c[0]  
 	    && c1[n] <= min_pmf_c[0] + length_bin 
	    && c2[n] >  min_pmf_c[1] 
	    && c2[n] <= min_pmf_c[1] + length_bin
	    && prob2[n] > 0                       ){
	       cout<<n+1<<"   "<<pote[n]<<"   "<<prob2[n]<<endl;
            }
   }

// END
   }
   cout<<"\n\nit took "<<(float)clock()/CLOCKS_PER_SEC<<" sec of CPU to execute this program"<<endl;
   return 0;
        return 0;
}
Example #16
0
int main(int argc, char** argv)
{
  try{
    //Maybe initialize Mpi
    Dune::MPIHelper& helper = Dune::MPIHelper::instance(argc, argv);
    std::cout << "Hello World! This is dune-iris-opm." << std::endl;
    if(Dune::MPIHelper::isFake)
    {
      std::cout<< "This is a sequential program." << std::endl;
      /*-----------------------------------------------------------------------------*/
      //                            The main program.


      //----------------------------------------------------------------
      //A) Must read necessary input stuff from files...
      //----------------------------------------------------------------
      PMTwoPhaseSimulationData simulationData;
      simulationData.readPMTwoPhaseSimulationData();
     
      //----------------------------------------------------------------
      //B) Must do necessary stuff connected to the dune-grid:
      //----------------------------------------------------------------
      //@HAF: Now tries to structure this code such that it can also work for other types of dune-grids
      //NOTE: DuneGridType is defined in IrisOpmTdefs.h
      //NOTE2: This does NOT work yet...only Sgrid can be used yet!

      //#ifdef SGridToBeUsed
      cout << endl;
      cout << simulationData.td_.NameOfGridType << endl;
      cout << simulationData.td_.NoGridCells_X << endl;
      cout << simulationData.td_.NoGridCells_Y << endl;
//       DuneGridType* DGridPtr;
      //if (simulationData.td_.NameOfGridType == "SGrid2D")
      //{
	const int dim=2;                               
	Dune::FieldVector<int,dim> N(2);
	//Puts the correct number of grid-blocks in each direction:              
	N[0] = simulationData.td_.NoGridCells_X; //@HAF: OK???
	N[1] = simulationData.td_.NoGridCells_Y; //@HAF: OK???
	//The geometrical size of the domain:
	Dune::FieldVector<DuneGridType::ctype,dim> L(0.0);
	Dune::FieldVector<DuneGridType::ctype,dim> H(1.0); 
	H[0] = simulationData.td_.X_Extent; //@HAF: OK???
	H[1] = simulationData.td_.Y_Extent; //@HAF: OK???
	//Creates the SGrid:
	DuneGridType Dgrid(N,L,H);
	//DGridPtr = &Dgrid;

	//}
      //#endif //SGridToBeUsed
#ifdef AluGridToBeUsed
      if (simulationData.td_.NameOfGridType == "ALUGridSimplex2D")
      {
	Opm::GridFactory<DuneGridType> factory();
	//Must fill in the vertices and elements from Triangle:
	//insertVertices( factory, "A.1.node");	
	//insertSimplices( factory, "A.1.ele");
	//Vertices:
	Dune::FieldVector<double,2> pos;
	double x,y,dummy;
	int AnzKnoten;

	std::ifstream ifs("A.1.node");	
	
	if (ifs.is_open()) {
	  ifs >> AnzKnoten >> dummy >> dummy >> dummy;
	  for (int i = 0; i < AnzKnoten; i++) {
	    ifs >> dummy >> x >> y >> dummy >> dummy;
	    pos[0] = x; pos[1] = y;
	    factory.insertVertex(pos);
	  } 
	  ifs.close();
	}
	else
	  std::cout << "Error: Can not open file\n";

	//Elements:
	unsigned int numberOfSimplices, corner1, corner2, corner3, dummy1;
	const Dune::GeometryType type( Dune::GeometryType::simplex, 2);
	std::vector< unsigned int > cornerIDs( 3 );

	std::ifstream ifs1("A.1.ele");

	if (ifs1.is_open()) {
	  ifs1 >> numberOfSimplices >> dummy1 >> dummy1;    
	  for (unsigned int i = 0; i < numberOfSimplices; i++) {
	    ifs1 >> dummy1 >> corner1 >> corner2 >> corner3;
	    cornerIDs[0] = corner1 - 1;
	    cornerIDs[1] = corner2 - 1;
	    cornerIDs[2] = corner3 - 1;
	    factory.insertElement(type, cornerIDs);      
	  }  
	  ifs1.close();
	}
Example #17
0
int main() {
  ColoredGraph<GraphVertex,TriColor> gr;
  set<GraphVertex,less<GraphVertex> > groupsall, filesall,functionsall;
  set<GraphVertex,less<GraphVertex> > groupssome, filessome,functionssome,S;
  set<GraphVertex,less<GraphVertex> > groupsnot, filesnot,functionsnot;
  ifstream ifs1("groups.txt");
  ifstream ifs2("files.txt");
  ifstream ifs3("files.txt");
  ifstream ifs4("choices.txt");
  cerr << "reading groups";
  readDoubleColumnGraph(ifs1,groupsall,gr,true);
  cerr << ", files";
  readDoubleColumnGraph(ifs2,filesall,gr,true);
  cerr << ", functions\n";
  readDoubleColumnGraph(ifs3,functionsall,gr,false);
  readSingleColumn(ifs4,gr);
#if 1
  ifstream ifs5("depends.txt");
  list<list<string> > dbllist;
  readMultiColumns(ifs5,dbllist);
#endif
  bool todo  = true;
  while(todo) {
    todo = false;
    gr.ColorChildComponents(TriColor::s_one,TriColor::s_two);
    list<GraphVertex> L(gr.getColored(TriColor::s_two));
    copy(L.begin(),L.end(),inserter(S,S.begin()));
#if 1
    todo = addElements(gr,TriColor::s_one,S,dbllist);
    cerr << "addelements give " << todo << '\n';
#endif
  };
  cerr << "Here is the set after the loop:\n";
  printset(cerr,S,",");
  set_intersection(S.begin(),S.end(),groupsall.begin(),groupsall.end(),
                   inserter(groupssome,groupssome.begin()));
  set_intersection(S.begin(),S.end(),filesall.begin(),filesall.end(),
                   inserter(filessome,filessome.begin()));
  set_intersection(functionsall.begin(),functionsall.end(),S.begin(),S.end(),
                   inserter(functionssome,functionssome.begin()));
  set_difference(groupsall.begin(),groupsall.end(),S.begin(),S.end(),
                   inserter(groupsnot,groupsnot.begin()));
  set_difference(filesall.begin(),filesall.end(),S.begin(),S.end(),
                   inserter(filesnot,filesnot.begin()));
  set_difference(functionsall.begin(),functionsall.end(),S.begin(),S.end(),
                   inserter(functionsnot,functionsnot.begin()));
  cerr << "all groups:\n";
  printset(cerr,groupsall,", ");
  cerr << "\nall files:\n";
  printset(cerr,filesall,", ");
  cerr << "\nall functions:\n";
  printset(cerr,functionsall,", ");
  cerr << "\n\n\n";
  cerr << "groups (not):\n";
  printset(cerr,groupsnot,", ");
  cerr << "\nfiles (not):\n";
  printset(cerr,filesnot,", ");
  cerr << "\nfunctions(not):\n";
  printset(cerr,functionsnot,", ");
  cerr << "\n\n\n";
  cerr << "groups:\n";
  printset(cerr,groupssome,", ");
  cerr << "\nfiles:\n";
  printset(cerr,filessome,", ");
  cerr << "\nfunctions:\n";
  printset(cerr,functionssome,", ");

  cerr << "Staring creation of the file Makefile.mark\n";
  ofstream ofs("Makefile.mark");
  ofs << "p9clist = ";
  printset(ofs,filessome,".o \\\n",".o \n");
  ofs.close();
  cerr << "Ended creation of the file Makefile.mark\n";

  cerr << "Staring creation of the file Makefile.cp\n";
  ofstream ofs2("Makefile.cp");
  ofs2 << "cp ";
  printset(ofs2,filessome,".[hc]pp copyplace/ \n cp ",".[hc]pp copyplace/ \n");
  ofs2.close();
  cerr << "Ended creation of the file Makefile.cp\n";
};
int
test_main(int /* argc */, char * /* argv */[]) {
    std::locale old_loc;
    std::locale * utf8_locale
        = boost::archive::add_facet(
              old_loc,
              new boost::archive::detail::utf8_codecvt_facet
          );

    typedef char utf8_t;
    typedef test_data<sizeof(wchar_t)> td;

    // Send our test UTF-8 data to file
    {
        std::ofstream ofs;
        ofs.open("test.dat", std::ios::binary);
        std::copy(
            td::utf8_encoding,
#if ! defined(__BORLANDC__)
            // borland 5.60 complains about this
            td::utf8_encoding + sizeof(td::utf8_encoding) / sizeof(unsigned char),
#else
            // so use this instead
            td::utf8_encoding + 12,
#endif
            boost::archive::iterators::ostream_iterator<utf8_t>(ofs)
        );
    }

    // Read the test data back in, converting to UCS-4 on the way in
    std::vector<wchar_t> from_file;
    {
        std::wifstream ifs;
        ifs.imbue(*utf8_locale);
        ifs.open("test.dat");

        wchar_t item = 0;
        // note can't use normal vector from iterator constructor because
        // dinkumware doesn't have it.
        for(;;) {
            item = ifs.get();
            if(item == WEOF)
                break;
            //ifs >> item;
            //if(ifs.eof())
            //    break;
            from_file.push_back(item);
        }
    }

    // compare the data read back in with the orginal
#if ! defined(__BORLANDC__)
    // borland 5.60 complains about this
    BOOST_CHECK(from_file.size() == sizeof(td::wchar_encoding)/sizeof(wchar_t));
#else
    // so use this instead
    BOOST_CHECK(from_file.size() == 6);
#endif

    BOOST_CHECK(std::equal(from_file.begin(), from_file.end(), td::wchar_encoding));

    // Send the UCS4_data back out, converting to UTF-8
    {
        std::wofstream ofs;
        ofs.imbue(*utf8_locale);
        ofs.open("test2.dat");
        std::copy(
            from_file.begin(),
            from_file.end(),
            boost::archive::iterators::ostream_iterator<wchar_t>(ofs)
        );
    }

    // Make sure that both files are the same
    {
        typedef boost::archive::iterators::istream_iterator<utf8_t> is_iter;
        is_iter end_iter;

        std::ifstream ifs1("test.dat");
        is_iter it1(ifs1);
        std::vector<utf8_t> data1;
        std::copy(it1, end_iter, std::back_inserter(data1));

        std::ifstream ifs2("test2.dat");
        is_iter it2(ifs2);
        std::vector<utf8_t> data2;
        std::copy(it2, end_iter, std::back_inserter(data2));

        BOOST_CHECK(data1 == data2);
    }

    // some libraries have trouble that only shows up with longer strings

    wchar_t * test3_data = L"\
    <?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>\
    <!DOCTYPE boost_serialization>\
    <boost_serialization signature=\"serialization::archive\" version=\"3\">\
    <a class_id=\"0\" tracking_level=\"0\">\
        <b>1</b>\
        <f>96953204</f>\
        <g>177129195</g>\
        <l>1</l>\
        <m>5627</m>\
        <n>23010</n>\
        <o>7419</o>\
        <p>16212</p>\
        <q>4086</q>\
        <r>2749</r>\
        <c>-33</c>\
        <s>124</s>\
        <t>28</t>\
        <u>32225</u>\
        <v>17543</v>\
        <w>0.84431422</w>\
        <x>1.0170664757130923</x>\
        <y>tjbx</y>\
        <z>cuwjentqpkejp</z>\
    </a>\
    </boost_serialization>\
    ";

    // Send the UCS4_data back out, converting to UTF-8
    std::size_t l = std::wcslen(test3_data);
    {
        std::wofstream ofs;
        ofs.imbue(*utf8_locale);
        ofs.open("test3.dat");
        std::copy(
            test3_data,
            test3_data + l,
            boost::archive::iterators::ostream_iterator<wchar_t>(ofs)
        );
    }

    // Make sure that both files are the same
    {
        std::wifstream ifs;
        ifs.imbue(*utf8_locale);
        ifs.open("test3.dat");
        BOOST_CHECK(
            std::equal(
                test3_data,
                test3_data + l,
                boost::archive::iterators::istream_iterator<wchar_t>(ifs)
            )
        );
    }

    delete utf8_locale;
    return EXIT_SUCCESS;
}