コード例 #1
0
	int run(int round, bool tracking, bool skipUntracked) {
		runge_kutta_dopri5<Phase> stepper;
		auto ctrdStepper = make_controlled(absoluteStepperError, relativeStepperError, stepper);
		Simulator<decltype(ctrdStepper)> simulator(ctrdStepper, &bbsystem);

		uniform_real_distribution<double> distributionNullB2Max(0, b2max);
		double b = sqrt(distributionNullB2Max(randomEngine));

		hydrogen->randomize(randomEngine);
		hydrogen->setPosition(vector3D(0, 0, 0));
		hydrogen->setVelocity(vector3D(0, 0, 0));

		bbsystem.setBodyPosition(projectile, vector3D(0, b, -50.0));
		bbsystem.setBodyVelocity(projectile, vector3D(0, 0, projectileVelocity));

		if (skipUntracked && !tracking) {
			return 0;
		}

		stream << bbsystem.phase;
		stream.flush();

		if (tracking) {
			printer = new Printer(to_string(round) + ".csv");
			printer->addField(&printField);
			simulator.setObserver(*printer);
		}

		if (condition->evaluate(bbsystem.phase, 0)) {
			stream << "\t" << "Initial condition error" << endl;
			return -3;
		}

		double energy = bbsystem.getSystemEnergy();
		double time = simulator.simulate(0.0, 1.0, 0.0001, *condition, 100);
		bool eBoundToTarget;
		bool eBoundToProjec;

		while (true) {

			if (time < 0.0) {
				stream << "\t" << "Distance not reached error" << endl;
				return -1;
			}

			if (abs((energy - bbsystem.getSystemEnergy()) / energy) > relativeEnergyError) {
				stream << "\t" << "Energy error: " << energy << " vs. " << bbsystem.getSystemEnergy() << endl;
				return -2;
			}

			eBoundToTarget = Utils::isBound(bbsystem, hydrogen->getElectron("1s1"), hydrogen->getNucleus());
			eBoundToProjec = Utils::isBound(bbsystem, hydrogen->getElectron("1s1"), projectile);

			if (!eBoundToTarget || !eBoundToProjec) {
				break;
			}

			stream << " " << round << " Extend Run";
			simulator.simulate(time, time + 1.0, 0.0001);
			time += 1.0;
			extended++;
		}

		if (eBoundToTarget && !eBoundToProjec) {
			stream << endl;
		}

		if (!eBoundToTarget && eBoundToProjec) {
			stream << "\t" << round << " --> Electron Capture" << endl;
			ecapture++;
		}

		if (!eBoundToTarget && !eBoundToProjec) {
			stream << "\t" << round << " --> Ionization" << endl;
			ionization++;
		}

		if (printer != nullptr)
			delete printer;

		stream.flush();
		return 0;
	}
コード例 #2
0
ファイル: preprocessCorpus.cpp プロジェクト: Geekking/lima
void doClActionOnOpeningString(
    std::string::const_iterator& start,
    std::string::const_iterator& end,
    boost::match_flag_type& flags,
    int& offset,
    ofstream& fout,
    std::string& np    )
{
  LIMA_UNUSED(np);
  CorefsMap CMap;
  deque<std::string>* ids = new deque<std::string>();
  deque<std::string>* nps = new deque<std::string>();
  deque<uint64_t>* npBegins = new deque<uint64_t>();
  deque<uint64_t>* npEnds = new deque<uint64_t>();

  while(true)
  {
    match_results<std::string::const_iterator> what;
    match_results<std::string::const_iterator> what1;
    match_results<std::string::const_iterator> what2;
    match_results<std::string::const_iterator> what3;

    regex_search(start, end, what1, eClBeginTag, flags);
    regex_search(start, end, what2, eClLinkBeginTag, flags);
    regex_search(start, end, what3, eClStop, flags);

    // if next is <RS ...>
    if (what1[0]!="" && what3[0] != "" && what1[0].first<what3[0].first)
    {   
      string internNp("");
      doRsTag(start, end, what1, flags, offset, ids, nps, npBegins, npEnds, internNp);
    }
    // if next is <LINK ...>
    else if (what2[0]!="" && what3[0] != "" && what2[0].first<what3[0].first)
    {
      if (string(what2[2].first,what2[2].second)=="COREF"||string(what2[2].first,what2[2].second)=="IDSEM") 
      {
        // extraction de la reference la plus à gauche
        regex_search(what2[0].first,what2[0].second,what,eClLinkExtract, flags);
        stringstream sstream;
        std::string ref = string(what[1].first,what[1].second);
        match_results<std::string::const_iterator> whatCompAnte;
        match_results<std::string::const_iterator> whatCompAna;
        regex_search(what[1].first,what[1].second, whatCompAnte, regex("([[:digit:]]+)\\.[[:digit:]]+"));
        // extraction de la référence la plus à droite
        // et inscription dans la map
//         cerr<<string(what[0].second, what2[0].second)<<endl;;
        sstream << cpt;
        
        while(regex_search(what[0].second, what2[0].second,what, eClLinkExtract, flags))        
        {
          what1 = what;
        }
        regex_search(what1[1].first,what1[1].second,whatCompAna,regex("([[:digit:]]+)\\.[[:digit:]]+"));
        // Renumérotation. Exemples :
        // si id = 12.4 et ref = 12.3
        // alors => id = 118.12.4 et ref = 118.12.3
        // si id = 12.4 et ref = 10.3
        // alors => id = 118.12.4 et ref = 116.10.3
        stringstream sstream2;
        sstream2 << cpt-
          (atoi(const_cast<char*>(string(whatCompAna[1].first,whatCompAna[1].second).c_str()))
          -atoi(const_cast<char*>(string(whatCompAnte[1].first,whatCompAnte[1].second).c_str())));
          CMap.insert(make_pair(sstream.str() + "." + string(what1[1].first,what1[1].second),sstream2.str() + "." +ref));

//         // extraction des autres références (de gauche à droite)
//         // et inscription dans la map 
// n'est pas valide !! quand 3 membres dans balise link il ne s'agit pas d une chaine de coreferences mais de l'entité la plus à droite qui réfèrent aux deux autres à la fois.
// //         cerr<<string(what[0].second, what2[0].second)<<endl;;
//         sstream << cpt;
//         while(regex_search(what[0].second, what2[0].second,what, eClLinkExtract, flags))        
//         {
//           regex_search(what[1].first,what[1].second,whatCompAna,regex("([[:digit:]]+)\\.[[:digit:]]+"));
//           // Renumérotation. Exemples :
//           // si id = 12.4 et ref = 12.3
//           // alors => id = 118.12.4 et ref = 118.12.3
//           // si id = 12.4 et ref = 10.3
//           // alors => id = 118.12.4 et ref = 116.10.3
//           stringstream sstream2;
//           sstream2 << cpt-
//             (atoi(const_cast<char*>(string(whatCompAna[1].first,whatCompAna[1].second).c_str()))
//             -atoi(const_cast<char*>(string(whatCompAnte[1].first,whatCompAnte[1].second).c_str())));
//             CMap.insert(make_pair(sstream.str() + "." + string(what[1].first,what[1].second),sstream2.str() + "." +ref));
// //             cerr << sstream.str() + "." + string(what[1].first,what[1].second) << " - " << sstream2.str() + "." +ref << endl;
//           
// //  cerr<<string(what[0].second, what2[0].second)<<endl;;
//         }
      }
        offset+= what2[0].first-start;
        start = what2[0].second;
    }
    // if next is </P>
    else
    {
      while (!ids->empty())
      {
        std::string ref;
        if (CMap.find(*ids->begin())!=CMap.end())
          ref = (*CMap.find(*ids->begin())).second;
        else ref = "";
        // write on ofstream
        fout << *ids->begin() << ";";
        fout << ref << ";" ;
        fout << *npBegins->begin() << ";";
        fout << *npEnds->begin() << ";";
        fout << *nps->begin() << ";" << endl;
        ids->pop_front();
        npBegins->pop_front();
        npEnds->pop_front();
        nps->pop_front();
      }
      offset += what3[0].first-start;
      start = what3[0].second;
      fout.flush();
      return;
    }
  }
}
コード例 #3
0
ファイル: file_appender.cpp プロジェクト: BestSilent/eos
         void rotate_files( bool initializing = false )
         {
             FC_ASSERT( cfg.rotate );
             fc::time_point now = time_point::now();
             fc::time_point_sec start_time = get_file_start_time( now, cfg.rotation_interval );
             string timestamp_string = start_time.to_non_delimited_iso_string();
             fc::path link_filename = cfg.filename;
             fc::path log_filename = link_filename.parent_path() / (link_filename.filename().string() + "." + timestamp_string);

             {
               fc::scoped_lock<boost::mutex> lock( slock );

               if( !initializing )
               {
                   if( start_time <= _current_file_start_time )
                   {
                       _rotation_task = schedule( [this]() { rotate_files(); },
                                                  _current_file_start_time + cfg.rotation_interval.to_seconds(),
                                                  "rotate_files(2)" );
                       return;
                   }

                   out.flush();
                   out.close();
               }
               remove_all(link_filename);  // on windows, you can't delete the link while the underlying file is opened for writing
               if( fc::exists( log_filename ) )
                  out.open( log_filename, std::ios_base::out | std::ios_base::app );
               else
                  out.open( log_filename, std::ios_base::out | std::ios_base::app);

               create_hard_link(log_filename, link_filename);
             }

             /* Delete old log files */
             fc::time_point limit_time = now - cfg.rotation_limit;
             string link_filename_string = link_filename.filename().string();
             directory_iterator itr(link_filename.parent_path());
             for( ; itr != directory_iterator(); itr++ )
             {
                 try
                 {
                     string current_filename = itr->filename().string();
                     if (current_filename.compare(0, link_filename_string.size(), link_filename_string) != 0 ||
                         current_filename.size() <= link_filename_string.size() + 1)
                       continue;
                     string current_timestamp_str = current_filename.substr(link_filename_string.size() + 1,
                                                                            timestamp_string.size());
                     fc::time_point_sec current_timestamp = fc::time_point_sec::from_iso_string( current_timestamp_str );
                     if( current_timestamp < start_time )
                     {
                         if( current_timestamp < limit_time || file_size( current_filename ) <= 0 )
                         {
                             remove_all( *itr );
                             continue;
                         }
                     }
                 }
                 catch (const fc::canceled_exception&)
                 {
                     throw;
                 }
                 catch( ... )
                 {
                 }
             }

             _current_file_start_time = start_time;
             _rotation_task = schedule( [this]() { rotate_files(); },
                                        _current_file_start_time + cfg.rotation_interval.to_seconds(),
                                        "rotate_files(3)" );
         }
コード例 #4
0
void MyController::onInit(InitEvent &evt) {  

  // handle of target and tool
  SimObj *target = getObj(myname());
  SimObj *toolName = getObj(myname());

  toolName->setMass(10.0); // mass of all the tools should be set uniformly
  
  target->getPosition(initTargetPos);  // initial target position
  target->getRotation(initTargetRotation); // initial target rotation in quaternion

  toolName->getPosition(initToolPos);  // initial tool position
  toolName->getRotation(initToolRotation); // initial tool rotation in quaternion

  isTargetAtRest = true;     // target and tool both are at rest initially.
  isToolAtRest = true;  
  insideTimer = true; 
  f_x = 0 ;
  f_z = 0 ;

  int xForceVariance = 4000;
  int zForceVariance = 4000;

  flag = true;
  Colli = false; 
  counterOfCollision = 0; 
  counterOfAction = 0; 


  // Reset the forces applied
  double r;
  r = ((double) rand() / (RAND_MAX)) ;
  f_x = r * int(xForceVariance);
  f_z = r * int(zForceVariance);

  forceOnTool_z = 8000 + f_z;
  forceOnTool_x = 0;

  forceOnTool.set(forceOnTool_x, 0 , forceOnTool_z);

  toolName->addForce(forceOnTool.x(), forceOnTool.y(), forceOnTool.z());
  toolName->getVelocity(appliedToolVel);


  myfile.flush(); // I have uncommented the file, because I want to overwrite the file.
  



//   if (myfile.is_open())
//   {
//      myfile << "toolVelAtHit_X" << " , " << "toolVelAtHit_Z" << " , ";  
//      myfile <<  "targetInitialVel_X" << " , " << "targetInitialVel_Z"  << " , ";
//      myfile << "Action" << " , " << "FunctionalFeature" << " , " ;
//      myfile << "forceOnTool_X" << " , " << "forceOnTool_Z " <<  " , ";
//      myfile << "InitialToolPos_X" << " , " << "InitialToolPos_Z" << " , ";
//      myfile << "InitialTargetPos_X" << " , " << "InitialTargetPos_Z" << " , ";
//      myfile <<  "targetFinalPos_X" << " , " << "targetFinalPos_Z"  << " , ";
//      myfile << "targetDisplacement_X" << " , " << "targetDisplacement_Z";
//      myfile <<  "\n" ;

// }


}  
コード例 #5
0
/**
Writes the boot sector of a FAT 32 volume

@internalComponent
@released

@param aOutPutStream handle for the image file
*/
void CFat32FileSystem::WriteBootSector(ofstream& aOutPutStream)
{
	MessageHandler::ReportMessage (INFORMATION,BOOTSECTORWRITEMSG,"FAT32");
	aOutPutStream.write(reinterpret_cast<char*>(&iData[0]),iFAT32BootSector.BytesPerSector());
	aOutPutStream.flush();
}
コード例 #6
0
void ApiLogger::CloseLogFile() 
{
    logfile.flush();
    logfile.close();
}
コード例 #7
0
ファイル: final_ekf.cpp プロジェクト: hildingur/filtering
int main(int argc, char** argv) {
	
	srand(time(NULL)); //seed the random number generator

	vector<double> prices;
	string input_file_name, parameter_file_name = "", residual_file_name = "";
	
	parse_args(argc, argv,
		input_file_name,
		parameter_file_name,
		residual_file_name);

	//setting cout to show 10 decimal places by default
	std::cout.setf(ios::fixed);
	std::cout<<setprecision(10); 

	read_lines(input_file_name, prices);
	cout<<"Found "<<prices.size()<<" prices"<<endl;
	
	n_stock_prices = prices.size();

	log_stock_prices = new double[n_stock_prices];
	u = new double[n_stock_prices];
	v = new double[n_stock_prices];
	estimates = new double[n_stock_prices + 1];

	for(unsigned int i = 0; i < prices.size(); i++) {
		log_stock_prices[i] = log(prices[i]);
	}

	//param variables are
	vol_params current_params(0.02, //omega
		1.00,  //theta
		0.50, //xi
		-0.20, //rho
		1.00,  //p
		pow(10.00, 6), //mle
		pow(10.00, 6), //chi2
		pow(10.00, 6), //kalman_chi2
		pow(10.00, 6) //(mean) adjusted_kalman_chi2 
		); 
	vol_params best_params(current_params);
	
	Vec_IO_DP* start_;
	
	Mat_IO_DP* identity_matrix;

	if(model!=VAR_P) //if we aren't trying to estimate p, we only need a 4x4 matrix
	{
		//Initializing the starting point
		start_ = new Vec_IO_DP(4);
		identity_matrix = new Mat_IO_DP(4, 4);
	} else { //we are trying to estimate p, so we want a 5x5 matrix
		//Initializing the starting point
		start_ = new Vec_IO_DP(5);
		identity_matrix = new Mat_IO_DP(5, 5);
	}

	Vec_IO_DP& start = *start_; //aliasing the pointer for easy reference
	
	paramter_file.open(parameter_file_name.c_str());
	residual_file.open(residual_file_name.c_str());
	//setting the output to 10 decimal places
	paramter_file.setf(ios::fixed);
	paramter_file<<setprecision(10);
	residual_file.setf(ios::fixed);
	residual_file<<setprecision(10);

	double* classic_residuals = new double[prices.size()];
	double* kalman_residuals = new double[prices.size()];
	double* corrected_kalman_residuals = new double[prices.size()];

	double chi2; //buffer variable.
	
	while(simulation_counter <= max_simulations)
	{
		int nvars = (model!=VAR_P) ? 4 : 5; 
		for(int i = 0; i < nvars; i++) 
		{
			for(int j = 0; j < nvars; j++)
			{
				(*identity_matrix)[i][j] = (i==j) ? 1 : 0;
			}
		}

		current_params.populate_starting_vector(start);
		for(int i = 0; i < 5; i++)
			cout<<start[i]<<endl;

		int iter;
		DP mle = 0.00;
		
		NR::powell(start, *identity_matrix, ftol, iter, mle, minimize_target_ekf);
		
		if(model==VAR_P)
			cout<<" p = "<<current_params.get_p();
		cout<<endl<<endl;

		/*
		* Setting the current params out of the optimizations.
		*/
		current_params.extract_params_from_vector(start);
		current_params.set_mle(mle);

		build_classic_residuals(prices, estimates, classic_residuals);
        build_kalman_residuals(prices, estimates, v, kalman_residuals);
        build_mean_corrected_kalman_residuals(prices, estimates, u, v, corrected_kalman_residuals);
		//getting the chi2 statistic for the classic residuals
		is_normal(classic_residuals, true, prices.size(), chi2); current_params.set_chi2(chi2);
		is_normal(kalman_residuals, true, prices.size(), chi2); current_params.set_kalman_chi2(chi2);
		is_normal(corrected_kalman_residuals, true, prices.size(), chi2); current_params.set_adjusted_kalman_chi2(chi2);

		if(runmode == NORMAL_RESIDUALS) 
		{
			bool solution_improved = false;

			//if(best_params.get_mle() > mle)a
			if(best_params.get_kalman_chi2() > current_params.get_kalman_chi2())
			//if(best_params.get_mle() > mle && best_params.get_kalman_chi2() > current_params.get_kalman_chi2())
			{
				solution_improved = true;
				mark_better_parameters(simulation_counter, 
					max_simulations, 
					best_params, 
					current_params, 
					log_file, 
					prices.size());
			} 
			else 
			{
				log_file<<"We have NOT found better parameters on simulation # "<<simulation_counter << " out of "<< max_simulations <<endl
					<<"-- new mle                       = "<< current_params.get_mle()  <<" old = "<<best_params.get_mle()<<endl
					<<"-- new chi2                      = "<<current_params.get_chi2() <<" old = "<<best_params.get_chi2()<<endl
					<<"-- new kalman chi2               = "<<current_params.get_kalman_chi2()<<" old = "<<best_params.get_kalman_chi2()<<endl
					<<"-- new mean adjusted kalman chi2 = "<<current_params.get_adjusted_kalman_chi2()<<" old = "<<best_params.get_adjusted_kalman_chi2()<<endl
					<<"-- Resetting the parameters to the previous best estimate, and then preturbing..."<<endl;
				current_params.copy_params(best_params);
			}

				
			current_params.set_omega(abs(gaussrand() * sqrt(2.00) + best_params.get_omega()));
			current_params.set_theta(abs(gaussrand() * sqrt(2.00) + best_params.get_theta()));
			current_params.set_xi(abs(gaussrand() * sqrt(2.00) + best_params.get_xi()));
			current_params.set_roe(((rand()/rand_max) * 2.00) - 1.00);
			current_params.set_p(abs(((double)rand())/rand_max) + 0.5); 

			log_file<<"old omega "<<best_params.get_omega()
				<<" new -> "<<current_params.get_omega()
				<<" diff= "<<best_params.get_omega() - current_params.get_omega()<<endl;
			log_file<<"old theta "<<best_params.get_theta()
				<<" new-> "<<current_params.get_theta()
				<<" diff= "<<best_params.get_theta() - current_params.get_theta()<<endl;
			log_file<<"old xi    "<<best_params.get_xi()   
				<<" new-> "<<current_params.get_xi()
				<<" diff= "<<best_params.get_xi() - current_params.get_xi()<<endl;
			log_file<<"old rho   "<<best_params.get_roe()  
				<<" new-> "<<current_params.get_roe()
				<<" diff= "<<best_params.get_roe() - current_params.get_roe()<<endl;
			if(model==VAR_P)
				log_file<<"old p     "<<best_params.get_p()
					<<" new-> "<<current_params.get_p()<<" diff= "
					<<best_params.get_p() - current_params.get_p()<<endl;

			log_file<<endl<<endl<<endl;


			call_counter = 0;
			
		} 
		
		simulation_counter++;
		paramter_file.flush(); //flush the buffer to disc
	}

	residual_file<<"LineNum"<<","
		<<"Prices"<<","
		<<"Estimates"<<","
		<<"ClassicResidual"<<","
		<<"KalmanResidual"<<","
		<<"CorrectedKalmanResidual"<<endl;
	if(runmode==SIMPLE) {
		log_file<<"Optimum values are "<<endl
			<<"--omega "<<current_params.get_omega()<<endl
			<<"--theta "<<current_params.get_theta()<<endl
			<<"--roe   "<<current_params.get_roe()<<endl
			<<"--xi    "<<current_params.get_xi()<<endl;
		if(model==VAR_P)
			log_file<<"--p     "<<current_params.get_p()<<endl;
		for(unsigned int i = 0; i < prices.size(); i++) {
			residual_file<<i<<"."<<prices[i]<<","<<exp(estimates[i])<<","
				<<classic_residuals[i]<<","
				<<kalman_residuals[i]<<","
				<<corrected_kalman_residuals[i]<<","
				<<endl;
		}
	} else {
		//need to build the residuals again.
		build_classic_residuals(prices, 
			best_params.get_estimates(), 
			classic_residuals);
                build_kalman_residuals(prices, 
			best_params.get_estimates(), 
			best_params.get_v(), 
			kalman_residuals);
                build_mean_corrected_kalman_residuals(prices, 
			best_params.get_estimates(), 
			best_params.get_u(), 
			best_params.get_v(), 
			corrected_kalman_residuals);

		log_file<<"Optimum values are "<<endl
			<<"--omega "<<best_params.get_omega()<<endl
			<<"--theta "<<best_params.get_theta()<<endl
			<<"--roe   "<<best_params.get_roe()<<endl
			<<"--xi    "<<best_params.get_xi()<<endl;
		if(model==VAR_P)
			log_file<<"--p     "<<best_params.get_p()<<endl;
		for(unsigned int i = 0; i < prices.size(); i++) {
			residual_file<<i<<","<<prices[i]<<","
				<<exp(estimates[i])<<","
				<<classic_residuals[i]<<","
                                <<kalman_residuals[i]<<","
                                <<corrected_kalman_residuals[i]<<","
                                <<endl;
		}
	}

	log_stats(log_file,
		classic_residuals,
		kalman_residuals,
		corrected_kalman_residuals,
		prices.size());

	residual_file.close();
	paramter_file.close();

	delete[] log_stock_prices, u, v, estimates, classic_residuals, kalman_residuals, corrected_kalman_residuals;
	delete start_, identity_matrix;
	/*
	cout<<"Press any key to continue"<<endl;
	cin.get();
	*/
	return 0;
}
コード例 #8
0
void MyController::onInit(InitEvent &evt) {  

 
  SimObj *target = getObj("box_015");
  SimObj *toolName = getObj("TShapeTool_015");


  toolName->setMass(10.0);
  
  target->getPosition(initTargetPos);
  target->getRotation(initTargetRotation);

  toolName->getPosition(initToolPos);
  toolName->getRotation(initToolRotation);

  isTargetAtRest = true;   
  isToolAtRest = true;  
  f_x = 0 ;
  f_z = 0 ;

  int xForceVariance = 2000;
  int zForceVariance = 2000;


  // Reset the forces applied
  double r;
  r = ((double) rand() / (RAND_MAX)) ;
  f_x = r * int(xForceVariance);
  f_z = r * int(zForceVariance);

  flag = true;
  Colli = false; 
  counter = 0; 

  forceOnTool_x = 5000 + f_z;
  forceOnTool_z = 5000 + f_z;

  // cout << "The applied force " << forceOnTool_x <<  " , " << forceOnTool_z << endl;


  forceOnTool.set(forceOnTool_x, 0 , forceOnTool_z);
  tapWithTool(toolName, initToolRotation, forceOnTool);

  myfile.flush(); // I have uncommented the file, because I want to overwrite the file. 


//   if (myfile.is_open())
//   {
//      myfile << "Action" << " , " << "FunctionalFeature" << " , " ;
//      myfile << "forceOnTool_X" << " , " << "forceOnTool_Z " <<  " , ";
//      myfile << "toolVelAtHit_X" << " , " << "toolVelAtHit_Z" << " , ";  
//      myfile << "InitialToolPos_X" << " , " << "InitialToolPos_Z" << " , ";
//      myfile << "InitialTargetPos_X" << " , " << "InitialTargetPos_Z" << " , ";
//      myfile <<  "targetFinalPos_X" << " , " << "targetFinalPos_Z"  << " , ";
//      myfile << "targetDisplacement_X" << " , " << "targetDisplacement_Z";
//      myfile <<  "\n" ;

// }


}  
コード例 #9
0
void plot_close(){
  fout << "splot -51" << endl;
  fout.flush();
  fout.close();
}
コード例 #10
0
ファイル: dar-io.cpp プロジェクト: mauroFH/OptiDAR_DEV
/*
@brief Output of a route.
@param route route
#param flog output stream
*/
void CDar::out_route_01(CRoute &route, ofstream &flog)
{
	char sep = CON_CSVFILE_SEPARATOR;
	int p_node, i_node, p_pred;
	CNode *ptr_node, *ptr_pred;
	float cdist;
	int ctime, i, j, time, i_vehicle, load_disabled, load_seated, load_standing;
	bool print_aux_data=true;

	p_node = route.p_head;
	cdist = 0;
	ctime = 0;
	p_pred = NIL;
	i_vehicle = route.i_vehicle;
	assert(i_vehicle >= 0);
	//...
	// Type of capacity constrint
	if (v_vehicles[i_vehicle].type_ccons == S)
		flog << "#node" << sep << "code" << sep << "type" << sep << "distance" << sep << "time" << sep << "load" << sep 
			<< "a.time" << sep << "d.time" << sep;
	if ((v_vehicles[i_vehicle].type_ccons == A) || (v_vehicles[i_vehicle].type_ccons == B))
		flog << "#node" << sep << "code" << sep << "type" << sep << "distance" << sep << "time" << sep << "seated" << sep << "standing" << sep << "disabled" << sep 
			<< "a.time" << sep << "d.time" << sep;
	if (print_aux_data)
	{
		flog << "a.time" << sep << "d.time" << sep << "e.time" << sep << "l.time" << sep;
	}
	flog << endl;
	//...
	while (p_node != NIL)
	{
		// Current node
		ptr_node = &(route.v_nodes[p_node]);
		i_node   = ptr_node->i_node;// index of the node

		if (p_pred != NIL)
		{
			ptr_pred = &(route.v_nodes[p_pred]);
			i = ptr_pred->i_node;
			j = ptr_node->i_node;
			time = ptr_pred->d_time;
			cdist = cdist + d(i, j, time, i_vehicle);
			ctime = ctime + (int)t(i, j, time, i_vehicle);
		}

		//...
		i = ptr_node->i_node;
		// Nodes are numbered from 0
		flog << i_node-1 << sep << v_nodes[i_node].code << sep << node_type_str[v_nodes[i].type] << sep << cdist << sep << ctime << sep;
		// Type of capacity constrint
		if (v_vehicles[i_vehicle].type_ccons == S)
			flog << ptr_node->q[0] << sep;
		if (v_vehicles[i_vehicle].type_ccons == A){
			load_seated   = (int)ptr_node->q[0];
			load_standing = 0;
			if (load_seated > v_vehicles[i_vehicle].seated_capacity){
				load_standing	= load_seated - v_vehicles[i_vehicle].seated_capacity;
				load_seated		= v_vehicles[i_vehicle].seated_capacity;
			}
			load_disabled = (int)ptr_node->q[1];
			//
			flog << load_seated << sep << load_standing << sep << load_disabled << sep;
			//
		}
		if (v_vehicles[i_vehicle].type_ccons == B){
			load_seated		= (int)ptr_node->q[0];
			load_standing	= (int)ptr_node->q[1];
			load_disabled	= 0;
			//
			flog << load_seated << sep << load_standing << sep << load_disabled << sep;
			//
		}
		//
		flog << ptr_node->a_time << sep << ptr_node->d_time << sep;
		//
		//
		if (print_aux_data){
			int ei = v_nodes[i_node].tw.e_time;
			int li = v_nodes[i_node].tw.l_time;
			char str[8];
			DATsec2string(ptr_node->a_time, str);  flog << str << sep;
			DATsec2string(ptr_node->d_time, str);  flog << str << sep;
			DATsec2string(ei, str);  flog << str << sep;
			DATsec2string(li, str);  flog << str << sep;
		}
		//
		flog << endl;
		//...

		// Next node
		p_pred = p_node;
		p_node = ptr_node->p_next;
	}
	flog.flush();
}
コード例 #11
0
	int run(int round, bool tracking, bool skipUntracked) {
		runge_kutta_dopri5<Phase> stepper;
		auto ctrdStepper = make_controlled(absoluteStepperError, relativeStepperError, stepper);
		Simulator<decltype(ctrdStepper)> simulator(ctrdStepper, &bbsystem);

		uniform_real_distribution<double> distributionNullB2Max(0, b2max);
		double b = sqrt(distributionNullB2Max(randomEngine));

		helium->randomize(randomEngine);
		helium->setPosition(vector3D(0, 0, 0));
		helium->setVelocity(vector3D(0, 0, 0));

		bbsystem.setBodyPosition(projectile, vector3D(0, b, -initialDistance));
		bbsystem.setBodyVelocity(projectile, vector3D(0, 0, projectileVelocity));

		DistanceCondition condition(projectile, helium->getNucleus(), initialDistance + 1.0);

		if (skipUntracked && !tracking) {
			return 0;
		}

		stream << bbsystem.phase;
		stream.flush();

		if (tracking) {
			printer = new Printer(to_string(round) + ".csv");
			printer->addField(&printField);
			simulator.setObserver(*printer);
		}

		if (condition.evaluate(bbsystem.phase, 0)) {
			stream << "\t" << "Initial condition error" << endl;
			return -3;
		}

		int maxRounds = (int) (1.2 * (2.0 * initialDistance + 1.0) / projectileVelocity + 1.0);
		double energy = bbsystem.getSystemEnergy();
		double time = simulator.simulate(0.0, 1.0, 0.0001, condition, maxRounds);
		bool e1s1BoundToTarget, e1s2BoundToTarget;
		bool e1s1BoundToProjec, e1s2BoundToProjec;

		while (true) {

			if (time < 0.0) {
				stream << "\t" << "Distance not reached error" << endl;
				return -1;
			}

			if (abs((energy - bbsystem.getSystemEnergy()) / energy) > relativeEnergyError) {
				stream << "\t" << "Energy error: " << energy << " vs. " << bbsystem.getSystemEnergy() << endl;
				return -2;
			}

			e1s1BoundToTarget = Utils::isBound(bbsystem, helium->getElectron("1s1"), helium->getNucleus());
			e1s2BoundToTarget = Utils::isBound(bbsystem, helium->getElectron("1s2"), helium->getNucleus());
			e1s1BoundToProjec = Utils::isBound(bbsystem, helium->getElectron("1s1"), projectile);
			e1s2BoundToProjec = Utils::isBound(bbsystem, helium->getElectron("1s2"), projectile);

			if ((!e1s1BoundToTarget || !e1s1BoundToProjec) && (!e1s2BoundToTarget || !e1s2BoundToProjec)) {
				break;
			}

			stream << " " << round << " Extend Run";
			simulator.simulate(time, time + 1.0, 0.0001);
			time += 1.0;
			extended++;
		}

		string bindings;
		for (bool bound : { e1s1BoundToTarget, e1s2BoundToTarget, e1s1BoundToProjec, e1s2BoundToProjec }) {
			if (bound)
				bindings.append("-");
			else
				bindings.append("+");
		}

		switch (Utils::hash(bindings.c_str())) {
		case Utils::hash("--++"):
			stream << endl;
			break;
		case Utils::hash("+-++"):
		case Utils::hash("-+++"):
			stream << "\t" << round << " --> Single Ionization" << endl;
			ionization1++;
			break;
		case Utils::hash("++++"):
			stream << "\t" << round << " --> Dual Ionization" << endl;
			ionization2++;
			break;
		case Utils::hash("+--+"):
		case Utils::hash("-++-"):
			stream << "\t" << round << " --> Single electron Capture" << endl;
			ecapture1++;
			break;
		case Utils::hash("++--"):
			stream << "\t" << round << " --> Dual electron Capture" << endl;
			ecapture2++;
			break;
		case Utils::hash("++-+"):
		case Utils::hash("+++-"):
			stream << "\t" << round << " --> Ionization And Capture" << endl;
			ionizationAndCapture++;
			break;
		default:
			throw std::logic_error("Unhandled energy configuration.");
		}

		if (printer != nullptr)
			delete printer;

		stream.flush();
		return 0;
	}
コード例 #12
0
inline void debug(ofstream& ofs)
{
	ofs << "im here!!!!!!!!";
	ofs.flush();
}
コード例 #13
0
// Image load callback - inserts the probes.
void ImgLoad(IMG img, void *v)
{
    // Called every time a new image is loaded

    if ( (IMG_Name(img).find("libdl.so") != string::npos) ||
         (IMG_Name(img).find("LIBDL.SO") != string::npos) ||
         (IMG_Name(img).find("LIBDL.so") != string::npos) )
    {
        RTN rtndlclose = RTN_FindByName(img, "dlclose");
        if (RTN_Valid(rtndlclose) && RTN_IsSafeForProbedReplacement(rtndlclose))
        {
            OutFile << CurrentTime() << "Inserting probe for dlclose at " << RTN_Address(rtndlclose) << endl;
            OutFile.flush();
            AFUNPTR fptr = (RTN_ReplaceProbed(rtndlclose, AFUNPTR(mydlclose)));
            fptrdlclose = (int (*)(VOID_PTR ))fptr;
        }

        RTN rtndlopen = RTN_FindByName(img, "dlopen");
        if (RTN_Valid(rtndlopen) && RTN_IsSafeForProbedReplacement(rtndlopen))
        {
            OutFile << CurrentTime() << "Inserting probe for dlopen at " << RTN_Address(rtndlopen) << endl;
            OutFile.flush();
            AFUNPTR fptr = (RTN_ReplaceProbed(rtndlopen, AFUNPTR(mydlopen)));
            fptrdlopen = (VOID_PTR (*)(__const CHAR_PTR , int ))fptr;
        }

        RTN rtndlsym = RTN_FindByName(img, "dlsym");
        if (RTN_Valid(rtndlsym) && RTN_IsSafeForProbedReplacement(rtndlsym))
        {
            OutFile << CurrentTime() << "Inserting probe for dlsym at " << RTN_Address(rtndlsym) << endl;
            OutFile.flush();
            AFUNPTR fptr = (RTN_ReplaceProbed(rtndlsym, AFUNPTR(mydlsym)));
            fptrdlsym = (VOID_PTR (*)(VOID_PTR, __const CHAR_PTR ))fptr;
        }

        RTN rtndlvsym = RTN_FindByName(img, "dlvsym");
        if (RTN_Valid(rtndlvsym) && RTN_IsSafeForProbedReplacement(rtndlvsym))
        {
            OutFile << CurrentTime() << "Inserting probe for dlvsym at " << RTN_Address(rtndlvsym) << endl;
            OutFile.flush();
            AFUNPTR fptr = (RTN_ReplaceProbed(rtndlvsym, AFUNPTR(mydlvsym)));
            fptrdlvsym = (VOID_PTR (*)(VOID_PTR, __const CHAR_PTR, __const CHAR_PTR))fptr;
        }

        RTN rtndladdr = RTN_FindByName(img, "dladdr");
        if (RTN_Valid(rtndladdr) && RTN_IsSafeForProbedReplacement(rtndladdr))
        {
            OutFile << CurrentTime() << "Inserting probe for dladdr at " << RTN_Address(rtndladdr) << endl;
            OutFile.flush();
            AFUNPTR fptr = (RTN_ReplaceProbed(rtndladdr, AFUNPTR(mydladdr)));
            fptrdladdr = (int (*)(__const void * , Dl_info * ))fptr;
        }

        RTN rtndladdr1 = RTN_FindByName(img, "dladdr1");
        if (RTN_Valid(rtndladdr) && RTN_IsSafeForProbedReplacement(rtndladdr1))
        {
            OutFile << CurrentTime() << "Inserting probe for dladdr1 at " << RTN_Address(rtndladdr1) << endl;
            OutFile.flush();
            AFUNPTR fptr = (RTN_ReplaceProbed(rtndladdr, AFUNPTR(mydladdr1)));
            fptrdladdr1 = (int (*)(__const void * , Dl_info *, void **, int ))fptr;
        }

        RTN rtndlerror = RTN_FindByName(img, "dlerror");
        if (RTN_Valid(rtndlerror) && RTN_IsSafeForProbedReplacement(rtndlerror))
        {
            OutFile << CurrentTime() << "Inserting probe for dlerror at " << RTN_Address(rtndlerror) << endl;
            OutFile.flush();
            AFUNPTR fptr = (RTN_ReplaceProbed(rtndlerror, AFUNPTR(mydlerror)));
            fptrdlerror = (CHAR_PTR (*)(void ))fptr;
        }
    }
    // finished instrumentation
}
コード例 #14
0
void NaturalDigits(ofstream & fout){
    int MenuNumber;
    bool correct=1,stop=1,newnumber=1,correct2=1;
    long double UserNumber;
    int NumberofBits;
    
    while (correct) {
        //цикл проверки верного ввода кол-ва разрядов
        while(correct2){
            cout<<"\nвведите кол-во разрядов(8 ,16, или 32)\n> ";
            cin>>NumberofBits;
            if((NumberofBits==8)||(NumberofBits==16)||(NumberofBits==32))
                correct2=0;
        }
        if(correct2==0){
            cout<<"введите число\n> ";
            cin>>UserNumber;
            if(UserNumber>floor(UserNumber))
                cout<<"\nВы ввели вещественное число,программа будет работать с целой частью\n";
            if(abs(UserNumber)>pow(2.,NumberofBits))
                cout<<"\nВы ввели слишком большое число ,некоторые биты будут отрезаны\n";
        }
        fout<<UserNumber<<"\n";
        int mass[33]={};
        newnumber=0;
        stop=1;
        translateInto2(mass,UserNumber,NumberofBits);
        for(int i=NumberofBits;i>=1;i--){
            //вывод массива с конца
            fout<<mass[i];
        }
        fout<<"\n";
        fout.flush();
        while(stop){
            //запуск меню после каждой используемой функции
            cout<<"\n"<<setw(20)<<"Меню";
            cout<<"\n  выберите операцию:\n";
            cout<<"1)изменить некоторые биты\n";
            cout<<"2)сделать инверсию бит\n";
            cout<<"3)перемещение последовательности бит на указанную позицию\n";
            cout<<"4)перестановка цепочек бит\n";
            cout<<"5)левый сдвиг на указанное кол-во бит\n";
            cout<<"6)правый сдвиг на указанное кол-во бит\n";
            cout<<"7)показать 10ный эквивалент\n";
            cout<<"8)вернуться к выбору числа и кол-ва разрядов\n";
            cout<<"9)Вернуться к выбору вида числа\n> ";
            cin>>MenuNumber;
            if(MenuNumber==1)
                ChangeSomeBits(mass,NumberofBits);
            if(MenuNumber==2)
                InversionBits(mass,NumberofBits);
            if(MenuNumber==3)
                MovementBits(mass,NumberofBits);
            if(MenuNumber==4)
                ChangesChainBits(mass,NumberofBits);
            if(MenuNumber==5)
                LeftShift(mass,NumberofBits);
            if(MenuNumber==6)
                RightShift(mass,NumberofBits);
            if(MenuNumber==7)
                BinDec(mass,NumberofBits);
            if(MenuNumber==8){
                //параметр выхода из главного меню
                correct=1;
                correct2=1;
                stop=0;
            }
            if(MenuNumber==9){
                //параметр выхода из всех циклов
                stop=0;
                correct=0;
            }
            for(int i=NumberofBits;i>=1;i--){
                //вывод массива с конца
                fout<<mass[i];
            }
            fout<<"\n";
            fout.flush();
        }
    }