Example #1
0
void Tracematch::advance_current_states(States& current_states, UINT32 symbol_id)
{
    list<Vertex> next_states;
    unordered_set<Vertex> visited_states;

    OutEdgeIterator oei, oei_end;
    list<Vertex>::iterator i = current_states.begin();
    while (i != current_states.end()) {
        if (visited_states.find(*i) == visited_states.end()) {
            /* Unvisited state */
            for (boost::tie(oei, oei_end) = boost::out_edges(*i, graph);
                 oei != oei_end; ++oei) {
                /* Epsilon transition */
                if (graph[*oei].symbol_id == SYMBOL_ID_EPSILON) {
                    current_states.push_back(boost::target(*oei, graph));
                }
                /* Match */
                else if (graph[*oei].symbol_id == symbol_id) {
                    next_states.push_back(boost::target(*oei, graph));
                }
            }
            visited_states.insert(*i);
        }
        /* Erase this element */
        current_states.erase(i++);
    }

    current_states = next_states;
}
Example #2
0
int
setVarsInformation (void)
{
  Var::clearVarsInfo();
  vector<string> labels;
  YAP_Term labelsL = YAP_ARG1;
  while (labelsL != YAP_TermNil()) {
    YAP_Atom atom = YAP_AtomOfTerm (YAP_HeadOfTerm (labelsL));
    labels.push_back ((char*) YAP_AtomName (atom));
    labelsL = YAP_TailOfTerm (labelsL);
  }
  unsigned count = 0;
  YAP_Term stateNamesL = YAP_ARG2;
  while (stateNamesL != YAP_TermNil()) {
    States states;
    YAP_Term namesL = YAP_HeadOfTerm (stateNamesL);
    while (namesL != YAP_TermNil()) {
      YAP_Atom atom = YAP_AtomOfTerm (YAP_HeadOfTerm (namesL));
      states.push_back ((char*) YAP_AtomName (atom));
      namesL = YAP_TailOfTerm (namesL);
    }
    Var::addVarInfo (count, labels[count], states);
    count ++;
    stateNamesL = YAP_TailOfTerm (stateNamesL);
  }
  return TRUE;
}
int SVM::check_question_set(States& qset) {
	if (main_equation == NULL) return -1;
	std::cout << " [" << qset.traces_num() << "]";
	for (int i = 0; i < qset.p_index; i++) {
		int pre = -1, cur = 0;
		std::cout << ".";
		//std::cout << "\t\t" << i << ">";
		//gsets[QUESTION].print_trace(i);
		for (int j = qset.index[i]; j < qset.index[i + 1]; j++) {
			cur = Equation::calc(main_equation, qset.values[j]);
			//std::cout << ((cur >= 0) ? "+" : "-");
			if ((pre >= 0) && (cur < 0)) {
				// deal with wrong question trace.
				// Trace back to print out the whole trace and the predicted labels.
				std::cerr << "\t\t[FAIL]\n \t  Predict wrongly on Question traces." << std::endl;
				qset.print_trace(i);
				for (int j = qset.index[i]; j < qset.index[i + 1]; j++) {
					cur = Equation::calc(main_equation, qset.values[j]);
					std::cout << ((cur >= 0) ? "+" : "-");
				}
				std::cout << std::endl;
				return -1;
			}
			pre = cur;
		}
		//std::cout << "END" << std::endl;
	}
	std::cout << " [PASS]";
	return 0;
}
Example #4
0
bool Tracematch::current_states_is_end(const States& current_states)
{
    States states = current_states;
    unordered_set<Vertex> visited_states;

    OutEdgeIterator oei, oei_end;
    list<Vertex>::iterator i = states.begin();
    while (i != states.end()) {

        if (visited_states.find(*i) == visited_states.end()) {
            /* Unvisited state */
            if (*i == graph_properties.end) {
                return true;
            }

            for (boost::tie(oei, oei_end) = boost::out_edges(*i, graph); oei != oei_end; ++oei) {
                /* Epsilon transition */
                if (graph[*oei].symbol_id == SYMBOL_ID_EPSILON) {
                    states.push_back(boost::target(*oei, graph));
                }
            }
            visited_states.insert(*i);
        }

        /* Erase this element */
        states.erase(i++);
    }

    return false;
}
Example #5
0
bool DFAConverter::build(int start, int last,
		const std::vector<NFATran>& trans,
		const std::map<size_t, Tag>& tags) {
	States lasts;
	lasts.insert(last);

	return build(start, lasts, trans, tags);
}
Example #6
0
States Database::fillState()
{
    States s;
    this->query.first();
    this->record = this->query.record();
    s.setId(this->query.value(this->record.indexOf("id")).toUInt());
    s.setDescription(this->query.value(this->record.indexOf("name")).toString());
    return s;
}
 /**
  * 
  * @brief returns all targets that correspond with the given source 
  *
  * @param - source: the source whose targets to look for
  * @return the set of all targets that correspond with the given source 
  *
  */
 const TransitionStorage::States TransitionStorage::getTargets( State source ) const
 {
   States targets;
   const Info::Internals & src = T_info.fromTrans(source);
   for( Info::InternalIterator it = src.begin(); it != src.end(); it++ )
   {
     targets.insert(getTarget(*it));
   }
   return targets;
 }
 /**
  * 
  * @brief returns all entry sites that correspond with the given call site
  *
  * @param - callSite: the call site whose entry sites to look for
  * @return the set of all entry sites that correspond with the given call site
  *
  */
 const TransitionStorage::States TransitionStorage::getEntries( State callSite ) const
 {
   States entries;
   const Info::Calls & cll = T_info.callTrans(callSite);
   for( Info::CallIterator it = cll.begin(); it != cll.end(); it++ )
   {
     entries.insert(getEntry(*it));
   }
   return entries;
 }
void map_ids(const States& o){
	Container::map_id_to_number()[o.getId()] = Container::get_id_counter();
	if(not o.calls.empty()){
		for(std::vector<Call>::const_iterator i=o.calls.begin();i!=o.calls.end();i++){
			i->lib=o.lib;
			i->id = o.getId();
			map_ids(*i);
		}
	}
}
 /**
  * 
  * @brief returns all return sites that correspond with the given call site
  *
  * @param - callSite: the call site whose return sites to look for
  * @return the set of all return sites that correspond with the given call site
  *
  */
 const TransitionStorage::States TransitionStorage::getReturnSites( State callSite ) const
 {
   States returns;
   const Info::Returns & pred = T_info.predTrans(callSite);
   for( Info::ReturnIterator it = pred.begin(); it != pred.end(); it++ )
   {
     returns.insert(getReturnSite(*it));
   }
   return returns;
 }
void Experiment::timer_cb(const ros::TimerEvent& event)
{  
	switch(mode_)
	{
	case MODE_REP_START:
	  actions_->Start();
	  last_time_ = ros::Time::now().toSec();
		state_ = states_->GetState();
		action_ = qobj_->GetAction(state_);
		actions_->Move(action_);
		ROS_INFO("Starting rep: %d", cnt_rep_);
		mode_ = MODE_REP;
		cnt_timesteps_++;
		break;
	case MODE_REP:
    state_p_ = (int)states_->GetState();

		if (learn_)
		{
			reward_ = states_->GetReward();
			qobj_->Update(reward_, state_, state_p_, action_);
			ROS_INFO("Action: %d, produced state: %d with reward: %f", action_, state_p_, reward_);
			ROS_INFO("Table: \n%s", qobj_->PrintTable().c_str());
		}

		state_ = state_p_;

    action_ = qobj_->GetAction(state_);
		actions_->Move(action_);
		
		cnt_timesteps_++;

		if (getDistance() < goal_radius_ || outOfBounds())
		{
      stopAndMoveToStart();
		}
		break;
	case MODE_RETURN:
  	if (move_stopped_ == true)
		{
			move_stopped_ = false;
			mode_ = MODE_REP_START;
      qobj_->DecreaseTemp();
			cnt_rep_++;
		}

		if (cnt_rep_ > num_reps_)
			mode_ = MODE_DONE;
		break;
	case MODE_DONE:
	  //lc_->ShowImage();
	  exit(1);
		break;
	}
}
Example #12
0
void R70(std::vector<Dynamic>& __ret) {
	//arguments
 Dynamic  hllr__0 =  Dynamic (__ret.back()); __ret.pop_back();
	 Dynamic  retval;

        States x;
        x.push_back(ptr<State>(StateArgScope((States&)hllr__0)));
        retval = x;
    
	__ret.push_back(retval);
}
Example #13
0
void R81(std::vector<Dynamic>& __ret) {
	//arguments
 ptr<int>          hllr__0 =  ptr<int>         (__ret.back()); __ret.pop_back();
	 Dynamic  retval;

        States x;
        x.push_back(ptr<State>(StateSymbol(*hllr__0)));
        retval = x;
    
	__ret.push_back(retval);
}
 /**
  * 
  * @brief returns all call sites that correspond with the given exit - return site pair
  *
  * @param - exitSite: the exit of the pair whose call sites to look for
  * @param = returnSite: the return site of the pair whose call sites to look for
  * @return the set of all call sites that correspond with the exit - return site pair
  *
  */
 const TransitionStorage::States TransitionStorage::getCallSites( State exitSite, State returnSite ) const
 {
   States calls;
   const Info::Returns & exit = T_info.exitTrans(exitSite);
   for( Info::ReturnIterator it = exit.begin(); it != exit.end(); it++ )
   {
     if( getReturnSite(*it) == returnSite )
       calls.insert(getCallSite(*it));  
   }
   return calls;
 }
Example #15
0
void R82(std::vector<Dynamic>& __ret) {
	//arguments
 ptr<std::string>  hllr__0 =  ptr<std::string> (__ret.back()); __ret.pop_back();
	 Dynamic  retval;

        States x;
        x.push_back(ptr<State>(StateNoise(*hllr__0)));
        retval = x;
    
	__ret.push_back(retval);
}
Example #16
0
void R27(std::vector<Dynamic>& __ret) {
	//arguments
 ptr<int>          hllr__1 =  ptr<int>         (__ret.back()); __ret.pop_back();
Dynamic hllr__0 = __ret.back(); __ret.pop_back();
	 Dynamic  retval;

        States list;
        list.push_back(ptr<State>(StateSymbol(*hllr__1)));
        retval = StateMBrack(dMScopeBrack(list));
    
	__ret.push_back(retval);
}
Example #17
0
void Experiment::timer_cb(const ros::TimerEvent& event)
{
	switch(mode_)
	{
	case MODE_REP_START:
		state_ = (int)states_->GetState();
		ROS_INFO("Starting rep: %d", cnt_rep_);
		mode_ = MODE_REP;
		break;
	case MODE_REP:
		action_ = qobj_->GetAction(state_);
		actions_->Move((Actions::moveType)action_);
		state_p_ = (int)states_->GetState();

		ROS_INFO("Action: %d, produced state: %d", action_, state_p_);

		if (learn_)
		{
			reward_ = states_->GetReward();
			qobj_->Update(reward_, state_, state_p_, action_);
			ROS_INFO("Action: %d, produced state: %d with reward: %f", action_, state_p_, reward_);
			ROS_INFO("Table: \n%s", qobj_->PrintTable().c_str());
		}

		state_ = state_p_;

		if (states_->GetDistance() < radius_)
		{
			mode_ = MODE_RETURN;
			ROS_INFO("Completed rep: %d, returning to start location", cnt_rep_);

			// Move to starting spot
			srv_.request.pose.position.x = start_x_;
			srv_.request.pose.position.y = start_y_;
			client_.call(srv_);
		}
		break;
	case MODE_RETURN:
		if (move_stopped_ == true)
		{
			move_stopped_ = false;
			mode_ = MODE_REP_START;
			cnt_rep_++;
		}

		if (cnt_rep_ > num_reps_)
			mode_ = MODE_DONE;
		break;
	case MODE_DONE:
		break;
	}
}
Example #18
0
static void merge_tags(const States& states,
		const std::map<size_t, Tag>& from,
		int s, std::map<size_t, Tag> *to) {
	size_t size = states.size();
	for (States::const_iterator it = states.begin();
			it != states.end(); ++it) {
		assert(*it >= 0);
		std::map<size_t, Tag>::const_iterator fit = from.find(*it);
		if (fit != from.end()) {
			Tag& tag = (*to)[s];
			tag.insert(fit->second.begin(), fit->second.end());
		}
	}
}
	/* Name: validate
	* Purpose: To find if the all of the transtions are valid.
	* Operation: This method it checks that each transition is based on the class States,
		Tape_Alphabet, and moves R or L.
	*/
void Transition_Function::validate(const Tape_Alphabet &tape_alphabet, States states, bool & valid){

		// Prevent two transitions from having the same source_state and Read_Character
	for (unsigned int i = 0; i < transitions.size(); i++){		
		for(unsigned int z = i + 1; z < transitions.size(); z++){			
			if(transitions[i].Source_State() == transitions[z].Source_State()
			&& transitions[i].Read_Character() == transitions[z].Read_Character()){
				valid = false;
				cout << "Error: Two transitions have the same source state '" << transitions[i].Source_State() << "' and read character '" << transitions[i].Read_Character() << "'.\n";
			}			
		}		
	}

		// Validate the the tape alphabet elements.
	for (unsigned int i = 0; i < transitions.size(); i++){

			// The read character is not contained within the tape alphabet.
		if (!tape_alphabet.is_element(transitions[i].Read_Character())){			
			cout << "Error: Transition read character '" << transitions[i].Read_Character() << "' is not in tape alphabet.\n";
			valid = false;
		}

			// The write character is not contained within the tape alphabet.
		if (!tape_alphabet.is_element(transitions[i].Write_Character())){
			cout << "Error: Transition write character '" << transitions[i].Write_Character() << "' is not in tape alphabet.\n";
			valid = false;
		}
	}

		// Validate that all of the states are in the list of states.
	for (unsigned int i = 0; i < transitions.size(); i++){

			// The source state is not in the list of states.
		if (!states.is_element(transitions[i].Source_State())){
			cout << "Error: Transition source state '" << transitions[i].Source_State() << "' is not in states.\n";

			valid = false;
		}

			// The destination state is not in the list of states. 
		if (!states.is_element(transitions[i].Destination_State())){
			cout << "Error: Transition destination state '" << transitions[i].Destination_State() << "' is not in states.\n";

			valid = false;
		}
	}
	
}
Example #20
0
double sample_hmm_posterior(
    int blocklen, const LocalTree *tree, const States &states,
    const TransMatrix *matrix, const double *const *fw, int *path)
{
    // NOTE: path[n-1] must already be sampled

    const int nstates = max(states.size(), (size_t)1);
    double A[nstates];
    double trans[nstates];
    int last_k = -1;
    double lnl = 0.0;

    // recurse
    for (int i=blocklen-2; i>=0; i--) {
        int k = path[i+1];

        // recompute transition probabilities if state (k) changes
        if (k != last_k) {
            for (int j=0; j<nstates; j++)
                trans[j] = matrix->get(tree, states, j, k);
            last_k = k;
        }

        for (int j=0; j<nstates; j++)
            A[j] = fw[i][j] * trans[j];
        path[i] = sample(A, nstates);
        //lnl += log(A[path[i]]);

        // DEBUG
        assert(trans[path[i]] != 0.0);
    }

    return lnl;
}
Example #21
0
void MapController::stateChanged(States st)
{
    Q_D(MapController);

    QHash<int, bool> hash;
    if (st.testFlag(stMove)) {
        QList<int> res = d->mapStBt.values(stMove);
        foreach (int key, res)
            hash[key] = true;
    }
Example #22
0
// 所有从from通过一次ch到达的NFA状态
// 这里有-1,表示上次fill只有一个最终状态,即-1
static States expand(const std::vector<NFATran>& trans, const States& from, char ch) {
	States to;
	for (States::const_iterator it = from.begin();
			it != from.end(); ++it) {
		int s = *it;
		if (s == -1) {
			to.clear();
			to.insert(-1);
			break;
		}

		const NFATran& tran = trans[s];
		NFATran::const_iterator tit = tran.find(ch);
		if (tit == tran.end()) {
			continue;
		}

		const States& next = tit->second;
		for (States::const_iterator nit = next.begin();
			nit != next.end(); ++nit) {
			to.insert(*nit);
		}
	}

	return to;
}
Example #23
0
//Return a queue of the calculated transition pairs, based on the non-deterministic
//  finite automaton, initial state, and queue of inputs; each pair in the returned
//  queue is of the form: input, set of new states.
//The first pair contains "" as the input and the initial state.
//If any input i is illegal (does not lead to any state in the non-deterministic finite
//  automaton), ignore it.
TransitionsQueue process(const NDFA& ndfa, std::string state, const InputsQueue& inputs) {

	TransitionsQueue answer;
	States initialState;

	initialState.insert(state);
	answer.enqueue(Transitions("", (initialState)));

	for (auto x : inputs)
	{
		if((ndfa[state].has_key(x)))
		{
			answer.enqueue(Transitions(x, ndfa[state][x]));
			//std::cout << "answer after enqueue: " << answer << std::endl;
		}
		else
		{
			break;
		}
	}
	return answer;
}
Example #24
0
int Database::insertState(States s)
{
    QVariant name = s.getDescription().toLower();
    if(!this->stateExist(name)){
        this->query.prepare("INSERT INTO States (name) VALUES (:name);");
        this->query.bindValue(":name",name);
        if(!this->query.exec()){
            this->showError(this->query.lastError());
            return -1;
        }
        return this->query.lastInsertId().toInt();
    }
    return 0;
}
Example #25
0
void States::add( const States& a)
{
    if( a.getNumFeatures()!=this->getNumFeatures() )
    {
        std::cerr << "add: feature mismatch" << std::endl;
        exit(EXIT_FAILURE);
    }
    this->X += a.X;
    this->V += a.V;
    for(int i = 0; i<getNumFeatures(); i++ )
    {
        this->features[i]->set_body_position( this->features[i]->get_body_position() +
                a.features[i]->get_body_position() );
        this->features[i]->set_world_position( this->features[i]->get_world_position() +
                a.features[i]->get_world_position() );
    }
    this->b += a.b;
}
std::string searchSimpleState(const States& o){
	if(not o.calls.empty()){
		for(std::vector<Call>::const_iterator i=o.calls.begin();i!=o.calls.end();i++){
			if(i->type=="task"){
				return i->getId();
			}
			if(i->type=="bt"){
				return i->getId()+"/"+i->text;
			}
			if(i->type=="fsm"){
				bool isResolved = o.lib->contains_fsm(i->text);
				if(isResolved){
					const Fsm& fsm = o.lib->fsms.at(i->text);
					return searchSimpleState(fsm.states.front());
				}
			}
		}
	}else{
		return o.getId();
	}
	return "NOT-FOUND";
}
Example #27
0
// compute one block of forward algorithm with compressed transition matrices
// NOTE: first column of forward table should be pre-populated
// This can be used for testing
void arghmm_forward_block_slow(const LocalTree *tree, const int ntimes,
                               const int blocklen, const States &states,
                               const LineageCounts &lineages,
                               const TransMatrix *matrix,
                               const double* const *emit, double **fw)
{
    const int nstates = states.size();

    // get transition matrix
    double **transmat = new_matrix<double>(nstates, nstates);
    for (int k=0; k<nstates; k++)
        for (int j=0; j<nstates; j++)
            transmat[j][k] = matrix->get(tree, states, j, k);

    // fill in forward table
    for (int i=1; i<blocklen; i++) {
        const double *col1 = fw[i-1];
        double *col2 = fw[i];
        double norm = 0.0;

        for (int k=0; k<nstates; k++) {
            double sum = 0.0;
            for (int j=0; j<nstates; j++)
                sum += col1[j] * transmat[j][k];
            col2[k] = sum * emit[i][k];
            norm += col2[k];
        }

        // normalize column for numerical stability
        for (int k=0; k<nstates; k++)
            col2[k] /= norm;
    }

    // cleanup
    delete_matrix<double>(transmat, nstates);
}
Example #28
0
void sample_recombinations(
    const LocalTrees *trees, const ArgModel *model,
    ArgHmmMatrixIter *matrix_iter,
    int *thread_path, vector<int> &recomb_pos, vector<NodePoint> &recombs,
    bool internal)
{
    States states;
    LineageCounts lineages(model->ntimes);
    const int new_node = -1;
    vector <NodePoint> candidates;
    vector <double> probs;

    // loop through local blocks
    for (matrix_iter->begin(); matrix_iter->more(); matrix_iter->next()) {

        // get local block information
        ArgHmmMatrices &matrices = matrix_iter->ref_matrices();
        LocalTree *tree = matrix_iter->get_tree_spr()->tree;
        lineages.count(tree, internal);
        matrices.states_model.get_coal_states(tree, states);
        int next_recomb = -1;

        // don't sample recombination if there is no state space
        if (internal && states.size() == 0)
            continue;

        int start = matrix_iter->get_block_start();
        int end = matrix_iter->get_block_end();
        if (matrices.transmat_switch || start == trees->start_coord) {
            // don't allow new recomb at start if we are switching blocks
            start++;
        }

        //int start = end + 1;  // don't allow new recomb at start
        //end = start - 1 + matrices.blocklen;

        // loop through positions in block
        for (int i=start; i<end; i++) {

            if (thread_path[i] == thread_path[i-1]) {
                // no change in state, recombination is optional

                if (i > next_recomb) {
                    // sample the next recomb pos
                    int last_state = thread_path[i-1];
                    TransMatrix *m = matrices.transmat;
                    int a = states[last_state].time;
                    double self_trans = m->get(
                        tree, states, last_state, last_state);
                    double rate = 1.0 - (m->norecombs[a] / self_trans);

                    // NOTE: the min prevents large floats from overflowing
                    // when cast to int
                    next_recomb = int(min(double(end), i + expovariate(rate)));
                }

                if (i < next_recomb)
                    continue;
            }


            // sample recombination
            next_recomb = -1;
            State state = states[thread_path[i]];
            State last_state = states[thread_path[i-1]];

            // there must be a recombination
            // either because state changed or we choose to recombine
            // find candidates
            candidates.clear();
            int end_time = min(state.time, last_state.time);
            if (state.node == last_state.node) {
                // y = v, k in [0, min(timei, last_timei)]
                // y = node, k in Sr(node)
                for (int k=tree->nodes[state.node].age; k<=end_time; k++)
                    candidates.push_back(NodePoint(state.node, k));
            }

            if (internal) {
                const int subtree_root = tree->nodes[tree->root].child[0];
                const int subtree_root_age = tree->nodes[subtree_root].age;
                for (int k=subtree_root_age; k<=end_time; k++)
                    candidates.push_back(NodePoint(subtree_root, k));
            } else {
                for (int k=0; k<=end_time; k++)
                    candidates.push_back(NodePoint(new_node, k));
            }

            // compute probability of each candidate
            probs.clear();
            for (vector<NodePoint>::iterator it=candidates.begin();
                 it != candidates.end(); ++it) {
                probs.push_back(recomb_prob_unnormalized(
                    model, tree, lineages, last_state, state, *it));
            }

            // sample recombination
            recomb_pos.push_back(i);
            recombs.push_back(candidates[sample(&probs[0], probs.size())]);

            assert(recombs[recombs.size()-1].time <= min(state.time,
                                                         last_state.time));
        }
    }
}
Example #29
0
 void addCreature(double currentPos){
     States creature;
     creature.initialize(rStrings);
     creature.set(currentPos);
     creatures.push_back(creature);
 }
Example #30
0
// 所有能从from通过EPSILON能达到的NFA状态(包括from)
static States fill(const std::vector<NFATran>& trans, const States& last, const States& from, bool* is_last) {
	std::queue<int> q;
	for (States::const_iterator it = from.begin();
			it != from.end(); ++it) {
		q.push(*it);
	}

	// ends表示终点(即最终状态),要判断这次转移是否只有-1
	States ends;
	States to;
	while (!q.empty()) {
		int s = q.front();
		q.pop();

		to.insert(s);
		if (last.find(s) != last.end()) {
			*is_last = true;
		}

		if (s == -1) {
			ends.insert(-1);
			continue;
		}

		const NFATran& tran = trans[s];
		NFATran::const_iterator it = tran.find(EPSILON);
		if (it == tran.end()) {
			ends.insert(s);
			continue;
		}

		const States& next = it->second;
		for (States::const_iterator nit = next.begin();
				nit != next.end(); ++nit) {
			if (to.find(*nit) == to.end()) {
				q.push(*nit);
			}
		}
	}

	if (ends.find(-1) == ends.end() || ends.size() > 1) {
		to.erase(-1);
	} else {
		to.clear();
		to.insert(-1);
	}

	return to;
}