Ejemplo n.º 1
0
/*
 * Parse the given binary file and fill the simulator data classes accordingly
 */
int parseInput(Memory& memory, bool DEBUG){
    char byte;
    uint32_t index = 0;
    int ret = 0;
    char header[4] = {0};
    std::ifstream infile("input", std::ios::binary);
    uint16_t code_sz = 0;
    uint16_t cdata = 0;
    uint16_t cdata_sz = 0;
    uint16_t smc = 0;
    uint16_t data = 0;
    uint16_t data_sz = 0;
    uint16_t mem = 0;
    uint16_t dbg_sz = 0;


    // reading the filetype=header string
    while (index < 4){
        if (infile.get(byte)){
            header[index] = byte;
            index++;
        }
        else{
            break;
        }
    }
    if ((header[0] != 'T') || (header[1] != 'o') || (header[2] != 'y') || (header[3] != '1') || (index != 4)){
        std::cout << "Wrong input file format =" << header << std::endl;
        infile.close();
        return 1;
    }

    // read 8 control fields 2 bytes each
    ret += readParam(infile, code_sz);
    ret += readParam(infile, cdata);
    ret += readParam(infile, cdata_sz);
    ret += readParam(infile, smc);
    ret += readParam(infile, data);
    ret += readParam(infile, data_sz);
    ret += readParam(infile, mem);
    ret += readParam(infile, dbg_sz);
    if (ret != 0){
        infile.close();
        std::cout << "Control section cannot be read" << std::endl;
        return 1;
    }

    // look what we've read so far
    if (DEBUG){
        std::cout << " header   = "   << header << std::endl
                  << " code_sz  = "   << std::dec << code_sz  << std::endl
                  << " cdata    = 0x" << std::hex << cdata    << std::endl
                  << " cdata_sz = "   << std::dec << cdata_sz << std::endl
                  << " smc      = 0x" << std::hex << smc      << std::endl
                  << " data     = 0x" << std::hex << data     << std::endl
                  << " data_sz  = "   << std::dec << data_sz  << std::endl
                  << " mem      = 0x" << std::hex << mem      << std::endl
                  << " dbg_sz   = "   << std::dec << dbg_sz   << std::endl;
    }

    // sanity and parameters pre-requirements check

    // non-zero code section, shall 4-bytes aligned
    if (code_sz == 0){
        std::cout << "code_sz cannot be zero" << std::endl;
        infile.close();
        return 1;
    }
    if (code_sz % 4){
        std::cout << "code_sz shall be 4-bytes aligned" << std::endl;
        infile.close();
        return 1;
    }

    // couple of extra flags, showing that the section shall be created (non-zero)
    bool cdata_nz = cdata != 0;
    bool smc_nz = smc != 0;
    bool data_nz = data != 0;
    bool mem_nz = mem != 0;

    // sanity check
    if (!cdata_nz && cdata_sz != 0){
        std::cout << "cdata_sz cannot be non-zero for cdata = 0" << std::endl;
        infile.close();
        return 1;
    }
    if (!data_nz && data_sz != 0){
        std::cout << "data_sz cannot be non-zero for data = 0" << std::endl;
        infile.close();
        return 1;
    }

    // check for monotonous section address raise
    if (smc_nz){
        if (smc <= cdata){
            std::cout << "smc must be > cdata" << std::endl;
            infile.close();
            return 1;
        }
    }
    if (data_nz){
        if (data <= smc){
            std::cout << "data must be > smc" << std::endl;
            infile.close();
            return 1;
        }
        if (data <= cdata){
            std::cout << "data must be > cdata" << std::endl;
            infile.close();
            return 1;
        }
    }
    if (mem_nz){
        if (mem <= data){
            std::cout << "mem must be > data" << std::endl;
            infile.close();
            return 1;
        }
        if (mem <= smc){
            std::cout << "mem must be > smc" << std::endl;
            infile.close();
            return 1;
        }
        if (mem <= cdata){
            std::cout << "mem must be > cdata" << std::endl;
            infile.close();
            return 1;
        }
    }

    // check section sizes and their representaions in the file
    uint16_t section_data_size = 0;
    uint16_t section_code_size = 0;
    uint16_t section_cdata_size = 0;
    
    section_data_size = mem_nz ? mem - data : 0xf000 - data;
    section_cdata_size = smc_nz ? smc - cdata : data_nz ? data - cdata : mem_nz ? mem - cdata : 0xf000 - cdata;
    section_code_size = cdata_nz ? cdata - 4 : smc_nz ? smc - 4 : data_nz ? data - 4 : mem_nz ? mem - 4 : 0xeffc;

    if (section_data_size < data_sz){
        std::cout << "data_sz is more than the actual section size = " << section_data_size << std::endl;
        infile.close();
        return 1;
    }

    if (section_code_size < code_sz){
        std::cout << "code_sz is more than the actual code size = " << section_code_size << std::endl;
        infile.close();
        return 1;
    }

    if (section_cdata_size < cdata_sz){
        std::cout << "cdata_sz is more than the actual section size = " << section_cdata_size << std::endl;
        infile.close();
        return 1;
    }



    // as we've got to this point, everyting shall be correct
    // create described memory regions and add them to the memory map
    ret = 0;
    uint16_t border_hi = 0xffff;
    MemoryRange* range;

    // I/O section
    range = new MemoryRange(0xf000, border_hi, 8, "i/o");
    ret += memory.registerMemoryRange(range);
    border_hi = 0xefff;

    // heap section
    if (mem_nz){
        range = new MemoryRange(mem, 0xefff, 6, "heap");
        ret += memory.registerMemoryRange(range);
        border_hi = mem - 1;
    }

    // data section
    if (data_nz){
        range = new MemoryRange(data, border_hi, 6, "data");
        ret += memory.registerMemoryRange(range);
        border_hi = data - 1;
    }

    // aux code section
    if (smc_nz){
        range = new MemoryRange(smc, border_hi, 7, "smc");
        ret += memory.registerMemoryRange(range);
        border_hi = smc - 1;
    }

    // constant data section
    if (cdata_nz){
        range = new MemoryRange(cdata, border_hi, 4, "cdata");
        ret += memory.registerMemoryRange(range);
        border_hi = cdata - 1;
    }

    // code section
    range = new MemoryRange(4, border_hi, 5, "code");
    ret += memory.registerMemoryRange(range);
    border_hi = 3;

    // reserved first segment
    range = new MemoryRange(0, border_hi, 0, "reserved");
    ret += memory.registerMemoryRange(range);

    if (ret){
        std::cout << "There were errors while registering memory regions" << std::endl;
        infile.close();
        return 1;
    }


    // fill the memory with pre-defined data from the file
    ret = 0;

    // code section
    ret = loadMemoryRange(infile, memory, "code", code_sz);
    if (ret){
        if (ret == 2) std::cout << "Insufficient data in the file, code section" << std::endl;
        else          std::cout << "Cannot locate previously registered memory range 'code'" << std::endl;
        infile.close();
        return 1;
    }
    // cdata section
    if (cdata_nz)
        ret = loadMemoryRange(infile, memory, "cdata", cdata_sz);
    else
        ret = 0;
    if (ret){
        if (ret == 2) std::cout << "Insufficient data in the file, cdata section" << std::endl;
        else          std::cout << "Cannot locate previously registered memory range 'cdata'" << std::endl;
        infile.close();
        return 1;
    }
    // data section
    if (data_nz)
        ret = loadMemoryRange(infile, memory, "data", data_sz);
    else
        ret = 0;
    if (ret){
        if (ret == 2) std::cout << "Insufficient data in the file, data section" << std::endl;
        else          std::cout << "Cannot locate previously registered memory range 'data'" << std::endl;
        infile.close();
        return 1;
    }
    // dbg section
    index = 0;
    while (index < dbg_sz){
        if (infile.get(byte)) index++;
        else                  break;
    }
    if (dbg_sz != index){
        std::cout << "Insufficient data in the file, dbg section" << std::endl;
        infile.close();
        return 1;
    }

    if (infile.get(byte)){
        std::cout << "Excessive data in the file" << std::endl;
        infile.close();
        return 1;
    }

    infile.close();
    return 0;    
}
void Buyer::Buyticket()
{
    Time time;
    int tag,selln;
    string line,type,dep_station,arr_station,temp,schedule;
    if(!time.Time_check())
    {
        cout<<"Today's train schedules are not updated!"<<endl;
        return;
    }

    chdir(time.Show_file_curdir());
    ifstream file_index("index.txt");

    cout<<"which station start:";cin>>dep_station;
    cout<<"which station arrive:";cin>>arr_station;
    cout<<endl;

    while(getline(file_index,line))
    {
        if(line.find("[dep_station] " + dep_station) != -1)
        {
            getline(file_index,line);
            if(line.find("[arr_station] " + arr_station) != -1)
            {
                getline(file_index,line);
                schedule = line;
                line = line + ".txt";
                ifstream file_train(line);
                while(getline(file_train,line))
                    cout<<line<<endl;
                file_train.close();

                cout<<endl;
                cout<<"Noseat   => 1"<<endl;
                cout<<"Hardseat => 2"<<endl;
                cout<<"Hardbed  => 3"<<endl;
                cout<<"Softbed  => 4"<<endl;
                cout<<endl;
                cout<<"Buy what kind of ticket:"<<endl;
                cout<<"Please enter the number behind the type:";cin>>tag;

                chdir("..\\..");
                ifstream file_check(File_user());
                while(getline(file_check,line))
                {
                    if(line.find("[dep_station] " + dep_station) != -1)
                    {
                        getline(file_check,line);
                        if(line.find("[arr_station] " + arr_station) != -1)
                        {
                            cout<<"repeat!"<<endl;
                            return;
                        }
                    }
                }

                switch(tag)
                {
                    case 1 : type = "noseat"; break;
                    case 2 : type = "hardseat"; break;
                    case 3 : type = "hardbed"; break;
                    case 4 : type = "softbed"; break;
                    default: cout<<"No such select !"<<endl; return;
                }
                ofstream file_user(File_user(), ios::out | ios::app);
                file_user<<endl;
                file_user<<"[schedule] "<<schedule<<endl;
                file_user<<"[date] "<<time.Show_cur()<<endl;
                file_user<<"[dep_station] "<<dep_station<<endl;
                file_user<<"[arr_station] "<<arr_station<<endl;
                file_user<<"[ticket_tag] "<<type<<endl;

                file_user.close();

                chdir(time.Show_file_curdir());
                ifstream infile(schedule + ".txt");
                ofstream outfile("temp.txt");
                while(getline(infile,line))
                {
                    if(line.find(type + "_selln") != -1)
                    {
                        stringstream str(line);
                        while(str >> temp)
                            selln = atoi(temp.c_str());
                        ++selln;
                        outfile<<"["<<type<<"_selln] "<<selln<<endl;
                    }
                    else outfile<<line<<endl;
                }
Ejemplo n.º 3
0
// opens file and reads the first 100 relevant characters
// newline, cr, spaces and tabs will be ignored
// return true if everything is ok
const bool GameField::readContest(const std::string& filename)
{
    bool ok = false;

    if ( !filename.empty() )
    {
        // open file for writing
        std::ifstream infile( filename.c_str() );
        char c = 0;
        unsigned int i = 0;
        unsigned int j = 0;
        
        if ( infile.good() )
        {
            while ( infile.good() && ( j < FIELD_EXTRA_HEIGHT ) )
            {
                if ( i >= FIELD_WIDTH )
                {
                    i = 0;
                    j++;
                }
                
                // read character
                infile.get(c);
                // std::cout << c;
                
                switch ( (Tile::TileType)c )
                {
                    case Tile::TILE_RED:
                    case Tile::TILE_GREEN:
                    case Tile::TILE_YELLOW:
                    case Tile::TILE_SHIELD:
                    case Tile::TILE_LILAC:
                    case Tile::TILE_BOMB_1:
                    case Tile::TILE_BOMB_2:
                    case Tile::TILE_BOMB_3:
                    case Tile::TILE_BOMB_4:
                    case Tile::TILE_BOMB_5:
                        // store tile
                        m_field[i][FIELD_EXTRA_HEIGHT-j-1].set((Tile::TileType)c);
                        i++;
                        break;
                    default:
                      // ignore everything else
                      break;
                }
            }
            
            // check if whole field was loaded
            if ( ( 0 != i ) || ( FIELD_EXTRA_HEIGHT != j ) )
            {
                std::cout << "GameField::readContest() error: game field from file "
                          << filename << " was not loaded completely "
                          << i << " " << j << std::endl;
            }
            else
            {
                ok = true;
                std::cout << "GameField::readContest() info: game field "
                          << filename << " loaded completely "
                          << std::endl;
            }

            // close file
            infile.close();
        }
        else
        {
            std::cout << "GameField::readContest() error: file "
                      << filename << " could not be opened" << std::endl;
        }
    }
    else
    {
        std::cout << "GameField::readContest() error: string is empty" << std::endl;
    }

    return ok;
}
Ejemplo n.º 4
0
bool AIDeerBehavior::SetValuesFromFile()
{
	float numberFromFile = 0;
	bool valuesRetrieved = false;
	char characters[16];

	std::ifstream infile("deerVariables.txt");
	if(infile.good())
	{

		//fear interval
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zFearInterval = numberFromFile;

		//minimum distance
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atoi(characters);
		this->zMinimumDistance = (int)numberFromFile;

		//field of view
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zFieldOfView = numberFromFile;

		//Threat movement speed threshold
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zThreatMovementSpeedThreshold = numberFromFile;

		//Confidence koef
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zConfidenceKoef = numberFromFile;

		//Distance too close for comfort
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zTooCloseInDistance = numberFromFile;

		//extra fear with more players
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zExtraFearWithNumberOfPlayers = numberFromFile;

		//extra fear with something too close
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zExtraFearWithCloseProximity = numberFromFile;

		//extra fear when seeing threat
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zExtraFearAtSight = numberFromFile;

		//extra fear when threat moves too quickly
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zExtraFearAtThreatMovementSpeed = numberFromFile;

		//amount of fear decrease
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zFearDecrease = numberFromFile;

		//fear when hurt
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zFearAtDamageDone = numberFromFile;

		//fear level between suspicious and aggressive.
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zSupspiciousToAggressiveThreshold = numberFromFile;

		//fear level between aggressive and afraid
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zAggressiveToAfraidThreshold = numberFromFile;

		//distance to walk when calm
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zDistanceToWalkWhenCalm = (int)numberFromFile;

		//distance to walk when suspicious
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zDistanceToWalkWhenSuspicious = (int)numberFromFile;

		//factor to use when chosing a new target
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zNewTargetCloseByAFactorOf = (int)numberFromFile;

		//flee distance
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zFleeDistance = (int)numberFromFile;

		//How afraid to be when a large sound even happens
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zLargeSoundEventFearIncrease = (int)numberFromFile;

		//The range of the pausing time when calm.
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zCalmRandomInterval = (int)numberFromFile;

		//The minimum value 
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zCalmRandomAddition = (int)numberFromFile;

		//the range of the pausing time when suspicious.
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zSupsiciousRandomInterval = (int)numberFromFile;

		//the minimum value
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zSupsiciousAddition = (int)numberFromFile;

		//the walking velocity
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zWalkingVelocity = numberFromFile;

		//the velocity when attacking
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zAttackingVelocity = numberFromFile;
		
		//the fleeing velocity
		infile.getline(characters, 256,' ');
		infile.ignore(256, '\n');
		numberFromFile = (float)atof(characters);
		this->zFleeingVelocity = numberFromFile;

		valuesRetrieved = true;
	}

	if(infile.is_open())
	{
		infile.close();
	}

	return valuesRetrieved;

}
Ejemplo n.º 5
0
int main(int argc, char** argv){

  //initialize libMesh
  LibMeshInit init(argc, argv);
  
  //parameters
  GetPot infile("fem_system_params.in");
  const bool transient                  = infile("transient", true);
  const Real deltat                     = infile("deltat", 0.005);
  unsigned int n_timesteps              = infile("n_timesteps", 20);
  const int nx                          = infile("nx",100);
  const int ny                          = infile("ny",100);
  const int nz                          = infile("nz",100);
  //const unsigned int dim                = 3;
  const unsigned int max_r_steps        = infile("max_r_steps", 3);
  const unsigned int max_r_level        = infile("max_r_level", 3);
  const Real refine_percentage          = infile("refine_percentage", 0.1);
  const Real coarsen_percentage         = infile("coarsen_percentage", 0.0);
  const std::string indicator_type      = infile("indicator_type", "kelly");
  const bool write_error                = infile("write_error",false);
  const bool flag_by_elem_frac          = infile("flag_by_elem_frac",true);
  
  const bool printJ                     = infile("print_jac",false); //DEBUG
      
#ifdef LIBMESH_HAVE_EXODUS_API
  const unsigned int write_interval    = infile("write_interval", 5);
#endif

  // Create a mesh, with dimension to be overridden later, distributed
  // across the default MPI communicator.
  Mesh mesh(init.comm());
  
  //create mesh
  unsigned int dim;
  if(nz == 0){ //to check if oscillations happen in 2D as well...
    dim = 2;
    MeshTools::Generation::build_square(mesh, nx, ny, 497150.0, 501750.0, 537350.0, 540650.0, QUAD9);
  }else{
    dim = 3;
    MeshTools::Generation::build_cube(mesh, 
                                      nx, ny, nz, 
                                      497150.0, 501750.0, 
                                      537350.0, 540650.0, 
                                      0.0, 100.0, 
                                      HEX27);
    //MeshTools::Generation::build_cube (mesh, 
    //                                      15, 3, 3,
    //                                     -0.0, 5.0,
    //                                    -0.0, 1.0,
    //                                     -0.0, 1.0,
    //                                    HEX27); //DEBUG
  }
  
  // Print information about the mesh to the screen.
  mesh.print_info();
  
  // Create an equation systems object.
  EquationSystems equation_systems (mesh);
  
  //name system
  ContamTransSysInv & system = 
    equation_systems.add_system<ContamTransSysInv>("ContamTransInv");
    
  //solve as steady or transient
  if(transient){
    //system.time_solver = AutoPtr<TimeSolver>(new EulerSolver(system)); //backward Euler
    system.time_solver = AutoPtr<TimeSolver>(new SteadySolver(system));
    std::cout << "\n\nAaahhh transience not yet available!\n" << std::endl;
    n_timesteps = 1;
  }
  else{
    system.time_solver = AutoPtr<TimeSolver>(new SteadySolver(system));
    libmesh_assert_equal_to (n_timesteps, 1); //this doesn't seem to work?
  }
  
  // Initialize the system
  equation_systems.init ();
  
  //initial conditions
  read_initial_parameters();
  system.project_solution(initial_value, initial_grad,
                          equation_systems.parameters);
  finish_initialization();

  // Set the time stepping options...
  system.deltat = deltat;
  
  //...and the nonlinear solver options...
  NewtonSolver *solver = new NewtonSolver(system); 
  system.time_solver->diff_solver() = AutoPtr<DiffSolver>(solver); 
  solver->quiet = infile("solver_quiet", true);
  solver->verbose = !solver->quiet;
  solver->max_nonlinear_iterations =
    infile("max_nonlinear_iterations", 15);
  solver->relative_step_tolerance =
    infile("relative_step_tolerance", 1.e-3);
  solver->relative_residual_tolerance =
    infile("relative_residual_tolerance", 0.0);
  solver->absolute_residual_tolerance =
    infile("absolute_residual_tolerance", 0.0);

  // And the linear solver options
  solver->max_linear_iterations           = infile("max_linear_iterations", 10000);
  solver->initial_linear_tolerance        = infile("initial_linear_tolerance",1.e-13);
  solver->minimum_linear_tolerance        = infile("minimum_linear_tolerance",1.e-13);
  solver->linear_tolerance_multiplier     = infile("linear_tolerance_multiplier",1.e-3);
    
  // Mesh Refinement object - to test effect of constant refined mesh (not refined at every timestep)
  MeshRefinement mesh_refinement(mesh);
  mesh_refinement.refine_fraction() = refine_percentage;
  mesh_refinement.coarsen_fraction() = coarsen_percentage;
  mesh_refinement.max_h_level() = max_r_level;
  
#ifdef LIBMESH_HAVE_GMV
  GMVIO(equation_systems.get_mesh()).write_equation_systems(std::string("invLF.gmv"), equation_systems); //DEBUG
#endif

  // Print information about the system to the screen.
  equation_systems.print_info();
  
  ExodusII_IO exodusIO = ExodusII_IO(mesh); //for writing multiple timesteps to one file
  
  for (unsigned int r_step=0; r_step<max_r_steps; r_step++)
    {
      std::cout << "\nBeginning Solve " << r_step+1 << std::endl;
      
      for (unsigned int t_step=0; t_step != n_timesteps; ++t_step)
        {
      
          std::cout << "\n\nSolving time step " << t_step << ", time = "
                    << system.time << std::endl;
          
          system.solve();
          system.postprocess();
          
          // Advance to the next timestep in a transient problem
          system.time_solver->advance_timestep();
   
      } //end stepping through time loop
      
      std::cout << "\n  Refining the mesh..." << std::endl;
      
      // The \p ErrorVector is a particular \p StatisticsVector
      // for computing error information on a finite element mesh.
      ErrorVector error;
      
      if (indicator_type == "patch")
        {
          // The patch recovery estimator should give a
          // good estimate of the solution interpolation
          // error.
          PatchRecoveryErrorEstimator error_estimator;
          error_estimator.set_patch_reuse(false); //anisotropy trips up reuse
          error_estimator.estimate_error (system, error);
        }
      else if (indicator_type == "kelly")
        {

          // The Kelly error estimator is based on
          // an error bound for the Poisson problem
          // on linear elements, but is useful for
          // driving adaptive refinement in many problems
          KellyErrorEstimator error_estimator;

          error_estimator.estimate_error (system, error);
        }
      
      // Write out the error distribution
      if(write_error){
        std::ostringstream ss;
        ss << r_step;
#ifdef LIBMESH_HAVE_EXODUS_API
        std::string error_output = "error_"+ss.str()+".e";
#else
        std::string error_output = "error_"+ss.str()+".gmv";
#endif
        error.plot_error( error_output, mesh );
      }
      
      // This takes the error in \p error and decides which elements
      // will be coarsened or refined. 
      if(flag_by_elem_frac)
        mesh_refinement.flag_elements_by_elem_fraction(error);
      else
        mesh_refinement.flag_elements_by_error_fraction (error);
      
      // This call actually refines and coarsens the flagged
      // elements.
      mesh_refinement.refine_and_coarsen_elements();
      
      // This call reinitializes the \p EquationSystems object for
      // the newly refined mesh.  One of the steps in the
      // reinitialization is projecting the \p solution,
      // \p old_solution, etc... vectors from the old mesh to
      // the current one.
      equation_systems.reinit ();
      
      std::cout << "System has: " << equation_systems.n_active_dofs()
                << " degrees of freedom."
                << std::endl;

    } //end refinement loop
    
  //use that final refinement
  for (unsigned int t_step=0; t_step != n_timesteps; ++t_step)
    {
  
      std::cout << "\n\nSolving time step " << t_step << ", time = "
                << system.time << std::endl;
      
      system.solve();
      system.postprocess();
      
      //DEBUG
      if(printJ){ //aahhh this doesn't print if solve not successful...
        std::ostringstream Jfile_name;
        Jfile_name << "J.dat";
        std::ofstream outputJ(Jfile_name.str());
        system.matrix->print(outputJ);
        outputJ.close();
      }
      
      Number QoI_computed = system.get_QoI_value("computed", 0);
      std::cout<< "Computed QoI is " << std::setprecision(17) << QoI_computed << std::endl;
      
      // Advance to the next timestep in a transient problem
      system.time_solver->advance_timestep();

    } //end stepping through time loop
    
    
#ifdef LIBMESH_HAVE_EXODUS_API
  for (unsigned int t_step=0; t_step != n_timesteps; ++t_step)
    {
      // Write out this timestep if we're requested to
      if ((t_step+1)%write_interval == 0)
        {
          std::ostringstream ex_file_name;
          std::ostringstream tplot_file_name;

          // We write the file in the ExodusII format.
          //ex_file_name << "out_"
          //            << std::setw(3)
          //            << std::setfill('0')
          //            << std::right
          //            << t_step+1
          //            << ".e";
                      
          tplot_file_name << "out_"
                      << std::setw(3)
                      << std::setfill('0')
                      << std::right
                      << t_step+1
                      << ".plt";

          //ExodusII_IO(mesh).write_timestep(ex_file_name.str(),
          //                                 equation_systems,
          //                                 1, /* This number indicates how many time steps
          //                                       are being written to the file */
          //                                 system.time);
          exodusIO.write_timestep("output.exo", equation_systems, t_step+1, system.time); //outputs all timesteps in one file
          TecplotIO(mesh).write_equation_systems(tplot_file_name.str(), equation_systems);
        }
    }
#endif // #ifdef LIBMESH_HAVE_EXODUS_API     

  // All done.
  return 0;
  
} //end main
Ejemplo n.º 6
0
int main(int argc, char* argv[]) {
    static struct option long_options[] = {
        {"help",        no_argument, 0, 'h'},
        {"from-format", required_argument, 0, 'f'},
        {"to-format",   required_argument, 0, 't'},
        {0, 0, 0, 0}
    };

    std::string input_format;
    std::string output_format;

    while (true) {
        int c = getopt_long(argc, argv, "dhf:t:", long_options, 0);
        if (c == -1) {
            break;
        }

        switch (c) {
            case 'h':
                print_help();
                exit(0);
            case 'f':
                input_format = optarg;
                break;
            case 't':
                output_format = optarg;
                break;
            default:
                exit(1);
        }
    }

    std::string input;
    std::string output;
    int remaining_args = argc - optind;
    if (remaining_args > 2) {
        std::cerr << "Usage: " << argv[0] << " [OPTIONS] [INFILE [OUTFILE]]" << std::endl;
        exit(1);
    } else if (remaining_args == 2) {
        input =  argv[optind];
        output = argv[optind+1];
    } else if (remaining_args == 1) {
        input =  argv[optind];
    }

    osmium::io::File infile(input, input_format);

    osmium::io::File outfile(output, output_format);

    if (infile.has_multiple_object_versions() && !outfile.has_multiple_object_versions()) {
        std::cerr << "Warning! You are converting from an OSM file with (potentially) several versions of the same object to one that is not marked as such.\n";
    }

    try {
        osmium::io::Reader reader(infile);
        osmium::io::Header header = reader.header();
        header.set("generator", "osmium_convert");

        osmium::io::Writer writer(outfile, header, osmium::io::overwrite::allow);
        while (osmium::memory::Buffer buffer = reader.read()) {
            writer(std::move(buffer));
        }
        writer.close();
        reader.close();
    } catch (std::exception& e) {
        std::cerr << e.what() << "\n";
        exit(1);
    }

    google::protobuf::ShutdownProtobufLibrary();
}
Ejemplo n.º 7
0
	uint8_t* LoadMeshInfo(const char* i_pFile,
		uint32_t& o_vertexElementCount, Mesh::VertexElement*& o_pVertexElements, 
		uint32_t& o_vertexOffset, uint32_t& o_vertexCount,
		uint32_t& o_indexOffset, uint32_t& o_indexCount,
		uint32_t& o_subMeshOffset, uint32_t& o_subMeshCount)
	{
		if (!i_pFile)
			return nullptr;
		std::ifstream infile(i_pFile, std::ifstream::binary);
		if (!infile)
		{
			std::stringstream decoratedErrorMessage;
			decoratedErrorMessage << "Failed to load binary mesh file: " << i_pFile;
			ErrorMessageBox(decoratedErrorMessage.str().c_str());
			return nullptr;
		}
		// get size of file
		infile.seekg(0, infile.end);
		std::ifstream::pos_type size = infile.tellg();
		infile.seekg(0);
		// allocate memory for file content
		char* pBuffer = new char[(unsigned int)size];
		// read content of infile
		infile.read(pBuffer, size);
		if (!infile)
		{
			std::stringstream decoratedErrorMessage;
			decoratedErrorMessage << "Failed to load all data from: " << i_pFile << ", only " << infile.gcount() << "could be load.";
			ErrorMessageBox(decoratedErrorMessage.str().c_str());
			infile.close();
			delete[] pBuffer;
			return nullptr;
		}
		uint32_t offset = 0;
		{
			o_vertexElementCount = *reinterpret_cast<uint32_t*>(pBuffer + offset);
			offset += sizeof(uint32_t);
			o_pVertexElements = reinterpret_cast<EAE_Engine::Mesh::VertexElement*>(pBuffer + offset);
			offset += sizeof(EAE_Engine::Mesh::VertexElement) * o_vertexElementCount;
			// Get VertexCount
			uint32_t vertexCount = *reinterpret_cast<uint32_t*>(pBuffer + offset);
			o_vertexCount = vertexCount;
			offset += sizeof(uint32_t);
			// Get IndexCount
			uint32_t indexCount = *reinterpret_cast<uint32_t*>(pBuffer + offset);
			o_indexCount = indexCount;
			offset += sizeof(uint32_t);
			// Get SubMeshCount
			uint32_t subMeshCount = *reinterpret_cast<uint32_t*>(pBuffer + offset);
			o_subMeshCount = subMeshCount;
			offset += sizeof(uint32_t);
			// Set vertexOffset
			o_vertexOffset = offset;
			offset += sizeof(Mesh::sVertex) * vertexCount;
			// Set indexOffset
			o_indexOffset = offset;
			offset += sizeof(uint32_t) * indexCount;
			// Set subMeshOffset
			o_subMeshOffset = offset;
			offset += sizeof(Mesh::sSubMesh) * subMeshCount;
		}
		infile.close();
		return reinterpret_cast<uint8_t*>(pBuffer);
	}
Ejemplo n.º 8
0
void ImageDataLayer<Dtype>::DataLayerSetUp(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top) {
  const int new_height = this->layer_param_.image_data_param().new_height();
  const int new_width  = this->layer_param_.image_data_param().new_width();
  const bool is_color  = this->layer_param_.image_data_param().is_color();
  string root_folder = this->layer_param_.image_data_param().root_folder();

  CHECK((new_height == 0 && new_width == 0) ||
      (new_height > 0 && new_width > 0)) << "Current implementation requires "
      "new_height and new_width to be set at the same time.";
  // Read the file with filenames and labels
  const string& source = this->layer_param_.image_data_param().source();
  LOG(INFO) << "Opening file " << source;
  std::ifstream infile(source.c_str());
  string filename;
  int label;
  while (infile >> filename >> label) {
    lines_.push_back(std::make_pair(filename, label));
  }

  if (this->layer_param_.image_data_param().shuffle()) {
    // randomly shuffle data
    LOG(INFO) << "Shuffling data";
    const unsigned int prefetch_rng_seed = caffe_rng_rand();
    prefetch_rng_.reset(new Caffe::RNG(prefetch_rng_seed));
    ShuffleImages();
  }
  LOG(INFO) << "A total of " << lines_.size() << " images.";

  lines_id_ = 0;
  // Check if we would need to randomly skip a few data points
  if (this->layer_param_.image_data_param().rand_skip()) {
    unsigned int skip = caffe_rng_rand() %
        this->layer_param_.image_data_param().rand_skip();
    LOG(INFO) << "Skipping first " << skip << " data points.";
    CHECK_GT(lines_.size(), skip) << "Not enough points to skip";
    lines_id_ = skip;
  }
  // Read an image, and use it to initialize the top blob.
  cv::Mat cv_img = ReadImageToCVMat(root_folder + lines_[lines_id_].first,
                                    new_height, new_width, is_color);
  const int channels = cv_img.channels();
  const int height = cv_img.rows;
  const int width = cv_img.cols;
  // image
  const int crop_size = this->layer_param_.transform_param().crop_size();
  const int batch_size = this->layer_param_.image_data_param().batch_size();
  if (crop_size > 0) {
    top[0]->Reshape(batch_size, channels, crop_size, crop_size);
    this->prefetch_data_.Reshape(batch_size, channels, crop_size, crop_size);
    this->transformed_data_.Reshape(1, channels, crop_size, crop_size);
  } else {
    top[0]->Reshape(batch_size, channels, height, width);
    this->prefetch_data_.Reshape(batch_size, channels, height, width);
    this->transformed_data_.Reshape(1, channels, height, width);
  }
  LOG(INFO) << "output data size: " << top[0]->num() << ","
      << top[0]->channels() << "," << top[0]->height() << ","
      << top[0]->width();
  // label
  top[1]->Reshape(batch_size, 1, 1, 1);
  this->prefetch_label_.Reshape(batch_size, 1, 1, 1);
}
Ejemplo n.º 9
0
bool symex_parseoptionst::get_goto_program(
  const optionst &options,
  goto_functionst &goto_functions)
{
  if(cmdline.args.size()==0)
  {
    error() << "Please provide a program to verify" << eom;
    return true;
  }

  try
  {
    if(cmdline.args.size()==1 &&
       is_goto_binary(cmdline.args[0]))
    {
      status() << "Reading GOTO program from file" << eom;

      if(read_goto_binary(cmdline.args[0],
           symbol_table, goto_functions, get_message_handler()))
        return true;
        
      config.ansi_c.set_from_symbol_table(symbol_table);

      if(cmdline.isset("show-symbol-table"))
      {
        show_symbol_table();
        return true;
      }
      
      irep_idt entry_point=goto_functions.entry_point();
      
      if(symbol_table.symbols.find(entry_point)==symbol_table.symbols.end())
      {
        error() << "The goto binary has no entry point; please complete linking" << eom;
        return true;
      }
    }
    else if(cmdline.isset("show-parse-tree"))
    {
      if(cmdline.args.size()!=1)
      {
        error() << "Please give one source file only" << eom;
        return true;
      }
      
      std::string filename=cmdline.args[0];
      
      #ifdef _MSC_VER
      std::ifstream infile(widen(filename).c_str());
      #else
      std::ifstream infile(filename.c_str());
      #endif
                
      if(!infile)
      {
        error() << "failed to open input file `" << filename << "'" << eom;
        return true;
      }
                              
      languaget *language=get_language_from_filename(filename);
                                                
      if(language==NULL)
      {
        error() << "failed to figure out type of file `" <<  filename << "'" << eom;
        return true;
      }
      
      language->set_message_handler(get_message_handler());
                                                                
      status("Parsing", filename);
  
      if(language->parse(infile, filename))
      {
        error() << "PARSING ERROR" << eom;
        return true;
      }
      
      language->show_parse(std::cout);
      return true;
    }
    else
    {
    
      if(parse()) return true;
      if(typecheck()) return true;
      if(final()) return true;

      // we no longer need any parse trees or language files
      clear_parse();

      if(cmdline.isset("show-symbol-table"))
      {
        show_symbol_table();
        return true;
      }

      irep_idt entry_point=goto_functions.entry_point();
      
      if(symbol_table.symbols.find(entry_point)==symbol_table.symbols.end())
      {
        error() << "No entry point; please provide a main function" << eom;
        return true;
      }

      status() << "Generating GOTO Program" << eom;

      goto_convert(symbol_table, goto_functions, ui_message_handler);
    }

    // finally add the library
    status() << "Adding CPROVER library" << eom;
    link_to_library(symbol_table, goto_functions, ui_message_handler);

    if(process_goto_program(options, goto_functions))
      return true;
  }

  catch(const char *e)
  {
    error() << e << eom;
    return true;
  }

  catch(const std::string e)
  {
    error() << e << eom;
    return true;
  }
  
  catch(int)
  {
    return true;
  }
  
  catch(std::bad_alloc)
  {
    error() << "Out of memory" << eom;
    return true;
  }
  
  return false;
}
Ejemplo n.º 10
0
void ReaderSTEP::loadModelFromFile( const std::wstring& filePath, shared_ptr<BuildingModel>& targetModel )
{
	// if file content needs to be loaded into a plain model, call resetModel() before loadModelFromFile
	size_t posDot = filePath.find_last_of(L".");
	if( filePath.size() < posDot + 3 || posDot > filePath.size() )
	{
		messageCallback("not an .ifc file", StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__);
		return;
	}
	std::wstring ext = filePath.substr(posDot + 1);
	
	if( boost::iequals( ext, "ifc" ) )
	{
		// ok, nothing to do here
	}
	else if( boost::iequals( ext, "ifcXML" ) )
	{
		// TODO: implement xml reader
		messageCallback( "ifcXML not yet implemented", StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__ );
		return;
	}
	else if( boost::iequals( ext, "ifcZIP" ) || boost::iequals(ext, "zip") )
	{
		messageCallback( "ifcZIP not implemented, see www.ifcquery.com for details", StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__ );
		return;
	}
	else
	{
		std::wstringstream strs;
		strs << "Unsupported file type: " << ext;
		messageCallback( strs.str(), StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__ );
		return;
	}

	// open file
	if( !(setlocale(LC_ALL, "en-US") || setlocale(LC_ALL, "en_us.UTF-8") ||  setlocale(LC_ALL, "en_US.utf8")))
	{
		std::wstringstream strs;
		strs << L"setlocale failed" << std::endl;
		messageCallback(strs.str().c_str(), StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__);
		return;
	}

	char* buf = nullptr;
	size_t len = std::wcstombs(buf, filePath.c_str(), 0);
	buf = new char[len + 1];
	std::wcstombs(buf, filePath.c_str(), (len + 1) * 6);
	std::string filePathStr(buf);
	delete[] buf;
	std::ifstream infile(filePathStr.c_str(), std::ifstream::in);
	
	if( !infile.is_open() )
	{
		std::wstringstream strs;
		strs << "Could not open file: " << filePath.c_str();
		messageCallback( strs.str().c_str(), StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__ );
		return;
	}

	// get length of file content
	std::streampos file_size = infile.tellg();
	infile.seekg( 0, std::ios::end );
	file_size = infile.tellg() - file_size;
	infile.seekg( 0, std::ios::beg );

	// read file content into string
	std::string buffer( (int)file_size, '\0' );
	infile.read( &buffer[0], file_size );
	infile.close();

	size_t file_header_start = buffer.find("HEADER;");
	size_t file_header_end = buffer.find("ENDSEC;");
	if( file_header_start == std::string::npos || file_header_end == std::string::npos )
	{
		messageCallback("Not a valid IFC file, might be zip archive, see www.ifcquery.com for details", StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__);
		return;
	}

	loadModelFromString( buffer, targetModel);
}
Ejemplo n.º 11
0
bool FBXIO::DoesFileExist(const char *fileName)
{
	//http://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exist-using-standard-c-c11-c
	std::ifstream infile(fileName);
	return infile.good();	
}
Ejemplo n.º 12
0
bool SimUtilities::isFile(const std::string& path) {
    std::ifstream infile(path);
    return infile.good();
}
void mexFunction(	int nlhs, mxArray *plhs[], 
				 int nrhs, const mxArray*prhs[] ) 
{ 
	/* retrive arguments */
	if( nrhs<4 ) 
		mexErrMsgTxt("4 input arguments are required."); 
    if( nlhs!=1 ) 
        mexErrMsgTxt("1 output arguments are required."); 
	// first argument : input array
	int n = mxGetM(prhs[0]); 
	int p = mxGetN(prhs[0]);
    if( p>1 )
        mexErrMsgTxt("Works only for vector arrays."); 
    int dir = (int) *mxGetPr(prhs[1]);
    double* x = mxGetPr(prhs[0]);

    if( mxGetM(prhs[3])!=2 && mxGetN(prhs[3])!=2 )
        mexErrMsgTxt("known_bounds must be of size 2."); 
    int known_size = (int) *mxGetPr(prhs[2]);

    // lower and upper bounds on the int to code
    int known_a = (int) mxGetPr(prhs[3])[0];
    int known_b = (int) mxGetPr(prhs[3])[1];
    bool coding_size = true;
    if( known_size>0 )          // the decoder will know the size and provide it
        coding_size = false;
    bool coding_bounds = false;
    if( known_a==known_b && known_b==-1 )
        coding_bounds = true;  // the decoder will not know the bounds and pr

    // create encoderovide it    
    int capacity = HISTO_CAPACITY;       // capacity of histogram for arithmetic coder  
    EscapeCoder* entropy = new EscapeCoder(capacity);

    if( dir==1 )
    {
        // compute range of the data
        int a = 1<<20, b = -(1<<20); 
        for( int i=0; i<n; ++i )
        {
            if( x[i]<a )
                a = (int) x[i];
            if( x[i]>b )
                b = (int) x[i];
        }
        int subrange = b-a+1;
		if( subrange>=HISTO_CAPACITY )
			mexErrMsgTxt( "Too much symbols." );

        // Open output file
        ofstream outfile(filename, ios::out | ios::trunc | ios::binary);
        if( !outfile )
            mexErrMsgTxt("Cannot open file."); 
        // Create I/O interface object for arithmetic coder
        Encoder* encoder = new Encoder( outfile );

        // set the number of symbols
        entropy->setNSym( subrange );

        // code the size of the image and range
        if( coding_size )
            encoder->writePositive(n);
        else if( known_size!=n )
            mexErrMsgTxt("The provided size does not match the real size."); 
        if( coding_bounds )
            encoder->writeInt(a);
        else if( known_a>a )
            mexErrMsgTxt("The provided bound does not match the real size."); 
        if( coding_bounds )
            encoder->writeInt(b);
        else if( known_b<b )
            mexErrMsgTxt("The provided bound does not match the real size."); 

        // perform coding
        for( int i=0; i<n; i++ ) 
        {
            // rescale to positive integers
            int symbol = (int) (x[i]-a);
            assert( symbol>=0 && symbol<subrange );
            entropy->write(encoder, symbol, TRUE);
        }
        // finish encoding
        encoder->flush();
        delete encoder;
        outfile.close();

        // reopen output file
        FILE* fin = fopen( filename, "rb" );
        if( fin==NULL )
            mexErrMsgTxt("Cannot open file."); 
        int nbr_bytes = 0;
        // compute number of bytes
        while( getc(fin)!=EOF )
            nbr_bytes++;
        fclose(fin);
        // retrieve results in byte
        fin = fopen( filename, "rb" );
        plhs[0] = mxCreateNumericMatrix( nbr_bytes, 1, mxDOUBLE_CLASS, mxREAL );
        double* y = mxGetPr( plhs[0] );
        for( int i=0; i<nbr_bytes; ++i )
        {
            y[i] = (double) getc(fin);
        }
        fclose(fin);
    }
    else
    {
        // write data to a file byte by byte
        FILE* fin = fopen( filename, "wb" );
        if( fin==NULL )
            mexErrMsgTxt("Cannot open file."); 
        for( int i=0; i<n; ++i )
        {
            char c = (char) x[i];
            fwrite( &c, sizeof(char), 1, fin );
        }
        fclose(fin);

        // open compressed image file
        ifstream infile( filename, ios::in | ios::nocreate | ios::binary);
        if( !infile )
            error( "Unable to open file %s", filename );
        // Create I/O interface object for arithmetic decoder
        Decoder *decoder = new Decoder( infile );

        // retrieve size of the data
        int a, b;
        if( coding_size )
            n = decoder->readPositive();
        else
            n = known_size;
        if( coding_bounds )
            a = decoder->readInt();
        else
            a = known_a;
        if( coding_bounds )
            b = decoder->readInt();
        else
            b = known_b;
        int subrange = b-a+1;

        // set the number of symbols
        entropy->setNSym( subrange );

        // retrieve the data
        plhs[0] = mxCreateNumericMatrix( n, 1, mxDOUBLE_CLASS, mxREAL );
        double* y = mxGetPr( plhs[0] );

        for( int i=0; i<n; ++i ) 
        {
            int symbol = entropy->read( decoder, TRUE );
            assert( symbol<subrange && symbol >= 0);
            y[i] = a + symbol;
        }
    }
}
Ejemplo n.º 14
0
int jsongrabmysql(string filename)
{
	int i, count = 0;
	MYSQL mysql;

	/*
mysql_init (&mysql);
        if(!mysql_real_connect(&mysql,"localhost","root", NULL , "sina", 3306, NULL, 0))
        {
                cout << "mysql fail!" << endl;
        }
        else
                cout << "mysql connected!" << endl;
	*/

	std::ifstream infile(filename.c_str());
	Json::Value root;
	Json::Reader reader;
	string str, msg;
	if(infile.is_open())
	{
		while(infile>>str)
			msg += str;
	}
	int contentpos = 0, textpos = 0, quotpos = 0, picpos = 0;
	while(contentpos != -1)
	{
		contentpos = msg.find("content", contentpos + 1);
	//	cout << "contentpos:" << contentpos << endl;
		if(contentpos == -1)
			break;
		if(textpos = msg.find("text", contentpos))
		{
	//		cout << "textpos:" << textpos << msg[textpos] <<  endl;	
		}
		quotpos = msg.find("\"", textpos+7);
	//	cout << "quotpos:" << quotpos << endl;
		picpos = msg.find("pic", quotpos);
	//	cout << "picpos:" << picpos << endl;
		while(picpos - quotpos != 3)
		{
			msg.replace(quotpos, 1, " ");
	
			quotpos = msg.find("\"", quotpos + 1);
	//		cout << "quotpos:" << quotpos << endl;
		}
	//	cout << endl;
	}
//	cout << msg << endl;
//		fstream outfile(filenametmp.c_str(), ios::out);
//		outfile << msg;
//		outfile.close();


		//cout << msg << endl;
	bool  ok = reader.parse(msg, root);
      	if (!ok)
        {
	  cout  << "Failed to parse configuration\n" << reader.getFormatedErrorMessages();
	  return 1;  
	}

	Json::Value arrayObj = root["result"];

	for(i = 0; i < arrayObj.size(); i++)
	  {
	    struct weiboinfo weiboinfotmp;
	    struct weibo weibotmp;
	    string content, topic;
	    int firstsh, secondsh;
	    
	    weiboinfotmp.mblogid = arrayObj[i]["mblogid"].asString();
	    weiboinfotmp.basicinfo_uid = arrayObj[i]["uid"].asLargestInt();
	    weiboinfotmp.basicinfo_time = arrayObj[i]["time"].asLargestInt();
	    weiboinfotmp.basicinfo_source = arrayObj[i]["source"].asInt();
	    weiboinfotmp.basicinfo_rtnum = arrayObj[i]["rtnum"].asInt();
	    weiboinfotmp.basicinfo_cmtnum = arrayObj[i]["cmtnum"].asInt();
	    weibotmp.content = arrayObj[i]["content"]["text"].asString();
	    content = weibotmp.content;
	    firstsh = content.find_first_of('#');
	    if(firstsh > 0)
	    {
			secondsh = content.find_first_of('#', firstsh + 1);
			int j;
			if(secondsh > firstsh)
			{
				for(j = firstsh + 1; j != secondsh; j++)
				{
					//cout << secondsh - firstsh << endl;
					//cout << content[j] << endl;
					topic += content[j];
				}
				weiboinfotmp.basicinfo_topic = topic;
			}
			//cout << topic << endl;
	      }

	    if(!arrayObj[i]["content"]["atUsers"].empty())
	      {
		Json::Value::Members member = (arrayObj[i]["content"]["atUsers"]).getMemberNames();
		vector<string>::iterator iMember;
		string atuser;
		//cout << *(member.begin()) << endl;
		for(iMember = member.begin(); iMember != member.end(); iMember++)
		  {
		    atuser += *iMember;
		    if(iMember + 1 != member.end())
		      atuser += ";";
		  }
		weiboinfotmp.atusers = atuser;
	      }
	    
	    weiboinfotmp.rtinfo_rootuid = arrayObj[i]["rt"]["rootuid"].asLargestInt();
	    weiboinfotmp.rtinfo_fromuid = arrayObj[i]["rt"]["fromuid"].asLargestInt();
	    string rturl = arrayObj[i]["rt"]["rturl"].asString();
	    if(!rturl.empty())
	      weiboinfotmp.rtinfo_fromid = rturl.substr(rturl.length() - 9, 9);
	    weiboinfotmp.rtinfo_rootid = arrayObj[i]["rt"]["rootid"].asString();
	    weiboinfotmp.rtinfo_rootrtnum = 0;
	    if(arrayObj[i]["rt"]["rootrtnum"].isString())
	      {
		weiboinfotmp.rtinfo_rootrtnum =  atoi(arrayObj[i]["rt"]["rootrtnum"].asString().c_str());
	      }
	    else if(arrayObj[i]["rt"]["rootrtnum"].isInt())
	      weiboinfotmp.rtinfo_rootrtnum = arrayObj[i]["rt"]["rootrtnum"].asLargestInt();
	    weiboinfotmp.rtinfo_rtreason = arrayObj[i]["rt"]["rtreason"].asString();
	    
	    if(i == arrayObj.size() - 1)
	      {
		weiboinfotmp.lastitem=1;
		weiboinfotmp.filename=filename;
	      }
	    else 
	      {
		weiboinfotmp.lastitem=0;
	      }
	    
	    infile.close();
	  }
	return 0;
}
Ejemplo n.º 15
0
int main(int argc, char *argv[])
{
    // declare variables
    std::vector<std::string> words;
    std::vector<frequencyCounter::words> wordCount;
    std::vector<frequencyCounter::characters> characterCount;

    std::string line;
    std::ofstream logfile;

    // Benchmark time
    QTime timer;
    timer.start();

    // check command line arguments
    if ( argc != 3 )
    {
        std::cout << "usage: " << argv[0] << " <filename> <logfile>\n";
        return 0;
    }

    // open file and check if open
    std::ifstream infile(argv[1]);

    if ( !infile.is_open())
    {
         std::cout << "Could not open " << argv[1] << " file\n";
         return 0;
    }

    frequencyCounter fc;

    // loop file, line by line
    while (std::getline(infile, line))
    {
        // split words from line
        words = fc.split(line, ' ');

        // parse characters and words
        fc.parseText(words, wordCount, characterCount);

        words.clear();

    }

    // sort the word and character vectors
    std::sort(wordCount.begin(), wordCount.end(), compareByWordCount());
    std::sort(characterCount.begin(), characterCount.end(), compareByChrCount());

    // write results to log file
    std::cout << "writing results to " << argv[1] << " file\n";

    logfile.open(argv[2]);
    logfile << "\nWords sorted by frequency\n\n";

    for(auto& word : wordCount)
        logfile << word.word << " = " << word.count << '\n';

    logfile << "\nCharacters sorted by frequency\n\n";

    for(auto& chrs : characterCount)
        logfile << chrs.chr << " = " << chrs.count << '\n';


    logfile.close();

    std::cout << "Done\n";

    std::cout << std::fixed;
    std::cout << std::setprecision(3);

    std::cout << "\nElapsed Time = " << timer.elapsed() * 0.001  << "\n";

    return 0;
}
Ejemplo n.º 16
0
void ImageDataLayer<Dtype>::DataLayerSetUp(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top) {
  const int new_height = this->layer_param_.image_data_param().new_height();
  const int new_width  = this->layer_param_.image_data_param().new_width();
  const bool is_color  = this->layer_param_.image_data_param().is_color();
  string root_folder = this->layer_param_.image_data_param().root_folder();

  CHECK((new_height == 0 && new_width == 0) ||
      (new_height > 0 && new_width > 0)) << "Current implementation requires "
      "new_height and new_width to be set at the same time.";
  // Read the file with filenames and labels
  const string& source = this->layer_param_.image_data_param().source();
  LOG(INFO) << "Opening file " << source;
  std::ifstream infile(source.c_str());
  string filename;
  int label;
  while (infile >> filename >> label) {
    lines_.push_back(std::make_pair(filename, label));
  }

  if (this->layer_param_.image_data_param().shuffle()) {
    // randomly shuffle data
    LOG(INFO) << "Shuffling data";
    const unsigned int prefetch_rng_seed = caffe_rng_rand();
    prefetch_rng_.reset(new Caffe::RNG(prefetch_rng_seed));
    ShuffleImages();
  }
  LOG(INFO) << "A total of " << lines_.size() << " images.";

  lines_id_ = 0;
  // Check if we would need to randomly skip a few data points
  if (this->layer_param_.image_data_param().rand_skip()) {
    unsigned int skip = caffe_rng_rand() %
        this->layer_param_.image_data_param().rand_skip();
    LOG(INFO) << "Skipping first " << skip << " data points.";
    CHECK_GT(lines_.size(), skip) << "Not enough points to skip";
    lines_id_ = skip;
  }
  // Read an image, and use it to initialize the top blob.
  cv::Mat cv_img = ReadImageToCVMat(root_folder + lines_[lines_id_].first,
                                    new_height, new_width, is_color);
  CHECK(cv_img.data) << "Could not load " << lines_[lines_id_].first;
  // Use data_transformer to infer the expected blob shape from a cv_image.
  vector<int> top_shape = this->data_transformer_->InferBlobShape(cv_img);
  this->transformed_data_.Reshape(top_shape);
  // Reshape prefetch_data and top[0] according to the batch_size.
  const int batch_size = this->layer_param_.image_data_param().batch_size();
  CHECK_GT(batch_size, 0) << "Positive batch size required";
  top_shape[0] = batch_size;
  for (int i = 0; i < this->PREFETCH_COUNT; ++i) {
    this->prefetch_[i].data_.Reshape(top_shape);
  }
  top[0]->Reshape(top_shape);

  LOG(INFO) << "output data size: " << top[0]->num() << ","
      << top[0]->channels() << "," << top[0]->height() << ","
      << top[0]->width();
  // label
  vector<int> label_shape(1, batch_size);
  top[1]->Reshape(label_shape);
  for (int i = 0; i < this->PREFETCH_COUNT; ++i) {
    this->prefetch_[i].label_.Reshape(label_shape);
  }
}
Ejemplo n.º 17
0
int SCBus::setup_batch(const char* file_name)
{
    cout << "SCBus: setup_batch() invoked" << endl;
    cout << "Parsing file '" << file_name << "'" << endl;

    std::string line; // FIXME: check why std:: is needed here
    ifstream infile(file_name);

    if (!infile.is_open()) {
        cout << "SCBus: Unable to open file '" << file_name << "'" << endl;
    }

    SCBusPacket packet;
    unsigned int dctr, data, lctr;
    long long ts, ts_last;
    ts_last = 0;
    lctr = 0;

    while (std::getline(infile, line)) {
        std::istringstream lss(line);
        std::string token;
        lctr++;

        getline(lss,token,' ');
        ts = std::stoll(token.c_str());
        if (ts_last >= ts && ts_last != 0) {
            cout << "WARNING: SCBus batch file time stamp is out of sequence in line "
                << lctr << ":" << endl;
            cout << "'" << line << "' (ignoring line)" << endl;
            continue;
        }

        memset(&packet, 0, sizeof(SCBusPacket));
        packet.header.timestamp = ts;

        dctr = 0;
        while (std::getline(lss,token,' ')) {
            if (dctr == SCBUS_PACKET_MAX_DATA_LENGTH-1) {
                cout << "WARNING: SCBus batch file data length is over the limit (" <<
                    (int)SCBUS_PACKET_MAX_DATA_LENGTH << ") in line " << lctr
                    << " (truncating line)" << endl;
                break;
            }
            data = std::stoul(token.c_str(),nullptr,16);
            if (data > 255) {
                cout << "WARNING: SCBus batch file data out of range in line "
                    << lctr << ":" << endl;
                cout << "'" << line << "' (truncating value)" << endl;
                data &= 0xFFul;
            }
            packet.data[dctr++] = (char)data;
        }

        if (dctr == 0) {
            cout << "WARNING: SCBus batch file with empty data field in line " << lctr << ":" << endl;
            cout << "'" << line << "' (ignoring line)" << endl;
            continue;
        }

        packet.header.length = dctr;
        batch_fifo.push(packet);
        ts_last = ts;
    }

    cout << "Parsing done" << endl;
    infile.close();
    return 0;
}
Ejemplo n.º 18
0
int	main(int argc, char *argv[]) {
	int	c;
	int	longindex;
	bool	force = false;
	double	radius = 1;
	ImagePtr	maskptr;
	double	degree = 0.0;
	while (EOF != (c = getopt_long(argc, argv, "dhe:?fm:r:", longopts,
		&longindex))) {
		switch (c) {
		case 'd':
			debuglevel = LOG_DEBUG;
			break;
		case 'e':
			degree = std::stod(optarg);
			break;
		case 'f':
			force = true;
			break;
		case 'h':
		case '?':
			usage(argv[0]);
			return EXIT_SUCCESS;
		case 'r':
			radius = std::stod(optarg);
			break;
		case 'm':
			maskptr = io::FITSin(optarg).read();
			break;
		default:
			throw std::runtime_error("unknown option");
		}
	}

	// if the mask is not specified, throw an exception
	if (!maskptr) {
		std::runtime_error("mask must be specified, use option --mask");
	}

	// make sure we have at least 2 files
	if (optind >= argc) {
		std::cerr << "must specify image to get hdr" << std::endl;
		return EXIT_FAILURE;
	}
	std::string	infile(argv[optind++]);
	if (optind >= argc) {
		std::cerr << "must specify output file name" << std::endl;
		return EXIT_FAILURE;
	}
	std::string	outfile(argv[optind++]);

	// convert the mask image to double, as we have to fourier transform it
	FourierImage	*fmask = NULL;
	typeconvert(unsigned char, maskptr);
	typeconvert(unsigned short, maskptr);
	typeconvert(unsigned int, maskptr);
	typeconvert(unsigned long, maskptr);
	typeconvert(float, maskptr);
	typeconvert(double, maskptr);
	if (NULL == fmask) {
		std::runtime_error("cannot work with this mask type");
	}
	FourierImagePtr	fmaskptr(fmask);

	// get a gaussian blurring function
	debug(LOG_DEBUG, DEBUG_LOG, 0, "create %s gauss with radius %f",
		maskptr->size().toString().c_str(), radius);
	TiledGaussImage	tg(maskptr->size(), radius, 1);
	Image<double>	*tgimage = new Image<double>(tg);
	ImagePtr	tgimageptr(tgimage);
	FourierImage	blurr(*tgimage);

	// convolve
	FourierImagePtr	blurred = (*fmask) * blurr;
	ImagePtr	blurredmaskptr = blurred->inverse();
	Image<double>	*blurredmask
		= dynamic_cast<Image<double>*>(&*blurredmaskptr);

	io::FITSout	blurredout("blurredout.fits");
	blurredout.setPrecious(false);
	blurredout.write(ImagePtr(tgimage));

	// open the input file
	io::FITSin	in(infile);
	ImagePtr	imageptr = in.read();
	debug(LOG_DEBUG, DEBUG_LOG, 0, "found %s-image of type %s", 
		imageptr->size().toString().c_str(),
		demangle(imageptr->pixel_type().name()).c_str());

	// hdr masking of image
	ImagePtr	outimage = do_deemphasize(imageptr, *blurredmask,
		degree);

	// find out whether the file exists
	io::FITSout	out(outfile);
	if (out.exists()) {
		if (force) {
			out.unlink();
		} else {
			std::cerr << "file " << outfile << " exists" << std::endl;
			return EXIT_FAILURE;
		}
	}

	// write the file
	out.write(outimage);

	return EXIT_SUCCESS;
}
Ejemplo n.º 19
0
int main(int argc, char **argv) {
    int			listenfd, connfd;  // Unix file descriptors
    struct sockaddr_in	servaddr;          // Note C use of struct
    char		buff[MAXLINE];
    // time_t		ticks;

    // 1. Create the socket
    if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("Unable to create a socket");
        exit(1);
    }

    // 2. Set up the sockaddr_in

    // zero it.  
    // bzero(&servaddr, sizeof(servaddr)); // Note bzero is "deprecated".  Sigh.
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family      = AF_INET; // Specify the family
    // use any network card present
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port        = htons(PORT_NUM);	// daytime server

    // 3. "Bind" that address object to our listening file descriptor
    if (bind(listenfd, (SA *) &servaddr, sizeof(servaddr)) == -1) {
        perror("Unable to bind port");
        exit(2);
    }

    // 4. Tell the system that we are going to use this sockect for
    //    listening and request a queue length
    if (listen(listenfd, LISTENQ) == -1) {
        perror("Unable to listen");
        exit(3);
    }
    
    std::unordered_map<std::string, int> m1 = 
    {
        {"msg_all", 1}, {"msg_flw", 2}, {"login", 3}, {"register", 4}, {"compose", 5},
        {"follow", 6}, {"unfollow", 7}
    };

    for ( ; ; ) {
        std::string path = "/Applications/XAMPP/xamppfiles/test/";
        std::string ext = ".txt";
        // 5. Block until someone connects.
        //    We could provide a sockaddr if we wanted to know details of whom
        //    we are talking to.
        //    Last arg is where to put the size of the sockaddr if
        //    we asked for one
	fprintf(stderr, "Ready to connect.\n");
        if ((connfd = accept(listenfd, (SA *) NULL, NULL)) == -1) {
            perror("accept failed");
            exit(4);
	}
	fprintf(stderr, "Connected\n");

    bzero(buff, strlen(buff));
    read(connfd, buff, 255);
    // fprintf(stderr, "data: %s\n", buff);

    std::string data = std::string(buff);
    std::istringstream iss(data);
    std::vector<std::string> tokens{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}};
    for(int i = 0; i < tokens.size() ; i++){
        std::cout << tokens[i] << " ";
    }
    std::cout << "\n";

    int cmd = m1[tokens[0]];
    // std::cout << cmd << " " << tokens[0] << " " << tokens.size() << "\n";

    switch(cmd){
    case 1:
    {
        std::cout << "msg_all execute\n";
        std::ifstream infile(path+"messages"+ext);
        std::string line, retval = "";
        if(infile.is_open()){
            while(getline(infile, line)){
                // std::cout << line << "\n";
                retval += (line + "\n");
                // write(connfd, line.c_str(), line.size());
            }
            write(connfd, retval.c_str(), retval.size());
            infile.close();
        }
        break;
    }
    case 2:
    {
        std::cout << "msg_flw execute\n";
        std::ifstream ifs(path+"following"+ext);
        std::vector<std::string> flwing;
        std::string line, username = tokens[1], retval = "";
        if(ifs.is_open()){
            while(getline(ifs, line)){
                std::istringstream iss2(line);
                std::vector<std::string> temp{std::istream_iterator<std::string>{iss2}, std::istream_iterator<std::string>{}};
                if(temp[0] == username){
                    for(int i = 1; i < temp.size(); i++){
                        flwing.push_back(temp[i]);
                    }
                }
            }
            ifs.close();
        }
        ifs.open(path+"messages"+ext);
        if(ifs.is_open()){
            while(getline(ifs, line)){
                std::istringstream iss2(line);
                std::vector<std::string> temp{std::istream_iterator<std::string>{iss2}, std::istream_iterator<std::string>{}};
                for(int i = 0; i < flwing.size(); i++){
                    if(flwing[i] == temp[0]){
                        retval += (line + "\n");
                    }
                }
            }
            write(connfd, retval.c_str(), retval.size());
            ifs.close();
        }
        break;
    }
    case 3:
    {
        std::cout << "login execute\n";
        std::ifstream infile(path+"users"+ext);
        std::string line, username = tokens[1], password = tokens[2];
        if(infile.is_open()){
            while(getline(infile, line)){
                std::istringstream iss2(line);
                std::vector<std::string> fields{std::istream_iterator<std::string>{iss2}, std::istream_iterator<std::string>{}};
                // std::cout << fields[0] << " " << fields[1] << " " << fields[2] << "\n";
                if(fields[0] == username){
                    if(fields[1] == password){
                        write(connfd, "true", 4);
                    }else{
                        write(connfd, "false", 5);
                    }
                    break;
                }
            }
            infile.close();
        }
        break;
    }
    case 4:
    {
        std::cout << "register execute\n";
        std::ifstream ifs(path+"users"+ext);
        std::string line, username = tokens[1], password = tokens[2], email = tokens[3];
        bool taken = false;
        if(ifs.is_open()){
            while(getline(ifs, line) && !taken){
                std::istringstream iss2(line);
                std::vector<std::string> temp{std::istream_iterator<std::string>{iss2}, std::istream_iterator<std::string>{}};
                if(temp[0] == username){
                    taken = true;
                }
            }
            ifs.close();
        }
        if(taken){
            write(connfd, "false", 5);
        }
        else{
            std::string retval = username + " " + password + " " + email;
            std::ofstream output(path+"users"+ext, std::ios::app);
            output << "\n" << retval;
            output.close();
            write(connfd, "true", 4);
        }
        break;
    }
    case 5:
    {
        std::cout << "compose execute\n";
        std::string author = tokens[1], timestamp = tokens[2];
        std::vector<std::string> msg;
        for(int i = 3; i < tokens.size(); i++){
            msg.push_back(tokens[i]);
        }
        std::ofstream output(path+"messages"+ext, std::ios::app);
        std::string retval = author + " " + timestamp + " ";
        for(int i = 0; i < msg.size(); i++){
            retval += msg[i];
            if(i != msg.size()-1)
                retval += " ";
        }
        output << "\n" << retval;
        output.close();
        break;
    }
    case 6:
    {
        std::cout << "follow execute\n";
        std::ifstream ifs(path+"following"+ext);
        std::string line, username = tokens[1], newf = tokens[2];
        std::vector<std::string> flwing;
        bool found = false, valid = true;
        std::ofstream output;
        std::string temp_file = path+"temp"+ext;
        if(ifs.is_open()){
            output.open(temp_file);
            while(getline(ifs, line) && valid){
                std::istringstream iss2(line);
                std::vector<std::string> temp{std::istream_iterator<std::string>{iss2}, std::istream_iterator<std::string>{}};
                if(temp[0] == username){
                    found = true;
                    for(int i = 1; i < temp.size(); i++){
                        flwing.push_back(temp[i]);
                        if(newf == temp[i]){
                            std::cout << "cond 1\n";
                            valid = false;
                            write(connfd, "false", 5);
                            break;
                        }
                    }
                }else{
                    output << line << "\n";
                }
            }
            ifs.close();
            output.close();
        }
        if(!found){
            std::cout << "cond 2\n";
            std::ofstream output2(path+"following"+ext, std::ios::app);
            std::string retval = username + " " + newf;
            output2 << "\n" << retval;
            output2.close();
            write(connfd, "true", 4);
        }
        if(valid && found){
            std::cout << "cond 3\n";
            output.open(path+"following"+ext);
            ifs.open(temp_file);
            while(getline(ifs, line)){
                output << line << "\n";
            }
            std::string retval = username + " ";
            for(int i = 0; i < flwing.size(); i++){
                retval += flwing[i];
                retval += " ";
            }
            retval += newf;
            output << retval;
            output.close();
            ifs.close();
            write(connfd, "true", 4);
        }
        break;
    }
    case 7:
    {
        std::cout << "unfollow execute\n";
        std::ifstream ifs(path+"following"+ext);
        std::string line, username = tokens[1], unf = tokens[2];
        std::vector<std::string> flwing;
        bool found = false, valid = true;
        std::ofstream output;
        std::string temp_file = path+"temp"+ext;
        if(ifs.is_open()){
            output.open(temp_file);
            while(getline(ifs, line) && valid){
                std::istringstream iss2(line);
                std::vector<std::string> temp{std::istream_iterator<std::string>{iss2}, std::istream_iterator<std::string>{}};
                if(temp[0] == username){
                    found = true;
                    for(int i = 1; i < temp.size(); i++){
                        if(temp[i] != unf){
                            flwing.push_back(temp[i]);
                        }
                    }
                    if(temp.size() != flwing.size() + 2){
                        valid = false;
                        write(connfd, "false", 5);
                        break;
                    }
                }else{
                    output << line << "\n";
                }
            }
            ifs.close();
            output.close();
        }
        if(!found){
            write(connfd, "false", 5);
            break;
        }
        if(valid && found){
            output.open(path+"following"+ext);
            ifs.open(temp_file);
            while(getline(ifs, line)){
                output << line << "\n";
            }
            std::string retval = username + " ";
            for(int i = 0; i < flwing.size(); i++){
                retval += flwing[i];
                if(i != flwing.size()-1)
                    retval += " ";
            }
            output << retval;
            output.close();
            ifs.close();
            write(connfd, "true", 4);
        }
        break;
    }
    default:
    {
        write(connfd, "error", 5);
        break;
    }
    }

        // 6. Close the connection with the current client and go back
        //    for another.
        close(connfd);
    }
}
Ejemplo n.º 20
0
int LTKInkFileReader::readUnipenInkFileWithAnnotation(const string& inkFile,const string& hierarchyLevel,const string& quality, LTKTraceGroup& traceGroup,map<string,string>& traceIndicesCommentsMap,LTKCaptureDevice& captureDevice, LTKScreenContext& screenContext)
{
    LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
                                        " Entering: LTKInkFileReader::readUnipenInkFileWithAnnotation()" << endl;

    vector<float> point;				//	a point of a trace

    float xDpi;							//	device resolution in the x direction

    float yDpi;							//	device resolution in the y direction

    float bboxLeft;						//	leftmost x-coord of the writing area

    float bboxBottom;					//	bottommost y-coord of the writing area

    float bboxRight;					//	rightmost x-coord of the writing area

    float bboxTop;						//	topmost y-coord of the writing area

    float floatChannelValue;			//	channel value of type float

    long longChannelValue;				//	channel value of type long

    string channelNames;				//	string containing all the channel names

    vector<string> channelNamesVector;	//	vector of channel names

    int channelIndex;					//	index to loop over all channels in the channel list

    vector<string> qualityLevels;		//	list of quality levels required

    vector<string> coordVals;			//	list of coordinate values present

    string remainingLine;				//remaining of the line that does not contain the required hierarchy level

    bool verFlag = false, hlevelFlag = false, coordFlag = false;//  bool level that denote whether version Info, Hierarchy level and coordinate info are set

    bool pendownFlag = false;

    LTKStringUtil::tokenizeString(quality,",", qualityLevels);

    //	opening the ink file

    if(inkFile.empty())
    {
        LOG(LTKLogger::LTK_LOGLEVEL_ERR)
                <<"Error : "<< EINKFILE_EMPTY <<":"<< getErrorMessage(EINKFILE_EMPTY)
                <<"LTKInkFileReader::readUnipenInkFileWithAnnotation()" <<endl;

        LTKReturnError(EINKFILE_EMPTY);
    }

    ifstream infile(inkFile.c_str());	//

    //	checking if the file open was successful

    if(!infile)
    {
        LOG(LTKLogger::LTK_LOGLEVEL_ERR)
                <<"Error : "<< EINK_FILE_OPEN <<":"<< getErrorMessage(EINK_FILE_OPEN)
                <<"LTKInkFileReader::readUnipenInkFileWithAnnotation()" <<endl;

        LTKReturnError(EINK_FILE_OPEN);
    }

    LTKTrace *trace = NULL;						//	initializing trace to NULL

    vector<LTKChannel> channels;				//	channels of a trace

    LTKTraceFormat traceFormat;					//	format of the trace

    //	reading the ink file

    string keyWord;								//	a key word of the unipen format

    while(infile)
    {
        keyWord = "";
        infile >> keyWord;

        if(keyWord == ".COORD")
        {
            coordFlag = true;

            getline(infile, channelNames);

            LTKStringUtil::tokenizeString(channelNames, " \t", channelNamesVector);

            for(channelIndex = 0; channelIndex < channelNamesVector.size(); ++channelIndex)
            {
                if(channelNamesVector[channelIndex] == "T")
                {
                    LTKChannel channel(channelNamesVector[channelIndex], DT_LONG, true);
                    channels.push_back(channel);
                }
                else
                {
                    LTKChannel channel(channelNamesVector[channelIndex], DT_FLOAT, true);
                    channels.push_back(channel);
                }
            }

            traceFormat.setChannelFormat(channels);

        }
        else if(keyWord == ".X_POINTS_PER_INCH")
        {
            infile >> xDpi;
            captureDevice.setXDPI(xDpi);

        }
        else if(keyWord == ".Y_POINTS_PER_INCH")
void EnergyDependentCorrections() {

  gStyle->SetOptStat(0);
  gStyle->SetTitleSize(0.08,"t");
  gStyle->SetPadLeftMargin(0.15);
  //gStyle->SetPadRightMargin(0.15);
  gStyle->SetPadBottomMargin(0.15);
  gStyle->SetTitleYSize(0.05);
  gStyle->SetTitleYOffset(1.4);
  gStyle->SetTitleXSize(0.05);
  gStyle->SetTitleXOffset(1.2);
  gStyle->SetTitleSize(0.04,"Z");
  gStyle->SetTitleOffset(1.6,"Z");
  gStyle->SetLabelSize(0.04,"xyz");
  gStyle->SetLegendBorderSize(0);
  gStyle->SetFillStyle(0);

  // read in the corrections and plot their deltaA/A for each bin
  // This can be done for both theory and MC

  //Int_t octmin = year==2011?0:60;
  //Int_t octmax = year==2011?59:121;

  std::vector <Double_t> energy;
  std::vector <Double_t> UnCorr2011;
  std::vector <Double_t> TheoryCorr2011;
  std::vector <Double_t> AllCorr2011;

  std::vector <Double_t> UnCorr2012;
  std::vector <Double_t> TheoryCorr2012;
  std::vector <Double_t> AllCorr2012;

  Double_t en, val, err;
  
  std::ifstream infile(TString::Format("%s/Asymmetries/UnCorr_OctetAsymmetries_AnaChC_Octets_%i-%i_BinByBin.txt",getenv("ANALYSIS_RESULTS"),0,59));
  
  while (infile >> en >> val >> err ) {
    energy.push_back(en);
    UnCorr2011.push_back(val);
  }

  infile.close();

  infile.open(TString::Format("%s/Asymmetries/DeltaTheoryOnly_OctetAsymmetries_AnaChC_Octets_%i-%i_BinByBin.txt",getenv("ANALYSIS_RESULTS"),0,59));
  
  while (infile >> en >> val >> err) {
    TheoryCorr2011.push_back(val);
  }

  infile.close();

  infile.open(TString::Format("%s/Asymmetries/AllCorr_OctetAsymmetries_AnaChC_Octets_%i-%i_BinByBin.txt",getenv("ANALYSIS_RESULTS"),0,59));
  
  while (infile >> en >> val >> err) {
    AllCorr2011.push_back(val);
  }

  infile.close();
    
  infile.open(TString::Format("%s/Asymmetries/UnCorr_OctetAsymmetries_AnaChC_Octets_%i-%i_BinByBin.txt",getenv("ANALYSIS_RESULTS"),60,121));
  
  while (infile >> en >> val >> err ) {
    energy.push_back(en);
    UnCorr2012.push_back(val);
  }

  infile.close();

  infile.open(TString::Format("%s/Asymmetries/DeltaTheoryOnly_OctetAsymmetries_AnaChC_Octets_%i-%i_BinByBin.txt",getenv("ANALYSIS_RESULTS"),60,121));
  
  while (infile >> en >> val >> err) {
    TheoryCorr2012.push_back(val);
  }

  infile.close();

  infile.open(TString::Format("%s/Asymmetries/AllCorr_OctetAsymmetries_AnaChC_Octets_%i-%i_BinByBin.txt",getenv("ANALYSIS_RESULTS"),60,121));
  
  while (infile >> en >> val >> err) {
    AllCorr2012.push_back(val);
  }

  infile.close();


  
  
  
  

  std::vector <Double_t> en_Th;
  std::vector <Double_t> corr_Th;
  std::vector <Double_t> en_MC2011;
  std::vector <Double_t> corr_MC2011;
  std::vector <Double_t> en_MC2012;
  std::vector <Double_t> corr_MC2012;
  
  
  for (int i=2;i<80;++i) {

    if (UnCorr2011[i]!=0.) en_Th.push_back(energy[i]), corr_Th.push_back(100.*(TheoryCorr2011[i]/UnCorr2011[i]-1.));
    if (TheoryCorr2011[i]!=0.) en_MC2011.push_back(energy[i]), corr_MC2011.push_back(100.*(AllCorr2011[i]/TheoryCorr2011[i]-1.));
    if (TheoryCorr2012[i]!=0.) en_MC2012.push_back(energy[i]), corr_MC2012.push_back(100.*(AllCorr2012[i]/TheoryCorr2012[i]-1.));
  }

  

  TCanvas *c2 = new TCanvas("c2","c2",1200,800);
  c2->Divide(2,1);

  c2->cd(1);

  TGraph *gTheory = new TGraph(en_Th.size(),&en_Th[0],&corr_Th[0]);
  gTheory->SetTitle("Theory Corrections vs. Energy");
  gTheory->SetMarkerStyle(kFullCircle);
  gTheory->SetMinimum(-5.);
  gTheory->SetMaximum(0.);
  gTheory->SetLineWidth(3);
  gTheory->SetLineColor(kBlack);
  gTheory->GetYaxis()->SetTitle("#DeltaA/A (%)");
  gTheory->GetYaxis()->CenterTitle();
  gTheory->GetXaxis()->SetTitle("Energy (keV)");
  gTheory->GetXaxis()->CenterTitle();
  gTheory->Draw("AL");
  
  c2->cd(2);

  TMultiGraph *mg = new TMultiGraph();
  mg->SetTitle("MC Corrections vs. Energy");
  
  TGraph *gMC2011 = new TGraph(en_MC2011.size(),&en_MC2011[0],&corr_MC2011[0]);
  gMC2011->SetMarkerStyle(kFullCircle);
  //gMC2011->SetMinimum(-10.);
  //gMC2011->SetMaximum(6.);
  gMC2011->SetLineWidth(3);
  gMC2011->SetLineColor(kBlue);
  gMC2011->GetYaxis()->SetTitle("#DeltaA/A (%)");
  gMC2011->GetYaxis()->CenterTitle();
  gMC2011->GetXaxis()->SetTitle("Energy (keV)");
  gMC2011->GetXaxis()->CenterTitle();
  //gMC2011->Draw("AC");

  TGraph *gMC2012 = new TGraph(en_MC2012.size(),&en_MC2012[0],&corr_MC2012[0]);
  gMC2012->SetMarkerStyle(kFullCircle);
  //gMC2012->SetMinimum(-10.);
  //gMC2012->SetMaximum(6.);
  gMC2012->SetLineWidth(3);
  gMC2012->SetLineColor(kGreen);
  //gMC2012->GetYaxis()->SetTitle("#DeltaA/A (%)");
  //gMC2012->GetYaxis()->CenterTitle();
  //gMC2012->GetXaxis()->SetTitle("Energy (keV)");
  //gMC2012->GetXaxis()->CenterTitle();
  //gMC2012->Draw("AC");
  
  mg->Add(gMC2011);
  mg->Add(gMC2012);
  mg->SetMinimum(-8.);
  mg->SetMaximum(6.);
  
  mg->Draw("AC");
  mg->GetYaxis()->SetTitle("#DeltaA/A (%)");
  mg->GetYaxis()->CenterTitle();
  mg->GetXaxis()->SetTitle("Energy (keV)");
  mg->GetXaxis()->CenterTitle();
  gPad->Modified();

  TLegend *leg = new TLegend(0.55,0.75,0.85,0.85);
  leg->AddEntry(gMC2011,"2011-2012","l");
  leg->AddEntry(gMC2012,"2012-2013","l");
  leg->SetTextSize(0.05);
  leg->Draw("SAME");
}
Ejemplo n.º 22
0
int LTKInkFileReader::readRawInkFile(const string& inkFile, LTKTraceGroup& traceGroup, LTKCaptureDevice& captureDevice, LTKScreenContext& screenContext)
{

    LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
                                        " Entering: LTKInkFileReader::readRawInkFile()" << endl;

    string dataLine;

    vector<string> dataVector;

    vector<float> point;				//	a point of a trace

    int pointIndex;

    if(inkFile.empty())
    {
        LOG(LTKLogger::LTK_LOGLEVEL_ERR)
                <<"Error : "<< EINKFILE_EMPTY <<":"<< getErrorMessage(EINKFILE_EMPTY)
                <<"LTKInkFileReader::readRawInkFile()" <<endl;

        LTKReturnError(EINKFILE_EMPTY);
    }

    //	opening the ink file

    ifstream infile(inkFile.c_str());

    //	checking if the file open was successful

    if(!infile)
    {
        LOG(LTKLogger::LTK_LOGLEVEL_ERR)
                <<"Error: LTKInkFileReader::readRawInkFile()"<<endl;

        LTKReturnError(EINK_FILE_OPEN);
    }

    vector<LTKChannel> channels; 				//	channels of a trace

    LTKChannel xChannel("X", DT_FLOAT, true);	//	x-coordinate channel of the trace

    LTKChannel yChannel("Y", DT_FLOAT, true);	//	y-coordinate channel of the trace

    LTKChannel tChannel("T", DT_FLOAT, true);	//	time channel of the trace

    //	initializing the channels of the trace

    channels.push_back(xChannel);

    channels.push_back(yChannel);

    channels.push_back(tChannel);

    //	composing the trace format object

    LTKTraceFormat traceFormat(channels);

    //	reading the ink file

    while(infile)
    {
        LTKTrace trace(traceFormat);

        while(infile)
        {
            getline(infile, dataLine);

            LTKStringUtil::tokenizeString(dataLine, " \t", dataVector);

            if(fabs( atof(dataVector[0].c_str()) + 1 ) < EPS)
            {
                traceGroup.addTrace(trace);

                break;
            }
            else if(fabs( atof(dataVector[0].c_str()) + 2 ) < EPS)
            {
                return SUCCESS;
            }
            else if(fabs( atof(dataVector[0].c_str()) + 6 ) < EPS)
            {
                captureDevice.setXDPI(atof(dataVector[1].c_str()));

                captureDevice.setYDPI(atof(dataVector[2].c_str()));
            }
            else if(atof(dataVector[0].c_str()) < 0)
            {
                //	unknown tag. skipping line

                continue;
            }
            else
            {

                for(pointIndex = 0; pointIndex < dataVector.size(); ++pointIndex)
                {
                    point.push_back(atof(dataVector[pointIndex].c_str()));
                }

                if(dataVector.size() == 2)
                {
                    point.push_back(0.0);
                }

                trace.addPoint(point);

                point.clear();
            }
        }
    }
    LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
                                        " Exiting: LTKInkFileReader::readRawInkFile()" << endl;

    return FAILURE;
}
Ejemplo n.º 23
0
// void sortforestCentVz(double etCut=40, char *infname = "/mnt/hadoop/cms/store/user/velicanu/forest/HiForestTrack_v3.root")
// void sortforestCentVz(double etCut=40, char *infname = "/mnt/hadoop/cms/store/user/velicanu/HIHighPt/HIRun2011_hiHighPtTrack_PromptSkim_forest_v0/9902eec616cc8b0649a7a8bb69754615/HiForest_998_1_rJ1.root")
// void sortforestCentVz(double etCut=40, char *infname = "/net/hisrv0001/home/dav2105/hdir/HIHighPt/HIRun2011_hiHighPtTrack_PromptSkim_forest_v0/9902eec616cc8b0649a7a8bb69754615/HiForest_1000_1_8wo.root")
// void sortforestCentVz(double etCut=40, char *infname = "/net/hisrv0001/home/dav2105/hdir/HIHighPt/HIRun2011_hiHighPtTrack_PromptSkim_forest_v0/9902eec616cc8b0649a7a8bb69754615/HiForest_1001_1_TRm.root")
void sortforestCentVz_dtest(int startline = 0)
{
  //! Define the input and output file and HiForest
  string buffer;
  vector<string> listoffiles;
  int nlines = 0;
  ifstream infile("/net/hidsk0001/d00/scratch/dav2105/forest/jobsort/jet80sortlist.txt");
  // ifstream infile("/net/hidsk0001/d00/scratch/dav2105/forest/jobsort/sortlist.txt");

  if (!infile.is_open()) {
    cout << "Error opening file. Exiting." << endl;
    return;
  } else {
    while (!infile.eof()) {
      infile >> buffer;
      listoffiles.push_back(buffer);
      nlines++;
    }
  }
  cout<<" here"<<endl;
  HiForest *c = new HiForest(listoffiles[startline].data());
  c->SetOutputFile(Form("sortedHiForest_%d.root",startline));

  
  //! loop through all the events once to construct the cent,vz pair array we'll be sorting over
  cout << "Constructing the cent:vz pair array..." << endl;
  for (int i=0;i<c->GetEntries();i++)
  {
    c->GetEntry(i);
    pair<int,double> centvz;
    centvz.first = c->evt.hiBin;
    centvz.second = c->evt.vz;
    evtCentVz.push_back(centvz);
    if (i%1000==0) cout <<i<<" / "<<c->GetEntries()<<" "<<c->setupOutput<<endl;
    // if (i > 1000) break;
  }
  
  //! Make the index array which will get sorted on first centrality
  int evtindecies[c->GetEntries()];
  for (int i=0;i<c->GetEntries();i++)
  {
    evtindecies[i] = i;
    // if (i > 1000) break;
	// cout << "In original loop | " << evtindecies[i] << " : (" << evtCentVz[evtindecies[i]].first <<" , "<<evtCentVz[evtindecies[i]].second << endl;
  }
  
  cout << "Sorting the cent:vz pair array..." << " "<<c->setupOutput<<endl;
  //! Sort the index array first on the centrality bin, then on the vz of the entry at that index
  qsort (evtindecies, c->GetEntries(), sizeof(int), comparecentvz);
  // qsort (evtindecies, 1000, sizeof(int), comparecentvz);
  
  //! Now fill the tree in the new order
  cout << "Filling the tree in the sorted order..." << " "<<c->setupOutput<<endl;
  for (int i=0;i<c->GetEntries();i++)
  {
    c->GetEntry(evtindecies[i]);
    c->FillOutput();
	// cout << "In fill loop | " << evtindecies[i] << " : (" << evtCentVz[evtindecies[i]].first <<" , "<<evtCentVz[evtindecies[i]].second << endl;
    if (i%1000==0) cout <<i<<" / "<<c->GetEntries()<<" "<<c->setupOutput<<endl;
    // if (i > 1000) break;
  }

  delete c;
}
Ejemplo n.º 24
0
void stdruncorr(int filenum = 0)
{


  string buffer;
  vector<string> listoffiles;
  int nlines = 0;
  ifstream infile("/net/hisrv0001/home/dav2105/corrana/makecorrhists/mcsorted.txt");

  if (!infile.is_open()) {
    cout << "Error opening file. Exiting." << endl;
    return;
  } else {
    while (!infile.eof()) {
      infile >> buffer;
      listoffiles.push_back(buffer);
      nlines++;
    }
  }

  
  cout<<"opening: "<<listoffiles[filenum].data()<<endl;
  stdcorrana(listoffiles[filenum].data());
  double leadingjetptlow[] =     {100,100,100,100,100,100,100,100,100};
  double leadingjetpthigh[] =    {120,120,120,300,300,300,300,300,300};
  double subleadingjetptlow[] =  {50 ,50 ,50 ,50 ,50 ,50 ,50 ,50 ,50 };
  double subleadingjetpthigh[] = {120,120,120,300,300,300,300,300,300};
  double ptasslow[] =            {2  ,3  ,5  ,2  ,3  ,3  ,1  ,2  ,3  };
  double ptasshigh[] =           {3  ,5  ,8  ,3  ,4  ,4  ,2  ,3  ,4  };


  int centmin[] = {0,4,12,20};
  int centmax[] = {4,12,20,40};
  
  float ajmin[] = { 0.00, 0.13, 0.24, 0.35 };
  float ajmax[] = { 0.13, 0.24, 0.35, 1.00 };
 
  
  TFile * outf = new TFile(Form("stdmcv2_%d.root",filenum),"recreate");
  
  for(int i = 0 ; i < 3 ; ++i)
  {
    cout<<"pt iteration "<<i<<endl;
    for(int cent = 0 ; cent < 4 ; ++cent)
    {
      cout<<"cent iteration "<<cent<<endl;
      for(int aj = 0 ; aj < 4 ; ++aj)
      {
        cout<<"aj iteration "<<aj<<endl;
        
        TH2D * ljtsig = JetTrackSignal    (0, leadingjetptlow[i], leadingjetpthigh[i] , subleadingjetptlow[i] , subleadingjetpthigh[i] , ptasslow[i] , ptasshigh[i], centmin[cent], centmax[cent],ajmin[aj],ajmax[aj]);
        TH2D * ljtbak = JetTrackBackground(0, leadingjetptlow[i], leadingjetpthigh[i] , subleadingjetptlow[i] , subleadingjetpthigh[i] , ptasslow[i] , ptasshigh[i], centmin[cent], centmax[cent],ajmin[aj],ajmax[aj]);
        TH2D * ljtcorr = (TH2D*)ljtsig->Clone(Form("corr_leadingjet%d_%d_ass%d_%d_cmin%d_cmax%d_ajmin%2.2f_ajmax%2.2f",(int)leadingjetptlow[i],(int)leadingjetpthigh[i],(int)ptasslow[i],(int)ptasshigh[i],centmin[cent],centmax[cent],ajmin[aj],ajmax[aj]));
        ljtcorr->Divide(ljtbak);
        ljtcorr->Scale(ljtbak->GetBinContent(ljtbak->FindBin(0,0)));
        ljtcorr->GetXaxis()->SetRange(ljtcorr->GetXaxis()->FindBin(-1.6),ljtcorr->GetXaxis()->FindBin(1.6));
        ljtcorr->GetYaxis()->SetRange(ljtcorr->GetYaxis()->FindBin(-3.1415926/2.0),ljtcorr->GetYaxis()->FindBin(3*3.1415926/2.0));
        
        TH2D * sljtsig = JetTrackSignal    (1, leadingjetptlow[i], leadingjetpthigh[i] , subleadingjetptlow[i] , subleadingjetpthigh[i] , ptasslow[i] , ptasshigh[i], centmin[cent], centmax[cent],ajmin[aj],ajmax[aj]);
        TH2D * sljtbak = JetTrackBackground(1, leadingjetptlow[i], leadingjetpthigh[i] , subleadingjetptlow[i] , subleadingjetpthigh[i] , ptasslow[i] , ptasshigh[i], centmin[cent], centmax[cent],ajmin[aj],ajmax[aj]);
        TH2D * sljtcorr = (TH2D*)sljtsig->Clone(Form("corr_subleadingjet%d_%d_ass%d_%d_cmin%d_cmax%d_ajmin%2.2f_ajmax%2.2f",(int)leadingjetptlow[i],(int)leadingjetpthigh[i],(int)ptasslow[i],(int)ptasshigh[i],centmin[cent],centmax[cent],ajmin[aj],ajmax[aj]));
        sljtcorr->Divide(sljtbak);
        sljtcorr->Scale(sljtbak->GetBinContent(sljtbak->FindBin(0,0)));
        sljtcorr->GetXaxis()->SetRange(sljtcorr->GetXaxis()->FindBin(-4.0),sljtcorr->GetXaxis()->FindBin(4.0));
        sljtcorr->GetYaxis()->SetRange(sljtcorr->GetYaxis()->FindBin(-3.1415926/2.0),sljtcorr->GetYaxis()->FindBin(3*3.1415926/2.0));
      }
    }
  }
  outf->Write();
  outf->Close();
}
Ejemplo n.º 25
0
void scanAll(TString dataFolder, TString dataType) {

  // find input files of type pla or Cu //
  TString command = "ls " + dataFolder + "/" + dataType + "*.dat > tmp/input.tmp"; 
  gSystem -> Exec(command); 

  // loop over the file and read data
  std::ifstream scanDir("input.tmp");
  string line;

  // plateaufile
  TString inFile;
  float hv,eff,shv,sff; 
  int nFile=0; 
  TGraphErrors *g[10];  

  TLegend* leg = new TLegend(0.7,0.6,0.99,0.95);
  leg->SetFillColor(kWhite);
  
  // read all the plateau files in the directory
  while( scanDir.good() ){  
    scanDir >> inFile; // = (TString)line;
    cout << inFile << endl; 
    std::string inputName = std::string(std::string(inFile));
    if(inputName.size() == 0) continue;
    char split_char = '/';
    std::vector<std::string> tokens;
    std::istringstream split(inputName);
    for(std::string each; getline(split, each, split_char); 
        tokens.push_back(each));

    split_char = '_';
    std::vector<std::string> tokens_name;
    std::istringstream split_name(tokens.at(1));
    for(std::string each; getline(split_name, each, split_char); 
        tokens_name.push_back(each));

   tokens_name.at(tokens_name.size()-1).erase(tokens_name.at(tokens_name.size()-1).size()-4,tokens_name.at(tokens_name.size()-1).size()-1);
   
   std::string LegName = tokens_name.at(0)+"_"+tokens_name.at(1)+"_"+tokens_name.at(2)+"_"+tokens_name.at(3);
  
    g[nFile] = new TGraphErrors(); 
    g[nFile] -> SetMarkerStyle(20 + (nFile%2)*4 ); 
    g[nFile] -> SetMarkerColor(kRed+1); 
    if (nFile/2==1) g[nFile] -> SetMarkerColor(kGreen+1 + (nFile%1)); 
    if (nFile/2==2) g[nFile] -> SetMarkerColor(kAzure+1 + (nFile%1)); 
    if (nFile/2==3) g[nFile] -> SetMarkerColor(kOrange+2+ (nFile%1)); 
    
  
    std::ifstream infile (inFile.Data(), std::ios::in);
    int ipt=0; 
    while ( infile.good() ) { 
      infile >> hv >> eff >> shv >> sff;
      g[nFile]->SetPoint(ipt,hv,eff); 
      g[nFile]->SetPointError(ipt,shv,sff); 
      cout << nFile << " " << ipt << " " << hv << " " << eff << endl;
      ipt++;
    }
    
    leg->AddEntry(g[nFile],LegName.c_str(),"PL");
    
    nFile++;
  }

  // do graph
  TCanvas *cc = new TCanvas("cc","cc",50.,50.,800.,500.); 
  cc -> cd();
  float xl=0.;
  float xh=15;
  TString xtit = "Absorber Thickness (X_{0})"; 
  if (dataType=="Scan") {
    xl=1200; 
    xh=3000.;
    xtit = "Bias voltage (V)"; 
  }
  if (dataType=="Cu" || dataType == "Pb") {
    xl=-1.;
    xh=15;
    xtit = "Absorber Thickness (X_{0})"; 
  }

  TH1F *hf = (TH1F*)gPad->DrawFrame(xl,0.,xh,1.2); 
  hf->GetXaxis()->SetTitle(xtit);   
  hf->GetYaxis()->SetTitle("Efficiency"); 
  for (int i=0;i<nFile;i++){
    g[i]->Draw("P"); 

  leg->Draw("same");
  }


  

}
Ejemplo n.º 26
0
void LoadOldBaseMaterial(AnsiString aFileName, TTreeView *aTreeView)
{

    ifstream infile(aFileName.c_str());

    char   buf[250];
 /// ----------------
    TTemp       CompareArray[1900];
    TTreeNode  *aParentNode = NULL;
    int         CurrentIndex = 0;
 /// ----------------

//    bool flag = false;
    bool fl1 = false;
    bool fl2 = false;
    bool fl3 = false;
//    bool fl4 = false;
//    bool fl5 = false;
//    bool fl6 = false;

      ShortString  Artikul;
      ShortString  Name;
      double       price;
//      ShortString  id;
      ShortString  Dim;

  // ---- Запалняю Триивью ----------
  TTreeNode *Node;
  aTreeView->Items->BeginUpdate();

      while (infile >> buf){
                   if (!fl1) {Artikul = buf; fl1 = true;}
             else  if (!fl2) {Name = buf; fl2 = true;}
             else  if (!fl3) {price = StrToFloat(buf); fl3 = true;}
             else  {/*if (!fl4) {fl4 = true;}
             else  if (!fl5) {fl5 = true;}
             else  if (!fl6) {fl6 = true;}
             else  { */
                     fl1 = false; fl2 = false; fl3 = false; //fl4 = false; fl5 = false; fl6 = false;
                     Dim = buf;


                 // ------------   Составляем массив из повторяющихся елементов (3 штуки) -----------
                     aParentNode = NULL;
                     bool aPresent = false;
                     for (int cc = 0; cc < CurrentIndex; cc++) {
                             if (CompareArray[cc].as[1] == Name[1] && CompareArray[cc].as[2] == Name[2] && CompareArray[cc].as[3] == Name[3]) {
                                 aPresent = true;
                                 aParentNode  = CompareArray[cc].Node;
                                 break;
                             }
                     }

                 // ------- Если нету тогда создаем новый родительский узел ---------------------
                     if (!aPresent) {
                           TElement  *Element = (TElement*) malloc (sizeof(TElement));  Element->Init();

                           Element->Id = ++GlobalMaterialCounter;
                           Element->ParentId = -1;
                           Element->Level    = 0;

                           CompareArray[CurrentIndex].as   = Name;
                           CompareArray[CurrentIndex].as.SetLength(3);
                           Element->Name                = CompareArray[CurrentIndex].as;

                           Node = aTreeView->Items->AddObject(NULL,CompareArray[CurrentIndex].as, Element);

                           CompareArray[CurrentIndex].Node = Node;
                           aParentNode = Node;

                           CurrentIndex ++;
                     }
                  // ------------

                     TElement  *Element = (TElement*) malloc (sizeof(TElement));  Element->Init();

                     for (int i = 1; i <= int(Name   [0]); i++) if (Name   [i] == '_') Name   [i] = ' ';
                     for (int i = 1; i <= int(Dim    [0]); i++) if (Dim    [i] == '_') Dim    [i] = ' ';
                     for (int i = 1; i <= int(Artikul[0]); i++) if (Artikul[i] == '_') Artikul[i] = ' ';


                     Element->GlobalElementId = ++GlobalElementID;
                     Element->Id = ++GlobalMaterialCounter;
                     Element->ParentId = (aParentNode == NULL) ? -1 : ((TElement*)aParentNode->Data)->Id;
                     Element->Level    = (aParentNode == NULL) ?  0 : 1;
                     Element->Type = etMaterial;
                     Element->Name = Name;
                     Element->Data.Price = price;
                     Element->Data.Dimension = Dim;
                     Element->Data.CatalogNumber = Artikul;

                     Node = aTreeView->Items->AddChildObject(aParentNode,Element->Name, Element);
                     Node->SelectedIndex = (aParentNode == NULL) ?  0 : 2;
                     Node->ImageIndex    = (aParentNode == NULL) ?  0 : 2;
                     Node->StateIndex    = (aParentNode == NULL) ?  0 : 2;
             }
        }

  aTreeView->Items->EndUpdate();
}
Ejemplo n.º 27
0
int main(int argc, char* argv[]) {
    std::string output_filename;

    static struct option long_options[] = {
        {"help",         no_argument, 0, 'h'},
        {"output", required_argument, 0, 'o'},
        {0, 0, 0, 0}
    };

    while (1) {
        int c = getopt_long(argc, argv, "ho:", long_options, 0);
        if (c == -1)
            break;

        switch (c) {
            case 'h':
                print_help();
                exit(return_code_ok);
            case 'o':
                output_filename = optarg;
                break;
            default:
                exit(return_code_fatal);
        }
    }

    if (output_filename.empty()) {
        std::cerr << "Missing -o/--output=OSMFILE option\n";
        exit(return_code_cmdline);
    }

    if (optind != argc - 1) {
        std::cerr << "Usage: osmcoastline_filter [OPTIONS] OSMFILE\n";
        exit(return_code_cmdline);
    }

    osmium::io::Header header;
    header.set("generator", "osmcoastline_filter");
    header.add_box(osmium::Box(-180.0, -90.0, 180.0, 90.0));

    osmium::io::File infile(argv[optind]);

    try {
        osmium::io::Writer writer(output_filename, header);

        std::set<osmium::object_id_type> ids;
        osmium::memory::Buffer output_buffer(10240);

        {
            osmium::io::Reader reader(infile, osmium::osm_entity_bits::way);
            while (auto input_buffer = reader.read()) {
                for (auto it = input_buffer.begin<const osmium::Way>(); it != input_buffer.end<const osmium::Way>(); ++it) {
                    const char* natural = it->get_value_by_key("natural");
                    if (natural && !strcmp(natural, "coastline")) {
                        output_buffer.add_item(*it);
                        output_buffer.commit();
                        if (output_buffer.committed() >= 10240) {
                            osmium::memory::Buffer new_buffer(10240);
                            std::swap(output_buffer, new_buffer);
                            writer(std::move(new_buffer));
                        }
                        for (const auto& nr : it->nodes()) {
                            ids.insert(nr.ref());
                        }
                    }
                }
            }
            reader.close();
        }

        {
            osmium::io::Reader reader(infile, osmium::osm_entity_bits::node);
            while (auto input_buffer = reader.read()) {
                for (auto it = input_buffer.begin<const osmium::Node>(); it != input_buffer.end<const osmium::Node>(); ++it) {
                    const char* natural = it->get_value_by_key("natural");
                    if ((ids.find(it->id()) != ids.end()) || (natural && !strcmp(natural, "coastline"))) {
                        output_buffer.add_item(*it);
                        output_buffer.commit();
                        if (output_buffer.committed() >= 10240) {
                            osmium::memory::Buffer new_buffer(10240);
                            std::swap(output_buffer, new_buffer);
                            writer(std::move(new_buffer));
                        }
                    }
                }
            }
            reader.close();
        }

        if (output_buffer.committed() > 0) {
            writer(std::move(output_buffer));
        }

        writer.close();
    } catch (osmium::io_error& e) {
        std::cerr << "io error: " << e.what() << "'\n";
        exit(return_code_fatal);
    }

    google::protobuf::ShutdownProtobufLibrary();
}
Ejemplo n.º 28
0
/**
 * \brief Main function in astro namespace
 */
int	main(int argc, char *argv[]) {
	int	c;
	const char	*darkfilename = NULL;
	const char	*flatfilename = NULL;
	double	minvalue = -1;
	double	maxvalue = -1;
	bool	demosaic = false;
	bool	interpolate = false;

	// parse the command line
	while (EOF != (c = getopt(argc, argv, "dD:F:?hm:M:bi")))
		switch (c) {
		case 'd':
			debuglevel = LOG_DEBUG;
			break;
		case 'D':
			darkfilename = optarg;
			break;
		case 'F':
			flatfilename = optarg;
			break;
		case 'm':
			minvalue = atof(optarg);
			break;
		case 'M':
			maxvalue = atof(optarg);
			break;
		case 'b':
			demosaic = true;
			break;
		case 'i':
			interpolate = true;
			break;
		case '?':
		case 'h':
			usage(argv[0]);
			return EXIT_SUCCESS;
			break;
		}

	// two more arguments are required: infile and outfile
	if (2 != argc - optind) {
		std::string	msg("wrong number of arguments");
		debug(LOG_ERR, DEBUG_LOG, 0, "%s", msg.c_str());
		throw std::runtime_error(msg);
	}
	std::string	infilename(argv[optind++]);
	std::string	outfilename(argv[optind]);
	debug(LOG_DEBUG, DEBUG_LOG, 0, "calibrate %s to %s",
		infilename.c_str(), outfilename.c_str());

	// read the infile
	FITSin	infile(infilename);
	ImagePtr	image = infile.read();

	// build the Imager
	Imager	imager;

	// if we have a dark correction, apply it
	ImagePtr	dark;
	if (NULL != darkfilename) {
		debug(LOG_DEBUG, DEBUG_LOG, 0, "dark correct: %s",
			darkfilename);
		FITSin	darkin(darkfilename);
		dark = darkin.read();
		imager.dark(dark);
		imager.darksubtract(true);
	}

	// if we have a flat file, we perform flat correction
	if (NULL != flatfilename) {
		debug(LOG_DEBUG, DEBUG_LOG, 0, "flat correction: %s",
			flatfilename);
		FITSin	flatin(flatfilename);
		ImagePtr	flat = flatin.read();
		imager.flat(flat);
		imager.flatdivide(true);
	}

	// perform bad pixel interpolation
	if (interpolate) {
		imager.interpolate(true);
	}

	// apply imager corrections
	imager(image);

	// if minvalue or maxvalue are set, clamp the image values
	if ((minvalue >= 0) || (maxvalue >= 0)) {
		if (minvalue < 0) {
			minvalue = 0;
		}
		if (maxvalue < 0) {
			maxvalue = std::numeric_limits<double>::infinity();
		}
		Clamper	clamp(minvalue, maxvalue);
		clamp(image);
	}

	// after all the calibrations have been performed, write the output
	// file
	FITSout	outfile(outfilename);

	// if demosaic is requested we do that now
	if (demosaic) {
		ImagePtr	demosaiced = demosaic_bilinear(image);
		outfile.write(demosaiced);
	} else {
		outfile.write(image);
	}

	// that's it
	return EXIT_SUCCESS;
}
Ejemplo n.º 29
0
int main(int argc, char** argv)
{
	//setting up default values
	width=DEFAULT_WIDTH;
	heigth=DEFAULT_HEIGTH;
	input_topic=DEFAULT_INPUT_TOPIC;
	output_topic=DEFAULT_OUTPUT_TOPIC;
	head_controller_topic=DEFAULT_HEAD_TOPIC;
	sampling_rate=RATE;
        //reading the configuration
	std::string path=ros::package::getPath("accompany_siena_images_republisher")+"/config/config.txt";
	//std::cout << path << "\n";
	
	std::ifstream infile(path.c_str());

	std::string param,value;
	while(infile >> param >> value)
	{
		//std::cout << "param: " << param << ", value: " << value <<"\n";
		if (param=="cob_version")
		{
			/*const char * c_val=value.c_str();
			if (strcmp(c_val,"cob3-6")==0||strcmp(c_val,"cob_3_6")==0||strcmp(c_val,"cob3_6")==0||strcmp(c_val,"cob-3-6")==0) cob_version==COB_3_6;
			if (strcmp(c_val,"cob3-2")==0||strcmp(c_val,"cob_3_2")==0||strcmp(c_val,"cob3_2")==0||strcmp(c_val,"cob-3-2")==0) cob_version==COB_3_2;
			printf("tmp cob version: %s\n",c_val);*/
			if (value=="cob3-6"||value=="cob_3_6"||value=="cob3-6"||value=="cob-3-6") cob_version=COB_3_6;
			if (value=="cob3-2"||value=="cob_3_2"||value=="cob3-2"||value=="cob-3-2") cob_version=COB_3_2;
		}
		if (param=="image_width")
		{
			sscanf(value.c_str(), "%d", &width);
		}
		if (param=="image_heigth")
		{	
			sscanf(value.c_str(), "%d", &heigth);
		}
		if (param=="input_topic")
		{
			input_topic=value;
		}
		if (param=="output_topic")
		{
			output_topic=value;
		}
		if (param=="head_downsampled_control_topic")
		{
			head_controller_topic=value;
		}
		if (param=="sampling_rate")
		{
			sscanf(value.c_str(), "%d", &sampling_rate);
		}
	}
	if (cob_version== COB_3_6)		
		std::cout <<"Cob version: cob 3-6\n";
	else
		std::cout <<"Cob version: cob 3-2\n";
	std::cout <<"Width:" <<width <<", Heigth:"<<heigth<<"\n";
	std::cout <<"Input topic: " <<input_topic<<"\n";
	std::cout <<"Output topic: " <<output_topic<<"\n";
	std::cout <<"Head Controller topic: " <<head_controller_topic<<"\n";
	std::cout <<"Sampling rate: "<<sampling_rate<<"\n";

	//computing (here -> only once!) pivot point coords:
	half_width=(int)width/2;
	half_heigth=(int)heigth/2;
	std::cout <<"HalfWidth:" <<half_width <<", HalfHeigth:"<<half_heigth<<"\n";
	
	ros::init(argc,argv,"Accompany_Republisher");
	ros::NodeHandle nh;
	
	image_transport::ImageTransport it2(nh);
	image_transport::Subscriber sub = it2.subscribe(input_topic, 1, image_callback);


	image_transport::ImageTransport it(nh);
	pub = it.advertise(output_topic,1);

	//Subscribing head position:
	ros::Subscriber head_sub=nh.subscribe(head_controller_topic,1,head_callback);
	
	std::cout <<"\n\n";
	std::cout << "Remapping topic \"" <<input_topic << "\" on \"" << output_topic <<"\"\n";
        std::cout << "Downsizing images to "<<width<<"x"<<heigth<<"\n";
	std::cout << "Cutting image frequency with "<<sampling_rate <<" ratio.\n";
	std::cout << "Images Republisher started...\n"	;

	//try to get robot version from environment
	try{
		std::cout << "Running robot: " << getenv("ROBOT") << "\n";
		std::string cob_run = getenv("ROBOT");
		if (cob_run=="cob3-2") cob_version=COB_3_2;
		if (cob_run=="cob3-6") cob_version=COB_3_6;
	}catch(const std::exception e)
	{
		std::cout << "Exception retriving running robot version: " << e.what() << "\n"; 
	}
	catch(...)
	{
		std::cout << "Generic exception retriving runninbg robot version: unknown.\n";
	}

	ros::spin();
	/*ros::Rate loop_rate(0.2);
	while (nh.ok())
	{
		if (last_img!= NULL) 
		{
			printf("**\n");
			sensor_msgs::ImagePtr msg = sensor_msgs::CvBridge::cvToImgMsg(last_img,"bgr8");
			pub.publish(msg);
			ros::spinOnce();
			loop_rate.sleep();
		}
	}*/
 	//cvReleaseImage(&last_img);
        
}
void MultiLabelImageDataLayer<Dtype>::DataLayerSetUp(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top) {

 const int new_height = this->layer_param_.image_data_param().new_height();
  const int new_width  = this->layer_param_.image_data_param().new_width();
  const bool is_color  = this->layer_param_.image_data_param().is_color();
  string root_folder = this->layer_param_.image_data_param().root_folder();


  CHECK(this->phase_ == TEST) << "Sorry, currently, the layer is designed only for TEST phase";

  CHECK((new_height == 0 && new_width == 0) ||
      (new_height > 0 && new_width > 0)) << "Current implementation requires "
      "new_height and new_width to be set at the same time.";
  // Read the file with filenames and labels
  const string& source = this->layer_param_.image_data_param().source();
  LOG(INFO) << "Opening file " << source;
  std::ifstream infile(source.c_str());
  string filename;

  LOG(INFO) << "Now start opening the image source file";

  char temp_str[1000];
  while (infile.getline(temp_str, 1000)) {

    char* pch;
    pch =strtok(temp_str, " ");
    if(pch == NULL){
      continue;
    }

    lines_.push_back(string(pch));
    vector<int> temp_labels;
    pch = strtok(NULL, " ");
    while(pch != NULL){
      int label = atoi(pch);
      temp_labels.push_back(label);
      pch = strtok(NULL, " ");
    }
    labels_.push_back(temp_labels);
  }
  LOG(INFO) << "Finish reading image sources.";
  if (this->layer_param_.image_data_param().shuffle()) {
    // randomly shuffle data
    LOG(INFO) << "Shuffling data";
    const unsigned int prefetch_rng_seed = caffe_rng_rand();
    prefetch_rng_.reset(new Caffe::RNG(prefetch_rng_seed));
    ShuffleImages();
  }
  LOG(INFO) << "A total of " << lines_.size() << " images.";

  lines_id_ = 0;
  // Check if we would need to randomly skip a few data points
  if (this->layer_param_.image_data_param().rand_skip()) {
    unsigned int skip = caffe_rng_rand() %
        this->layer_param_.image_data_param().rand_skip();
    LOG(INFO) << "Skipping first " << skip << " data points.";
    CHECK_GT(lines_.size(), skip) << "Not enough points to skip";
    lines_id_ = skip;
  }
  // Read an image, and use it to initialize the top blob.
  LOG(INFO) << "Start reading images";
  cv::Mat cv_img = ReadImageToCVMat(root_folder + lines_[lines_id_],
                                    new_height, new_width, is_color);
  // Use data_transformer to infer the expected blob shape from a cv_image.

  LOG(INFO) << "Finish reading images.   Start transforming according to the settings";
  vector<int> top_shape = this->data_transformer_->InferBlobShape(cv_img);
  this->transformed_data_.Reshape(top_shape);


  LOG(INFO) << "Tranformation finished.   Start reshaping";

  // Reshape prefetch_data and top[0] according to the batch_size.
  const int batch_size = this->layer_param_.image_data_param().batch_size();
  top_shape[0] = batch_size;
  this->prefetch_data_.Reshape(top_shape);
  top[0]->ReshapeLike(this->prefetch_data_);
  #ifdef _DEBUG_YKLI_
    for(int i = 0; i < top_shape.size(); i ++){
      LOG(INFO) << "top_shape's size: ["<<i<<"]: "<<top_shape[i];
    }
  #endif

  LOG(INFO) << "output data size: " << top[0]->num() << ","
      << top[0]->channels() << "," << top[0]->height() << ","
      << top[0]->width();
  // label


  int max_label_num_ = this->layer_param_.image_data_param().max_label();
  vector<int> label_shape(2);
  label_shape[0] = batch_size;
  label_shape[1] = max_label_num_+1;
  #ifdef _DEBUG_YKLI_
    for(int i = 0; i < label_shape.size(); i ++){
      LOG(INFO) << "label_shape's size: ["<<i<<"]: "<<label_shape[i];
    }
  #endif
  top[1]->Reshape(label_shape);
  this->prefetch_label_.Reshape(label_shape);
}