tIASCapabilities SimulationServer::capabilities(const std::string& goal,
                                                const std::string& environment)
{
    Simulator simulator;

    return simulator.capabilities(goal, environment);
}
Example #2
0
// Interpter of VM
Value Simulator::interpreter(AbstractComponent *_component, Thread *_thread, Value *__args, ArgNo __n)
{
    // Create simulation context
    Simulator sim;
    sim.m_thread = _thread;
    sim.m_component = _component;
    sim.m_domain = _thread->get_current_domain();
    sim.m_function = _thread->get_this_function();
    sim.m_program = sim.m_function->get_program();
    sim.m_argn = __n;
    sim.m_args = __args;
    sim.m_localn = sim.m_function->get_max_local_no();
    sim.m_locals = (Value *)STD_ALLOCA(sizeof(Value) * sim.m_localn);
    sim.m_constantn = sim.m_program->get_constants_count();
    sim.m_constants = sim.m_program->get_constant(0);
    sim.m_object_varn = sim.m_component->m_program->get_object_vars_count();
    sim.m_object_vars = sim.m_component->m_object_vars;
    memset(sim.m_locals, 0, sizeof(Value) * sim.m_localn);

    // Set byte codes
    sim.m_byte_codes = sim.m_function->get_byte_codes_addr();

    // Start simulation
    return sim.run();
}
Example #3
0
void TraceTest::runTest(Random<double>* random, RLProblem<double>* problem,
    Projector<double>* projector, Trace<double>* trace)
{
  StateToStateAction<double>* toStateAction = new StateActionTilings<double>(projector,
      problem->getDiscreteActions());
  double alpha = 0.2 / projector->vectorNorm();
  double gamma = 0.99;
  double lambda = 0.3;
  double epsilon = 0.01;
  Sarsa<double>* sarsa = new Sarsa<double>(alpha, gamma, lambda, trace);
  Policy<double>* acting = new EpsilonGreedy<double>(random, problem->getDiscreteActions(), sarsa,
      epsilon);
  OnPolicyControlLearner<double>* control = new SarsaControl<double>(acting, toStateAction, sarsa);

  RLAgent<double>* agent = new LearnerAgent<double>(control);
  Simulator<double>* sim = new Simulator<double>(agent, problem, 5000, 500, 1);
  Simulator<double>::Event* performanceVerifier = new PerformanceVerifier<double>();
  sim->onEpisodeEnd.push_back(performanceVerifier);
  sim->setVerbose(false);
  sim->run();

  delete toStateAction;
  delete sarsa;
  delete acting;
  delete control;
  delete agent;
  delete sim;
  delete performanceVerifier;
}
Example #4
0
void Wrapper::run_single_individual(Individual& I){
    Simulator Sim;
    Neural_Network NN;
    I.set_individual_params(isize_1, isize_2, imutate_mag_1, imutate_mag_2, imutate_amount_1, imutate_amount_2);
    
    // TODO - User inputs all weights.
    // TODO -Able to change how weights are generated, access to different random functions.
    
    I.build_individual(); // TODO - change
    
    Sim.initialize_sim();
    
    NN.take_input_limits(Sim.currentstate.state_variables_LowLimit, Sim.currentstate.state_variables_UpLimit);
    NN.take_output_limits(Sim.currentstate.control_LowLimits, Sim.currentstate.control_UpLimits);
    NN.take_num_hidden_units(this->hidden_layer_size); /// repeated from initialize, but no harm.
    NN.take_num_controls(Sim.currentstate.num_of_controls); /// repeated from initialize, but to no harm.
    NN.take_weights(I.get_individual1(), I.get_individual2()); /// repeated from communication_from_EA, but to no harm.

    
    NN.communication_from_EA(I.get_individual1(), I.get_individual2());
    while (Sim.t<Sim.tmax || Sim.lander.frame.at(1).s > Sim.lander.frame.at(1).target){
        vector<double> action;
        action = NN.activation_function(Sim.currentstate.translate_function());
        Sim.run_sim(action);
        NN.reset_neural_network();                      // Do we want this??
    }
    // fitness function from Sim
    // I.set_fit_rating( double );
    // get phenotypes from Sim
    // I.set_phenotypes( double , double );
    // ME.place_individual_in_map(I);
}
Example #5
0
int main(int argc, char *argv[])
{
    // ======= Classi =======
    Simulator simulator; // Simulator
    OgreApp ogreapp(&simulator); // Ogre Application

    // ======= Leggi il file di configurazione =======
    Json::Value conf;
    char config_file_name[512] = "config.conf\0";
    if (argc > 1) {
        snprintf(config_file_name, sizeof(config_file_name), "%s", argv[1]);
    } else {
        usage(argv[0]);
    }
    printf("Leggo il file di configurazione '%s'...\n", config_file_name);
    std::ifstream config_file;
    config_file.open(config_file_name);
    Json::Reader reader;
    if ( !reader.parse( config_file, conf ) ) {
        // report to the user the failure and their locations in the document.
        error("Errore nel leggere il file di configurazione:\n%s", reader.getFormatedErrorMessages().c_str());
    }
    config_file.close();

    // ======= Applica la configurazione =======
    simulator.load_configuration(conf);
    simulator.init_state();
    ogreapp.load_configuration(conf);
    
    // ======= Start =======
    ogreapp.startMainLoop();
    
    return 0;
}
Example #6
0
int
ACCELSIM::transfer(uint8_t *send, uint8_t *recv, unsigned len)
{
	uint8_t cmd = send[0];

	if (cmd & DIR_READ) {
		// Get data from the simulator
		Simulator *sim = Simulator::getInstance();

		if (sim == NULL) {
			return ENODEV;
		}

		// FIXME - not sure what interrupt status should be
		recv[1] = 0;

		// skip cmd and status bytes
		if (cmd & ACC_READ) {
			sim->getRawAccelReport(&recv[2], len - 2);

		} else if (cmd & MAG_READ) {
			sim->getMagReport(&recv[2], len - 2);
		}
	}

	return PX4_OK;
}
Example #7
0
int
GPSSIM::receive(int timeout)
{
	Simulator *sim = Simulator::getInstance();
	simulator::RawGPSData gps;
	sim->getGPSSample((uint8_t *)&gps, sizeof(gps));

	_report_gps_pos.timestamp_position = hrt_absolute_time();
	_report_gps_pos.lat = gps.lat;
	_report_gps_pos.lon = gps.lon;
	_report_gps_pos.alt = gps.alt;
	_report_gps_pos.timestamp_variance = _report_gps_pos.timestamp_position;
	_report_gps_pos.eph = (float)gps.eph * 1e-2f;
	_report_gps_pos.epv = (float)gps.epv * 1e-2f;
	_report_gps_pos.timestamp_velocity = _report_gps_pos.timestamp_position;
	_report_gps_pos.vel_m_s = (float)(gps.vel) / 100.0f;
	_report_gps_pos.vel_n_m_s = (float)(gps.vn) / 100.0f;
	_report_gps_pos.vel_e_m_s = (float)(gps.ve) / 100.0f;
	_report_gps_pos.vel_d_m_s = (float)(gps.vd) / 100.0f;
	_report_gps_pos.cog_rad = (float)(gps.cog) * 3.1415f / (100.0f * 180.0f);
	_report_gps_pos.fix_type = gps.fix_type;
	_report_gps_pos.satellites_used = gps.satellites_visible;

	usleep(200000);
	return 1;
}
Example #8
0
int main()
{
	// Create our model
	FMI<double>* hello = new HelloWorld();
	// Wrap a set of solvers around it
	Hybrid<double>* hybrid_model =
		new Hybrid<double>
		(
			hello, // Model to simulate
			new corrected_euler<double>(hello,1E-5,0.01), // ODE solver
			new discontinuous_event_locator<double>(hello,1E-5) // Event locator
			// You must use this event locator for OpenModelica because it does
			// not generate continuous zero crossing functions
		);
        // Create the simulator
        Simulator<double>* sim =
			new Simulator<double>(hybrid_model);
		// Run the simulation for ten seconds
        while (sim->nextEventTime() <= 10.0)
			sim->execNextEvent();
		// Cleanup
        delete sim;
		delete hybrid_model;
		// Done!
        return 0;
}
int main()
{	int x;
	Simulator S;
	cout<<"Enter Inter Arrival Time Range"<<endl;
	cin>>S.Arrmin>>S.Arrmax;
	cout<<"Enter Service Time Range"<<endl;
	cin>>S.Sermin>>S.Sermax;
	
	cout<<"Enter Time-out Time Range"<<endl;
	cin>>S.Coutmin>>S.Coutmax;
	cout<<"Enter maximum Departures"<<endl;
	cin>>S.Depmax;
	cout<<"Number of Servers"<<endl;
	cin>>S.Sn;
	cout<<"Buffer length including Servers"<<endl;
	cin>>x;
	S.Bfr.maxsize = x - S.Sn;
	cout<<endl;
	S.start();
	cout<<endl;
	cout<<"Average Waiting Time = "<<S.Mcs.CalculateAvgWaitTime()<<endl;
	cout<<"Total Departures = "<<S.Mcs.totalDep<<endl;
	cout<<"Total Arrivals = "<<S.Mcs.totalArr<<endl;
	cout<<"Fraction of Customers Successfully Serviced = "<<(S.Mcs.totalDep)/(S.Mcs.totalArr)<<endl;
	cout<<"Fraction of time Server were busy= "<<S.Mcs.AvgTimeSvrBusy<<endl;
	cout<<"Average Queue length = "<<S.Mcs.Queuelength<<endl;
	cout<<"Fraction of Customers Out due to full buffer = "<<S.Mcs.CalculateFractionBfrfull()<<endl;
	cout<<"Total Timeouts = "<<S.Mcs.ttlTimeouts<<endl;
	cout<<"Fraction of Customers timed out = "<<(S.Mcs.ttlTimeouts)/(S.Mcs.totalArr)<<endl;
	return 0;

}
Example #10
0
/**
 * Main.
 *
 * @param   int      number of arguments
 * @param   char**   arguments
 * @return  int
 */
int main(int argc, char **argv)
{
	// Make sure we have the minimum number of arguments
	if (argc != 9)
	{
		printf("Not enough arguments: %d", argc);
		throw;
	}

	Simulator::Config config = Simulator::Config();

	// Set bitmap file locations
	config.real_bitmap = argv[2];
	config.robot_bitmap = argv[3];

	// Start position (x, y)
	config.start.first = atoi(argv[4]);
	config.start.second = atoi(argv[5]);

	// Goal position (x, y)
	config.goal.first = atoi(argv[6]);
	config.goal.second = atoi(argv[7]);

	// Robot scan radius
	config.scan_radius = atoi(argv[8]);

	// Build the simulator and draw
	Simulator sim = Simulator(argv[1], config);
	sim.draw();

	return 0;
}
Example #11
0
int main (int argc, char *argv[]) {
	//print usage
		cout << "\njemris "  << VERSION;
#ifdef GIT_COMMIT
		cout << " (" << GIT_COMMIT << ")";
#endif
        cout << "\n" << endl;

	if (argc==1) {
		usage();
		return 0;
	}

	string input (argv[1]);

	//CASE 1: Dump list of modules in xml file
	if (input == "modlist")  {
		SequenceTree* seqTree = SequenceTree::instance();
		seqTree->SerializeModules("mod.xml");
		//delete seqTree;
		return 0;
	}

	//CASE 2: try Dump of seq-diagram from Sequence xml-file
	SequenceTree* seqTree = SequenceTree::instance();
	seqTree->Initialize(input);
	if (seqTree->GetStatus()) {
		seqTree->Populate();
		ConcatSequence* seq = seqTree->GetRootConcatSequence();
		seq->SeqDiag("seq.h5");
		seq->DumpTree();
		if (argc==3) seq->WriteStaticXML("jemris_seq.xml");
		//delete seqTree;
		return 0;
	}

	//CASE 3: try simulation from Simulator xml-file
	Simulator sim (input);
	if (sim.GetStatus()) {
		static clock_t runtime = clock();
		do_simu(&sim);
		runtime = clock() - runtime;
		printf ("Actual simulation took %.2f seconds.\n", runtime / 1000000.0);
		return 0;
	}

	//CASE 4: try Dump of sensitivities from CoilArray xml-file
	CoilArray* coils = new CoilArray();
	cout << "dumping sensitivity maps to sensmaps.h5 ...\n";
	coils->Initialize(input);
	if (coils->Populate() == OK) {
		coils->DumpSensMaps(true);
		cout << "done!\n";
		return 0;
	}
	
	//OTHERWISE: not a valid input
	cout << input << " is not a valid input.\n";
	return 0;
}
Example #12
0
int main(int argc, char** argv)
{
	// Get the parameters for the experiment from the command line
	if (argc != 4) {
		cout << "freq left_throttle right_throttle" << endl;
		return 0;
	}
	// Get the frequency of the voltage signal from the first argument
	double freq = atof(argv[1]);
	// Create a command from the driver that contains the duty ratios and
	// directions.
	SimPacket sim_command;
	sim_command.left_power = atof(argv[2]);
	sim_command.right_power = atof(argv[3]);
	// Create computer, simulator, and event listener. 
	Computer* computer = new Computer(freq);
	Simulator<SimEvent>* sim = new Simulator<SimEvent>(computer);
	ComputerListener* l = new ComputerListener(computer);
	// Add an event listener to plot the voltage signals
	sim->addEventListener(l);
	// Inject the driver command into the simulation at time 0
	Bag<Event<SimEvent> > input;
	SimEvent cmd(sim_command);
	Event<SimEvent> event(computer,cmd);
	input.insert(event);
	sim->computeNextState(input,0.0);
	// Run the simulation 
	while (sim->nextEventTime() <= 0.004)
		sim->execNextEvent();
	// Clean up and exit
	delete sim; delete computer; delete l;
	return 0;
}
Example #13
0
// --------------------------------------------------
void Wrapper::mutate_MAP(){
    int mut_gen = ME.get_mutate_generation();
    for (int g=0; g<mut_gen; g++){
        Simulator Sim;
        Neural_Network NN;
        
        // p1 and p2 rand numbers OR -> rand placment function() modifiable
        //ME.individual_from_map(p1, p2);
        NN.communication_from_EA(ME.get_temp_individual1(), ME.get_temp_individual2());
        Sim.initialize_sim();
        /// %%% /// %%% BEGIN SIMULATION LOOP %%% /// %%% ///
        while (Sim.t<Sim.tmax && Sim.lander.frame.at(1).s > Sim.lander.frame.at(1).target){
            /// while the simulator still has time left on the clock
            /// AND
            /// the craft is above ground level:
            
            NN.communication_from_simulator_deprecated(Sim.currentstate.translate_function(), Sim.currentstate.state_variables_UpLimit, Sim.currentstate.state_variables_LowLimit, hidden_layer_size, Sim.currentstate.num_of_controls, Sim.currentstate.control_UpLimits, Sim.currentstate.control_LowLimits);
            Sim.run_sim(NN.communication_to_simulator());
            NN.reset_neural_network();                      // Do we want this??
        }
        /// %%% /// %%% END SIMULATION LOOP %%% /// %%% ///
        // fitness function from Sim
        // I.set_fit_rating( double );
        // get phenotypes from Sim
        // I.set_phenotypes( double , double );
        // ME.place_individual_in_map(I);
    }
}
Example #14
0
int main()
{
	Simulator simulator;

	simulator.setTimeStep(0.25f);
	simulator.setAgentDefaults(15.0f, 10, 1.5f, 1.5f, 1.0f, 2.0f);

	for (std::size_t i = 0; i < 250; ++i) {
		const Vector2 position = 200.0f * Vector2(std::cos(0.004f * i * HRVO_TWO_PI), std::sin(0.004f * i * HRVO_TWO_PI));
		simulator.addAgent(position, simulator.addGoal(-position));
	}

	do {
#if HRVO_OUTPUT_TIME_AND_POSITIONS
		std::cout << simulator.getGlobalTime();

		for (std::size_t i = 0; i < simulator.getNumAgents(); ++i) {
			std::cout << " " << simulator.getAgentPosition(i);
		}

		std::cout << std::endl;
#endif /* HRVO_OUTPUT_TIME_AND_POSITIONS */

		simulator.doStep();
	}
	while (!simulator.haveReachedGoals());

	return 0;
}
Example #15
0
int main (int argc, char *argv[])
{
	if (argc != 3 && argc != 4) {
		qWarning("Usage: simulator <port> <frequency>");
		qWarning("       simulator <port> <frequency> <infile>");
		return 1;
	}
	int frequency = 0;
	bool ok = false;
	frequency = QString(argv[2]).toInt(&ok);
	if (!ok) {
		qWarning("Frequency must be an integer");
		return 1;
	}

	QCoreApplication app(argc, argv);

	Simulator *simulator;
	if (argc == 3) {
		simulator = new Simulator(&app);
	} else if (argc == 4) {
		simulator = new Simulator(argv[3], &app);
	}

	if (!simulator->start(argv[1], frequency)) {
		qWarning("Failed to start simulator");
		return 1;
	}

	return app.exec();
}
Example #16
0
int main() {

	airport.enter_data();
	airport.run_simulation();
	airport.show_stats();

	return 0;
}
Example #17
0
int main(int argc, char **argv) {
    ros::init(argc, argv, "Simulator");
    ros::NodeHandle n;
    Simulator s;
    s.init(n);
    s.run();
    return 0;
}
int main(int argc, char const *argv[])
{
    //freopen("DEBUG_INFO.rpt", "w", stdout);
    Simulator* simulator = new Simulator(argc, argv);
    simulator->start();
    printf("Smulation ends.");
    return 0;
}
void ModuleDispose::do_run(Entity* entity) {
    Simulator *simulator = Simulator::getInstance();
    if (this->_collectStatistics) {
        /*@Todo: collect entity statistics*/
    }
    simulator->removeEntity(entity);
    Debug::cout(Debug::Level::fine, this, entity, "Entity was removed from system");
}
Example #20
0
int main(int argc, char* argv[])
{
	Simulator simulator;

	simulator.run(sf::milliseconds(17));

	return EXIT_SUCCESS;
}
void SimulateWindow::getFiles(const QString assemblyCodeFile, const QString textDumpFile, const QString memoryDumpFile, const QString registerUpdateFile)
{
    ui->textBrowser->clear();
    Simulator simulator;
    simulator.memory.getPointers(ui->textBrowser);
    AssemblyParser assemblyParser(assemblyCodeFile.toStdString(), textDumpFile.toStdString(), memoryDumpFile.toStdString(), simulator.memory, simulator.program, ui->textBrowser);
    if (!TERMINATE)
        simulator.simulate(registerUpdateFile.toStdString(), ui->textBrowser);
}
void Node::randomize_position()
{
	float pos = 0; 
	//resolution 0.1m
	pos = rand() % (Sim.getArenaWidth()*10);
	w_0[X] = pos/10;
	pos = rand() % (Sim.getArenaHeight()*10);
	w_0[Y] = pos/10;	
}
Example #23
0
int main(int argc, const char* argv[])
{
	Simulator simulator;
	simulator.handleArguments(argc, argv);
	if (simulator.handleAll())
		return -1;
	simulator.startSimulation();
	simulator.end();
	return 0;
}
Example #24
0
int main(int argc, char* argv[]){
	if (argc == 1) {
		cout << "Error: No input file!" << endl;
		return 0;
	}
    Simulator* simulator = new Simulator(argv[1], argv[2], false, false);
	simulator->simulate();
	delete simulator;
	return 1;
}
Example #25
0
void FluidCinderApp::setup()
{
	s.initializeGrid(400,200);
	s.addParticles();
	n = s.particles.size();
	gl::VboMesh::Layout layout;
	layout.setDynamicPositions();
	
	vertices = new GLfloat[n*4];
}
Example #26
0
int main(int argc, char **argv){
  //declaration of variable and containers
  int num = 0;//subarg <num> 
//  string type_str = parse_args(argc, argv, num);//type indicator of schedulers
  //test init
  Simulator sim;
  sim.init_process_n_event("./data/input0");
   
  return 0;  
}
Example #27
0
static void
simulate(const Settings &settings, const std::vector<std::string> &args, char *envp[]) {
    // Create and configure simulator
    Simulator sim;
    if (settings.usingDebugger)
        RSIM_Debugger::attach(sim);
    sim.configure(settings.simSettings, envp);

    // Load specimen directly or via debugger
    pid_t existingPid = -1;
    char *rest = NULL;
    errno = 0;
    if (args.size()==1 && (existingPid=strtoul(args.front().c_str(), &rest, 0))>=0 && !errno && !*rest) {
        if (sim.loadSpecimen(existingPid) < 0)
            return;
    } else {
        if (sim.loadSpecimen(args) < 0)
            return;
    }

    // Run the simulation
    if (settings.catchingSignals)
        sim.activate();
    sim.main_loop();
    if (settings.catchingSignals)
        sim.deactivate();
    std::cerr <<sim.describe_termination() <<"\n";
    sim.terminate_self(); // probably doesn't return
}
Example #28
0
int main(int argc, char **argv)
{
	QApplication app(argc, argv);

	Logger::setupLogging(argc, argv);

	Simulator server;
	server.show();

	return app.exec();
}
void PyEmbedder::InitPython()
{
	int iRet = 0;
	if(!Py_IsInitialized())
	{
		Py_SetProgramName("AnimatLab");
		Py_Initialize();

		if(!Py_IsInitialized())
			THROW_ERROR(Al_Err_lFailedToInitPython, Al_Err_strFailedToInitPython);

		Simulator *lpSim = ActiveSim();
		if(!lpSim)
			THROW_ERROR(Al_Err_lSimNotDefined, Al_Err_strSimNotDefined);

		std::string strExePath = lpSim->ExecutablePath();
		strExePath = Std_Replace(strExePath, "\\", "/");

		//Import base modules and set paths correctly.
		std::string strInit = "import os,sys,traceback,math\n"
							  "sys.path.append(\"" + strExePath + "\")\n"
							  "os.chdir(\"" + strExePath + "\")\n";
		iRet = PyRun_SimpleString(strInit.c_str());
		if(iRet != 0)
			THROW_ERROR(Al_Err_lFailedToInitPython, Al_Err_strFailedToInitPython);

		//Try to import AnimatSimPy
		iRet = PyRun_SimpleString("import AnimatSimPy\n");
		if(iRet != 0)
			THROW_ERROR(Al_Err_lFailedToImportAnimatSimPy, Al_Err_strFailedToImportAnimatSimPy);

		//Setup sys exception handler for animatsim.
		std::string strExcept = "def animat_excepthook(type, value, tb):\n"
							    "    strErr = \"\".join(traceback.format_exception(type, value, tb))\n"
							    "    AnimatSimPy.SetLastScriptError(strErr)\n"
							    "sys.excepthook = animat_excepthook\n";
		iRet = PyRun_SimpleString(strExcept.c_str());
		if(iRet != 0)
			THROW_ERROR(Al_Err_lFailedToInitPython, Al_Err_strFailedToInitPython);

		//For testing of exception handler.
		//std::string strTest = "a = \"text\"\n"
		//					  "b = 5\n"
		//					  "error = a + b\n";
		//iRet = PyRun_SimpleString(strTest.c_str());
		//if(iRet != 0)
		//{
		//	std::string strErr = GetLastScriptError();
		//}

		m_bPyInit = true;
	}
}
int main(int argc, char** argv)
{
    Opm::parameter::ParameterGroup param(argc, argv);
    Dune::MPIHelper::instance(argc,argv);
#ifdef USE_TBB
    int num_threads = param.getDefault("num_threads", tbb::task_scheduler_init::default_num_threads());
    tbb::task_scheduler_init init(num_threads);
#endif
    Simulator sim;
    sim.init(param);
    sim.run();
}