/// includes tests for getNumberOfStates/Inputs/Outputs() /// and confirms generate(), removeTransition(), removeState() void tGenerateSaveLoad() { DEBUG_MSG("Generate: %s", machineTypeNames[fsm->getType()]); fsm->generate(0, 0, 0);// = create(1,1,1) is minimum /// ERR: <type>::generate - the number of states needs to be greater than 0 (set to 1) /// ERR: <type>::generate - the number of inputs needs to be greater than 0 (set to 1) /// ERR: <type>::generate - the number of outputs needs to be greater than 0 (set to 1) ARE_EQUAL(fsm->getNumberOfStates(), state_t(1), "The number of states is not correct."); ARE_EQUAL(fsm->getNumberOfInputs(), input_t(1), "The number of inputs is not correct."); ARE_EQUAL(fsm->getNumberOfOutputs(), output_t(1), "The number of outputs is not correct."); tSaveLoad(); fsm->generate(5, 3, 2); ARE_EQUAL(fsm->getNumberOfStates(), state_t(5), "The number of states is not correct."); ARE_EQUAL(fsm->getNumberOfInputs(), input_t(3), "The number of inputs is not correct."); ARE_EQUAL(fsm->getNumberOfOutputs(), output_t(2), "The number of outputs is not correct."); tSaveLoad(); fsm->removeTransition(0, 0); fsm->removeTransition(1, 1); fsm->removeTransition(2, 2); /// 3 transitions * 2 machines = 6 ERRs if fsm->isOutputTransition() /// <type>::getOutput - there is no such transition fsm->removeState(3); /// if fsm->isOutputTransition() && there was a transition to state 3, then 2 ERRs: /// <type>::getOutput - there is no such transition tSaveLoad(); }
/// includes tests for getNumberOfStates/Inputs/Outputs() /// and confirms create(), removeTransition() void tCreateSaveLoad() { DEBUG_MSG("Create: %s", machineTypeNames[fsm->getType()]); fsm->create(0, 0, 0);// = create(1,0,0) is minimum /// ERR: <type>::create - the number of states needs to be greater than 0 (set to 1) ARE_EQUAL(fsm->getNumberOfStates(), state_t(1), "The number of states is not correct."); ARE_EQUAL(fsm->getNumberOfInputs(), input_t(0), "The number of inputs is not correct."); ARE_EQUAL(fsm->getNumberOfOutputs(), output_t(0), "The number of outputs is not correct."); tSaveLoad(); fsm->create(5, 3, 2); ARE_EQUAL(fsm->getNumberOfStates(), state_t(5), "The number of states is not correct."); ARE_EQUAL(fsm->getNumberOfInputs(), input_t(3), "The number of inputs is not correct."); ARE_EQUAL(fsm->getNumberOfOutputs(), output_t(2), "The number of outputs is not correct."); /// 5 states * 3 inputs * 2 machines = 30 ERRs if fsm->isOutputTransition() /// <type>::getOutput - there is no such transition tSaveLoad(); fsm->setTransition(0, 0, 0); fsm->setTransition(0, 1, 1); fsm->setTransition(0, 2, 2); fsm->setTransition(1, 0, 3); fsm->setTransition(2, 1, 4); fsm->setTransition(3, 2, 0); fsm->setTransition(4, 0, 2); /// (5 states * 3 inputs - 7 transitions) * 2 machines = 16 ERRs if fsm->isOutputTransition() /// <type>::getOutput - there is no such transition tSaveLoad(); }
state_t graph_t<NodeCount>::next(const state_t & state, sigma_t sigma) const { //edge_t backward_edge = state.e == GRAPH_0 ? switch_setting(sigma, state) : GRAPH_0; /* Find the vertex connected to the edge */ const typename graph_t<NodeCount>::connection_t *connection = std::find_if(m_graph[state.v], m_graph[state.v] + NodeCount, vertex_contains_edge<NodeCount>(state.e)); unsigned int vertex = connection - m_graph[state.v]; /* Find the edge connecting the newly found vertex to our state vertex */ edge_t backward_edge = m_graph[vertex][state.v][std::find(connection->begin(), connection->end(), state.e) - connection->begin()]; if (backward_edge == GRAPH_0) return state_t(vertex, switch_setting(sigma, state_t(vertex, 0))); else return state_t(vertex, GRAPH_0); }
/// includes tests for getNumberOfStates/Inputs/Outputs(), getType(), /// isReduced(), isOutputState/Transition(), getStates(), addState(), removeState() /// save(), load() /// confirms getOutput(), getNextState() void tSaveLoad() { string path = DATA_PATH; path += "tmp/"; string filename = fsm->save(path); ARE_EQUAL(!filename.empty(), true, "This %s cannot be saved into path '%s'.", machineTypeNames[fsm->getType()], path.c_str()); ARE_EQUAL(fsm2->load(filename), true, "File '%s' cannot be loaded.", filename.c_str()); DEBUG_MSG(filename.c_str()); ARE_EQUAL(fsm->getType(), fsm2->getType(), "Types of machines are not equal."); ARE_EQUAL(fsm->getNumberOfStates(), fsm2->getNumberOfStates(), "The numbers of states are not equal."); ARE_EQUAL(fsm->getNumberOfInputs(), fsm2->getNumberOfInputs(), "The numbers of inputs are not equal."); ARE_EQUAL(fsm->getNumberOfOutputs(), fsm2->getNumberOfOutputs(), "The numbers of outputs are not equal."); ARE_EQUAL(fsm->isReduced(), fsm2->isReduced(), "The indicators of minimal form are not equal."); ARE_EQUAL(fsm->isOutputState(), fsm2->isOutputState(), "The indicators of state outputs are not equal."); ARE_EQUAL(fsm->isOutputTransition(), fsm2->isOutputTransition(), "The indicators of transition outputs are not equal."); auto states = fsm->getStates(); ARE_EQUAL(fsm->getNumberOfStates(), state_t(states.size()), "The numbers of states are not equal."); auto states2 = fsm2->getStates(); ARE_EQUAL(states == states2, true, "The sets of states are not equal."); ARE_EQUAL((find(states.begin(), states.end(), 0) != states.end()), true, "The initial state is missing."); for (state_t& state : states) { if (fsm->isOutputState()) { ARE_EQUAL(fsm->getOutput(state, STOUT_INPUT), fsm2->getOutput(state, STOUT_INPUT), "The outputs of state %d are different.", state); } for (input_t i = 0; i < fsm->getNumberOfInputs(); i++) { state_t nextState = fsm->getNextState(state, i); //DEBUG_MSG("%d", nextState); if (fsm->isOutputTransition()) { output_t output = fsm->getOutput(state, i); ARE_EQUAL(output, fsm2->getOutput(state, i), "The outputs on input %d from state %d are different.", i, state); if (nextState == NULL_STATE) { ARE_EQUAL(WRONG_OUTPUT, output, "There is no transition on input %d from state %d but output %d is set.", i, state, output); } } ARE_EQUAL(nextState, fsm2->getNextState(state, i), "The next states on input %d from state %d are different.", i, state); ARE_EQUAL(nextState != WRONG_STATE, true, "The next state on input %d from state %d is wrong.", i, state); if (nextState != NULL_STATE) { ARE_EQUAL((find(states.begin(), states.end(), nextState) != states.end()), true, "The next state is wrong."); } } } auto newState = fsm->addState(); //DEBUG_MSG("%d", newState); ARE_EQUAL(fsm->getNumberOfStates(), fsm2->getNumberOfStates() + 1, "The numbers of states are to be different by one."); ARE_EQUAL(newState, fsm2->addState(), "IDs of new states are not equal."); ARE_EQUAL(fsm->getNumberOfStates(), fsm2->getNumberOfStates(), "The numbers of states are not equal."); fsm->removeState(newState); ARE_EQUAL(fsm->getNumberOfStates(), fsm2->getNumberOfStates() - 1, "The numbers of states are to be different by one."); }
int main(int argc , char ** argv){ int * state = new int[36]; for(int i = 1; i < argc; i++){ state[i-1] = atoi(argv[i]); } state_t stat = state_t(); stat.set_state(state); stat.set_player(false); state_t best = stat.bestNextMove(); best.print(std::cout,10); }
void ext_model::update( double time ) { view::update(time); double const fms_calc_step = cfg().model_params.msys_step; if(pilot_impl_) { double dt = last_time_ ? time - *last_time_ : 0.; #if 0 if (!cg::eq_zero(dt)) { geo_base_3 prev_pos = pilot_impl_->state().dyn_state.pos; if (dt > 0) { size_t steps = cg::floor(dt / fms_calc_step + fms_calc_step * .1); fms::pilot_simulation_ptr pilot_sim(pilot_impl_); for (size_t i = 0; i < steps; ++i) { pilot_sim->update(fms_calc_step); } } point_3 offset = prev_pos(pilot_impl_->state().dyn_state.pos); double course = pilot_impl_->state().dyn_state.course; double roll = pilot_impl_->roll(); cpr orien(course, polar_point_3(offset).pitch, roll); set_state(state_t(pilot_impl_->state(), orien.pitch, orien.roll, state_.version + 1), false); if (pilot_impl_->instrument() && pilot_impl_->instrument_ended()) { fms::plan_t plan; if (get_plan().size() > 1) { auto tmp_plan = fms::plan_t(get_plan().begin()+1, get_plan().end()); std::swap(plan, tmp_plan); } else if (pilot_impl_->instrument()->kind() == fms::INSTRUMENT_APPROACH && pilot_impl_->state().dyn_state.cfg != fms::CFG_GD) { plan.push_back(fms::create_direction_instrument(boost::none, get_instruments_env())) ; } set_plan(plan); } } #endif } last_time_ = time; }
inline void error_report(lua_State *state, bool suc, int type, int idx, const char *msg) { if( suc ) return; std::ostringstream os; os << "lua parameter error: " << std::endl << "index [" << idx << "]" << std::endl << "real type [" << ::lua_typename(state, ::lua_type(state, idx)) << "]" << std::endl << "expected type [" << ::lua_typename(state, type) << "]" << std::endl << "information [" << msg << "]" << std::endl; throw parameter_error_t(state_t(state), std::move(os.str())); }
uint64_t next() { uint64_t cur_word, cur_m; uint8_t cur_depth; assert(m_stack.size()); boost::tie(cur_word, cur_m, cur_depth) = m_stack.back(); m_stack.pop_back(); while (cur_depth < m_bits) { boost::random::uniform_int_distribution<uint64_t> dist(0, cur_m); uint64_t left_m = dist(m_gen); uint64_t right_m = cur_m - left_m; // push left and right children, if present if (right_m > 0) { m_stack.push_back(state_t(cur_word | (uint64_t(1) << (m_bits - cur_depth - 1)), right_m, cur_depth + 1)); } if (left_m > 0) { m_stack.push_back(state_t(cur_word, left_m, cur_depth + 1)); } // pop next child in visit boost::tie(cur_word, cur_m, cur_depth) = m_stack.back(); m_stack.pop_back(); } if (cur_m > 1) { // push back the current leaf, with cur_m decreased by one m_stack.push_back(state_t(cur_word, cur_m - 1, cur_depth)); } return cur_word; }
void sample_sigmas(const graph_t<NodeCount> & graph, const ObservationIteratorT & observation_begin, const ObservationIteratorT & observation_end, OutputIteratorT & output_it, size_t num_samples, size_t burn_in, size_t sampling_interval) { sampler<sigma_t, probability_t, OutputIteratorT> s(output_it, burn_in, sampling_interval); Q<NodeCount> q; for(size_t i = 0; i < NodeCount; ++i) { for(size_t j = 0; j < num_edges; ++j) { sigma_t sigma(random_sigma<NodeCount>()); D_over_stop_state<NodeCount, ObservationIteratorT> d(graph, state_t(i, edges[j]), observation_begin, observation_end); // <sigma_t, Q<NodeCount>, D_over_stop_state<NodeCount, ObservationIteratorT>, sampler<sigma_t, probability_t, OutputIteratorT> > metropolis_hastings(sigma, q, d, s, num_samples / (NodeCount * num_edges)); } } }
static int handler(lua_State *state) { std::uint32_t len = 0; const char *msg = ::lua_tolstring(state, -1, &len); std::string error_msg; if( len == 0 ) error_msg = "unknown error"; else error_msg.append(msg, len); std::printf(error_msg.c_str()); std::printf("\n"); stack_trace(state, std::cerr); assert(0 && "lua has fatal error"); throw fatal_error_t(state_t(state), std::move(error_msg)); return 0; }
state_t graph_t<NodeCount>::previous(const state_t & state, sigma_t sigma) const { edge_t backward_edge = state.e == GRAPH_0 ? switch_setting(sigma, state) : GRAPH_0; /* Find the vertex connected to the edge backward_edge */ const typename graph_t<NodeCount>::connection_t *connection = std::find_if(m_graph[state.v], m_graph[state.v] + NodeCount, vertex_contains_edge<NodeCount>(backward_edge)); /*const typename graph_t<NodeCount>::connection_t *connection; unsigned int vertex; for(size_t i = 0; i < NodeCount; ++i) { if (m_graph[state.v][i].find(backward_edge) != std::string::npos) { connection = &m_graph[state.v][i]; vertex = i; break; } }*/ unsigned int vertex = connection - m_graph[state.v]; /* Find the edge connecting the newly found vertex to our state vertex */ return state_t(vertex, m_graph[vertex][state.v][std::find(connection->begin(), connection->end(), backward_edge) - connection->begin()]); }
void model::update(double time) { view::update(time); if(start_) { start_(); start_.clear(); } double dt = time - (last_update_ ? *last_update_ : 0); if (!cg::eq_zero(dt)) { update_model(time, dt); #if 0 if (!manual_controls_) #endif sync_phys(dt); #if 0 else { cg::geo_base_3 base = phys_->get_base(*phys_zone_); decart_position cur_pos = phys_vehicle_->get_position(); geo_position cur_glb_pos(cur_pos, base); set_state(state_t(cur_glb_pos.pos, cur_pos.orien.get_course(), 0)); } #endif sync_nodes_manager(dt); } last_update_ = time; }
void trace_plot(const graph_t<NodeCount> & graph, const ObservationIteratorT & observation_begin, const ObservationIteratorT & observation_end, OutputIteratorT & output_it, size_t num_samples) { Q<NodeCount> q; for(size_t i = 0; i < NodeCount; ++i) { for(size_t j = 0; j < num_edges; ++j) { D_over_stop_state<NodeCount, ObservationIteratorT> d(graph, state_t(i, edges[j]), observation_begin, observation_end); std::vector< probability_t > weighted_samples(num_samples / (NodeCount * num_edges), probability_t(0)); for(size_t k = 0; k < smooth_samples; ++k) { sigma_t sigma(random_sigma<NodeCount>()); // <sigma_t, Q<NodeCount>, D_over_stop_state<NodeCount, ObservationIteratorT>, sampler<sigma_t, probability_t, OutputIteratorT> > std::vector< std::pair<sigma_t, probability_t> > samples; std::back_insert_iterator< std::vector< std::pair<sigma_t, probability_t> > > inserter(samples); sampler<sigma_t, probability_t, std::back_insert_iterator< std::vector< std::pair<sigma_t, probability_t> > > > s(inserter, 0, 1); metropolis_hastings(sigma, q, d, s, num_samples / (NodeCount * num_edges)); //std::cerr << "asdf4, state: " << i << ", " << edges[j] << ", num_samples: " << samples.size() << " of " << (num_samples / (NodeCount * num_edges)) << std::endl; for(size_t i = 0; i < samples.size(); ++i) weighted_samples[i] += samples[i].second; } for(size_t i = 0; i < weighted_samples.size(); ++i) weighted_samples[i] /= smooth_samples; output_it = weighted_samples; ++output_it; } } }
/** * Tests an obstacle appearing during a trajectory execution */ TEST_F(StateMachineControlTest, TrajectoryInterrupt) { StateMachineControl *fsm_control = new StateMachineControl(lcm_, "../TrajectoryLibrary/trajtest/full", "tvlqr-action-out", "state-machine-state", "altitude-reset", false); //fsm_control->GetFsmContext()->setDebugFlag(true); SubscribeLcmChannels(fsm_control); ForceAutonomousMode(); float altitude = 100; // send an obstacle to get it to transition to a new time mav::pose_t msg = GetDefaultPoseMsg(); lcm_->publish(pose_channel_, &msg); ProcessAllLcmMessages(fsm_control); float point[3] = { 24, 0, 0+altitude }; SendStereoPointTriple(point); ProcessAllLcmMessages(fsm_control); lcm_->publish(pose_channel_, &msg); ProcessAllLcmMessages(fsm_control); // ensure that we have changed trajectories EXPECT_EQ_ARM(fsm_control->GetCurrentTrajectory().GetTrajectoryNumber(), 2); // from matlab Trajectory running_traj = fsm_control->GetCurrentTrajectory(); // wait for that trajectory to time out int64_t t_start = GetTimestampNow(); double t = 0; while (t < 1.0) { usleep(7142); // 1/140 of a second msg.utime = GetTimestampNow(); t = (msg.utime - t_start) / 1000000.0; Eigen::VectorXd state_t = running_traj.GetState(t); msg.pos[0] = state_t(0); msg.pos[1] = state_t(1); msg.pos[2] = state_t(2) + altitude; msg.vel[0] = state_t(6); msg.vel[1] = state_t(7); msg.vel[2] = state_t(8); double rpy[3]; rpy[0] = state_t(3); rpy[1] = state_t(4); rpy[2] = state_t(5); double quat[4]; bot_roll_pitch_yaw_to_quat(rpy, quat); msg.orientation[0] = quat[0]; msg.orientation[1] = quat[1]; msg.orientation[2] = quat[2]; msg.orientation[3] = quat[3]; msg.rotation_rate[0] = state_t(9); msg.rotation_rate[1] = state_t(10); msg.rotation_rate[2] = state_t(11); lcm_->publish(pose_channel_, &msg); ProcessAllLcmMessages(fsm_control); } // now add a new obstacle right in front! std::cout << "NEW POINT" << std::endl; lcm_->publish(pose_channel_, &msg); ProcessAllLcmMessages(fsm_control); float point2[3] = { 18, 12, 0+altitude }; SendStereoPointTriple(point2); ProcessAllLcmMessages(fsm_control); lcm_->publish(pose_channel_, &msg); ProcessAllLcmMessages(fsm_control); fsm_control->GetOctomap()->Draw(lcm_->getUnderlyingLCM()); BotTrans body_to_local; bot_frames_get_trans(bot_frames_, "body", "local", &body_to_local); fsm_control->GetTrajectoryLibrary()->Draw(lcm_->getUnderlyingLCM(), &body_to_local); fsm_control->GetTrajectoryLibrary()->Draw(lcm_->getUnderlyingLCM(), &body_to_local); bot_lcmgl_t *lcmgl = bot_lcmgl_init(lcm_->getUnderlyingLCM(), "Trjaectory"); bot_lcmgl_color3f(lcmgl, 0, 1, 0); fsm_control->GetCurrentTrajectory().Draw(lcmgl ,&body_to_local); bot_lcmgl_switch_buffer(lcmgl); bot_lcmgl_destroy(lcmgl); EXPECT_EQ_ARM(fsm_control->GetCurrentTrajectory().GetTrajectoryNumber(), 3); // from matlab delete fsm_control; UnsubscribeLcmChannels(); }
int main(int argc, const char **argv) { srand(time(NULL)); const size_t num_samples = 10000, burn_in = 5, sampling_interval = 5; const size_t NodeCount = 12; typename graph_t<NodeCount>::connection_t map[][NodeCount] = /*{ { "", "L", "0", "R" }, { "0","", "R", "L" }, { "0", "R","", "L" }, { "R", "0", "L","" }, };*/ { {"", "0", "R","","","","","","", "L","","" }, { "0","", "L", "R","","","","","","","","" }, { "0", "L","", "R","","","","","","","","" }, {"", "L", "R","","","","","","","","", "0" }, {"","","","","", "R","","", "L","", "0","" }, {"","","","", "R","","", "L", "0","","","" }, {"","","","","","","", "R","","", "L", "0" }, {"","","","","", "0", "R","","","", "L","" }, {"","","","", "R", "L","","","", "0","","" }, { "0","","","","","","","", "L","","", "R" }, {"","","","", "R","", "0", "L","","","","" }, {"","","", "L","","", "R","","", "0","","" }, }; graph_t<NodeCount> graph; graph.parse(map); const size_t observation_length = 100; typedef std::vector<edge_t> observation_sequence_t; observation_sequence_t observation; const state_t state(generate_observation_sequence<NodeCount>(graph, observation_length, std::back_insert_iterator<observation_sequence_t>(observation))); std::cerr << "observation sequence:"; std::copy(observation.begin(), observation.end(), std::ostream_iterator<edge_t>(std::cerr, ", ")); std::cerr << "stop state is: " << state << std::endl; //std::cerr << "previous:" << graph.previous(state_t(0, '0'), 0) << std::endl; typedef std::vector< std::pair<sigma_t, probability_t> > sigma_sequence_t; sigma_sequence_t sigmas; std::back_insert_iterator<sigma_sequence_t> inserter(sigmas); sample_sigmas<NodeCount>(graph, observation.begin(), observation.end(), inserter, num_samples, burn_in, sampling_interval); /*std::cerr << "sigmas:" << std::endl; probability_t p(0); for(sigma_sequence_t::iterator it = sigmas.begin(); it != sigmas.end(); ++it) { std::cerr << "(" << it->first << ", " << it->second << "), "; p += it->second; }*/ //std::cerr << "state_probability: " << state_probability<NodeCount>(state, graph, observation.begin(), observation.end(), sigmas.begin(), sigmas.end()) << std::endl; std::vector< std::pair<state_t, probability_t> > sorted_states; probability_t total_prob(0); for(size_t i = 0; i < NodeCount; ++i) { for(size_t j = 0; j < num_edges; ++j) { probability_t prob = state_probability<NodeCount>(state_t(i, edges[j]), graph, observation.begin(), observation.end(), sigmas.begin(), sigmas.end()); //std::cerr << "state_probability: " << prob << " for stop_state: " << state_t(i, edges[j]) << std::endl; total_prob += prob; sorted_states.push_back(std::make_pair(state_t(i, edges[j]), prob)); } } std::cerr << "total_prob: " << total_prob << std::endl; std::sort(sorted_states.begin(), sorted_states.end(), state_probability_sort_comp()); for(std::vector< std::pair<state_t, probability_t> >::const_iterator it = sorted_states.begin(); it != sorted_states.end(); ++it) { std::cerr << "probability: " << it->second << " for state: " << it->first; if (it->first.v == state.v && it->first.e == state.e) std::cerr << " [ answer ]"; std::cerr << std::endl; } /* * trace plot */ std::vector<std::vector< probability_t > > traces; std::back_insert_iterator< std::vector<std::vector< probability_t > > > traces_inserter(traces); trace_plot(graph, observation.begin(), observation.end(), traces_inserter, num_samples); //std::cerr << "plot done" << std::endl; std::fstream file("plot.py", std::ios_base::out); /* pl.semilogy([ prob / length for prob in p ]) #break pl.xlabel('interval') pl.ylabel('log(probability) + k') pl.title('Convergence plot') pl.grid(True) pl.savefig(filename, bbox_inches = 0) pl.show() */ file << "import pylab as pl" << std::endl << "pl.xlabel('interval')\npl.ylabel('log(probability) + k')\npl.title('Convergence plot')\npl.grid(True)" << std::endl; for(std::vector<std::vector< probability_t > >::const_iterator it = traces.begin(); it != traces.end(); ++it) { file << "pl.semilogy([ "; for(std::vector< probability_t >::const_iterator jt = it->begin(); jt != it->end() -1; ++jt) file << *jt << ", "; file << *(it->end() - 1) << " ])" << std::endl; } file << "pl.show()" << std::endl; file.close(); }
monotone_generator(uint64_t m, uint8_t bits, unsigned int seed) : m_gen(seed) , m_bits(bits) { m_stack.push_back(state_t(0, m, 0)); }
inline D_over_stop_state(const graph_t<NodeCount> & graph, const state_t & start_state, const ObservationIteratorT & observation_begin, const ObservationIteratorT & observation_end) : D<NodeCount, ObservationIteratorT>(graph, state_t(), observation_begin, observation_end), m_graph(graph), m_start_state(start_state), m_observation_begin(observation_begin), m_observation_end(observation_end) { }
inline observation_probability(const graph_t<NodeCount> & graph, const ObservationIteratorT & observation_begin, const ObservationIteratorT & observation_end) : D<NodeCount, ObservationIteratorT>(graph, state_t(), observation_begin, observation_end) { }