void DotFileGenerator::generate(SMDescription smDesc) { newGraph(smDesc.title); for( int i=0; i < smDesc.stateList.size(); i++) { addState(smDesc.stateList.at(i)); } out << endl; for( int i=0; i < smDesc.transitionList.size(); i++) { addTransition(smDesc.transitionList.at(i)); } endGraph(); }
void DFA::DFAState::read(Source &r) { #undef pt #define pt(a) //pr(a) pt(("DFAState::read\n")); r >> flags_; short sCount; r >> sCount; pt((" flags=%x #syms=%d\n",flags_,sCount)); for (short i = 0; i < sCount; i++) { char sym, dest; r >> sym >> dest; pt((" sym %d, trans %d\n",(byte)sym,(byte)dest)); addTransition((byte)dest,(byte)sym); } }
static void make(const ToolPalette_T& palette, QState* waitState, QState& parent) { /// TimeNode auto moveTimeNode = new MoveTimeNodeState<Scenario::Command::MoveEventMeta, Scenario_T, ToolPalette_T>{ palette, palette.model(), palette.context().commandStack, palette.context().objectLocker, &parent}; iscore::make_transition<ClickOnTimeNode_Transition<Scenario_T>>(waitState, moveTimeNode, *moveTimeNode); moveTimeNode->addTransition(moveTimeNode, finishedState(), waitState); }
void DialogTransition::on_buttonBox_accepted() { QString sourceStateName=ui->cb_State->currentText(); QChar symbolRead=ui->cb_readSymbol->currentText().at(0); QChar symbolWrite=ui->cb_writeSymbol->currentText().at(0); QString targetStateName=ui->cb_targetState->currentText(); QChar movement; QString mov=ui->cb_movement->currentText(); if(mov=="I") movement='L'; else if(mov=="D") movement='R'; else movement='S'; emit addTransition(sourceStateName,symbolRead,symbolWrite,movement, targetStateName); }
static void make(const ToolPalette_T& palette, QState* waitState, QState& parent) { /// Constraint /// //TODO remove useless arguments to ctor auto moveConstraint = new MoveConstraintState<Scenario::Command::MoveConstraint, Scenario_T, ToolPalette_T>{ palette, palette.model(), palette.context().commandStack, palette.context().objectLocker, &parent}; iscore::make_transition<ClickOnConstraint_Transition<Scenario_T>>(waitState, moveConstraint, *moveConstraint); moveConstraint->addTransition(moveConstraint, finishedState(), waitState); }
int StateMachine::loadFromFile(QString fileName) { QRegExp rx("^\\s*(\\S+)\\s--\\s(\\S+)\\s/\\s(\\S+)\\s->\\s(\\S+)\\s*$"); QFile file(fileName); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { std::cerr << "Error while opening file \"" << fileName.toStdString() << "\"." << std::endl; exit(1); } QTextStream in(&file); int i = 1; while (!in.atEnd()) { QString currLine = in.readLine(); int pos = rx.indexIn(currLine); if (pos == -1) { std::cerr << "Syntax error at input line " << i << "." << std::endl; exit(1); } QStringList matched = rx.capturedTexts(); State initialState = matched[1], finalState = matched[4]; Input input = matched[2]; Output output = matched[3]; Transition *t = new Transition(initialState, finalState, input, output); addTransition(t); i++; } file.close(); return 0; }
/*! Adds an unconditional transition from this state to the given \a target state. */ void QtState::addTransition(QtAbstractState *target) { addTransition(new UnconditionalTransition(), target); }
/*! Adds a transition that's triggered by the finished event of this state, and that has the given \a target state. \sa QtStateFinishedEvent */ void QtState::addFinishedTransition(QtAbstractState *target) { addTransition(new QtStateFinishedTransition(this), target); }
/*! Adds the given \a transition. The transition has this state as the source, and has no target. */ void QtState::addTransition(QtAbstractTransition *transition) { addTransition(transition, QList<QtAbstractState*>()); }
//Returns Start State for the NFA of the input REGEX. //This builds an individual NFA for the input REGEX and stores the start and final state. //'$' represents EPSILON transition. void buildIndividualNFA(char pattern[], char POSTFIX[]) { int i = 0; char ch; Stack starts, ends; init(&starts); init(&ends); while(ch = POSTFIX[i++]) { if(ch == '|')//Union { STATE start1 = pop(&starts), start2 = pop(&starts); STATE end1 = pop(&ends), end2 = pop(&ends); STATE newStart = nextAvailableState++, newEnd = nextAvailableState++; addTransition(newStart, start1, '$'); addTransition(newStart, start2, '$'); addTransition(end1, newEnd, '$'); addTransition(end2, newEnd, '$'); push(&starts, newStart);push(&ends, newEnd); } else if(ch == '#')//Kleene Closure { STATE start = pop(&starts), end = pop(&ends); STATE newStart = nextAvailableState++, newEnd = nextAvailableState++; addTransition(end, start, '$'); addTransition(newStart, newEnd, '$'); addTransition(newStart, start, '$'); addTransition(end, newEnd, '$'); push(&starts, newStart);push(&ends, newEnd); } else if(ch == '&') { STATE start1 = pop(&starts), start2 = pop(&starts); STATE end1 = pop(&ends), end2 = pop(&ends); addTransition(end2, start1, '$'); push(&starts, start2);push(&ends, end1); } else if(ch == '@') { char a = POSTFIX[i++], b = POSTFIX[i++]; int j; STATE start = nextAvailableState++, end = nextAvailableState++; for(j=a;j<=b;++j) addTransition(start, end, j); push(&starts, start);push(&ends, end); } else { STATE start = nextAvailableState++, end = nextAvailableState++; addTransition(start, end, ch); push(&starts, start);push(&ends, end); } } addStartState(pop(&starts)); addFinalState(pop(&ends), pattern); }
//![12] void addState(QState *state, QAbstractAnimation *animation) { StateSwitchTransition *trans = new StateSwitchTransition(++m_stateCount); trans->setTargetState(state); addTransition(trans); trans->addAnimation(animation); }
Transition *Automaton::addEndLine(State *start, State *end) { Transition * newTransition=addTransition(start,end); newTransition->type=TransitionType::ENDLINE; return newTransition; }
Transition *Automaton::addEndCapture(State *start, State *end) { Transition * newTransition=addTransition(start,end); newTransition->type=TransitionType::ENDCAPTURE; return newTransition; }
// Methode d'apprentissage d'un PRFA prefixe RESULT PPRFA::DEES (T_ModeVariables modeVariables, Sample & S, double prec, double epsprime, bool verbose, T_ModeReturn moderet, T_ModeEpsilon modeeps, unsigned int maxstates, unsigned int seuil, int maxmots, int maxsearches, bool bestsearch, bool stepssave) { try { // ------------------------- affichage des informations ---------------------- // if (verbose) { cout << "\t\t=== DEES ==="; cout << "\nSample size = " << S.size (); cout << "\nprecision = " << prec; cout << "\nbound = " << epsprime; cout << "\nmoderet = "; switch (moderet) { case ::begin: cout << "begin"; break; case ::end: cout << "end"; } cout << "\nmodeeps = "; switch (modeeps) { case epsfixed: cout << "epsfixed"; break; case variable: cout << "variable"; break; case word_variable: cout << "word_variable"; break; } cout << "\nmaxstates = " << maxstates; cout << "\nseuil = " << seuil; cout << "\nmaxmots = " << maxmots << endl; } if (prec == 0) { return becomePrefixTree(S); } // -------------------------- INITIALISATION ---------------------- vide (); // on initialise le PFA. if (S.size () == 0) throw 0; // on verifie que l'echantillon n'est pas vide. S.prefixialise (); // Transformation de l'Èchantillon en echantillon prefixiel. Sigma = S.alphabet (); // on met ‡† jour l'alphabet alph = S.dictionnaire (); // et le dictionnaire associÈ. // Declaration Word v; // the word v which represent the word associated to the state to add. list < Word > X; // The set of words which are potential prime residuals. Sample::const_iterator u; // current word of the sample. float val; // a floating value used to calculate tau. Word w; // a word Word ww; // another word Lettre a; // a letter (we will have v=wa) Alphabet::const_iterator b; // pour enumerer toutes les lettres SFunc solution; // the system solution SFunc solutiontemp; // a temporary solution StateSet::iterator q; // Pour enumerer les √©tats Simplex simplx; // L'objet simplexe qui contient les algorithmes de resolution de systemes. set < Word, ordre_mot > W; // L'ensemble de mots à tester Word::iterator z; // last letter // --- init variables --- v.clear (); // v = epsilon (empty word) // X is the set of one letter words of S when prefixialised val = 0; for (u = ++(S.begin ()); (u != S.end ()) && (u->first.size () < 2); ++u) { X.push_back (u->first); val += u->second; } // We create the first state (epsilon) addState (v, 1, 1 - (float(val) / float(S.size ()))); W.clear (); // liste_mots_associes(W,v,S,maxmots); ajoute_mots_associes(W,v,S,maxmots); // There may be a general state State generalstate = -1; // Step saving string svgfile="etape-"; // -------------------------- LEARNING LOOP ----------------------- if (verbose) cout << "Ajout des états : " << endl; // For each element in X (the temporary list) while (!X.empty ()) { v = *(X.begin ()); // v <-- min X; X.pop_front (); // X <-- X\{v} ; // wa=v w = v; a = *(w.rbegin ()); z = w.end (); --z; w.erase (z); //w.pop_back (); //~ if (verbose) { //~ cout << "["; //~ cout << affiche(v) <<"]"; //~ cout.flush(); //~ } if (stepssave) { save(svgfile+affiche(v)); } /// 3 possible cases : /// (1) not enought data (make a loop to the general state) /// (2) there is no solution (add a new state and update X) /// (3) there is a solution (make a return of transitions) if (S[v] < seuil) // case (1) not enought data { // cout << "CASE (1)" << endl; if (generalstate == -1) { // if the general state was not created, we create it generalstate = addState (v, 0, 1 / float(Sigma.size () + 1)); for (b = Sigma.begin (); b != Sigma.end (); ++b) { MA::addTransition (generalstate, *b, generalstate, 1 / float(Sigma.size () + 1)); } } addTransition (w, a, generalstate, ((double) S[v] / (double) S[w])); XR[w + a] = generalstate; if (verbose) { cout << "S"; cout.flush (); } } else { solution.clear (); // init solutions // calculate the solution of the linear system sol (modeVariables, solution, v, S, simplx, prec / pow(float(S[v]), float(0.4)), moderet, modeeps, W, maxmots, false); if (solution.empty ()) // if there is no solution (case (2) add a new state and update X { // cout << "CASE (2)" << endl; // if there is no solution then we add the state associated with v // updating X and tau (val will contain tau[v]) val = 0; for (b = Sigma.begin (); b != Sigma.end (); b++) { // pour toute les lettres de l'alphabet v += *b; //v.push_back (*b); // on ajoute b a la fin de v if (S.find (v) != S.end ()) { // si vb appartient a l'echantillon, alors X.push_back (v); // on l'ajoute a X val += S[v]; // et val = val + S(vb\Sigma^*) } z = v.end (); --z; v.erase (z); //v.pop_back (); // on efface la derniere lettre pour que la variable v = le mot v. } if (verbose) { cout << "A"; cout.flush (); } addState (v,0, 1 - (val / (double) S[v])); // adding the new state if (size () > maxstates) throw 1; addTransition (w, a, v, ((double) S[v] / (double) S[w])); // updating phi : phi(w,a,wa) = S(wa)/S(w) } else { // cout << "CASE (3)" << endl; // else we return transitions if (verbose) { cout << "R"; cout.flush (); } for (q = Q.begin (); q != Q.end (); q++) { val = (float) solution[*q] * ((double) S[v] / (double) S[w]); if (val != 0) { addTransition (w, a, *q, val); } } } } } if (verbose) cout << endl; erase_transitions (epsprime, -epsprime); // deleting transitions less than epsprime //best_transition_delete(S,verbose); if (modeVariables == nonconstrained) { return VAL(0); } else { return renormalise (); // renormalisation in order to disable borders effects } } catch (int erreur) { if (PFA_VERBOSE) { if (erreur != 1) { cerr << "PFA::DEES(Sample S)" << endl; } switch (erreur) { case 0: cerr << "Sample vide !!!" << endl; break; case 1: // il y a trop d'etats erase_transitions (epsprime); return renormalise (); break; default: cerr << "Erreur n∞" << erreur << endl; } } return ERR (erreur); } }
void ActionPattern::xmlInit(const QDomNode& _node, const ActionPatternMap& _apMap) { ArbiterRepository * ar = ArbiterRepository::instance(); BehaviourRepository * br = BehaviourRepository::instance(); // first pass // retrieve arbiter // we need it to register the behaviours there QDomNode n = _node.firstChild(); while( !n.isNull() ) { QDomElement e = n.toElement(); // try to convert the node to an element. if( !e.isNull() ) { // the node was really an element. QDomAttr attribute = e.attributeNode("name"); // retrieve arbiter if (e.tagName()=="arbiter") { if (arbiter_ == NULL) { if (!attribute.isNull() && !attribute.value().isEmpty()) { string name(attribute.value()); Arbiter* a; if ((a = ar->getArbiter(name)) != 0) { ArbiterParameters * params = a->getParametersInstance(); arbiter(a, params); } else { std::string error("Arbiter not registered: " + name); throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup(error.c_str())); } } else { throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup("Arbiter without name.")); } } else { throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup("Multiple arbiters specified.")); } } // syntax checking else if (e.tagName() != "behaviour" && e.tagName() != "transition") { std::string error("Unknown tag name: " + string(e.tagName())); throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup(error.c_str())); } } n = n.nextSibling(); } // There has to be exact one arbiter if (arbiter_ == NULL) { std::string error("ActionPattern without an arbiter: " + actionPatternName_); throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup(error.c_str())); } // second pass // retrieve behaviours and transitions n = _node.firstChild(); while( !n.isNull() ) { QDomElement e = n.toElement(); // try to convert the node to an element. if( !e.isNull() ) { // the node was really an element. QDomAttr attribute = e.attributeNode("name"); // retrieve behaviours if (e.tagName() == "behaviour") { if (!attribute.isNull() && !attribute.value().isEmpty()) { string name(attribute.value()); Behaviour * behaviour; BehaviourParameters * parameters; if ((behaviour = br->getBehaviour(name)) != 0) { parameters = behaviour->getParametersInstance(); KeyValueList params; params <<= n; *parameters <<= params; addBehaviour(behaviour, parameters); } else { std::string error("Behaviour not registered: " + name); throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup(error.c_str())); } } else { throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup("Behaviour without name.")); } } // retrieve transitions else if (e.tagName() == "transition") { QDomAttr attrMessage = e.attributeNode("message"); string message; if (!attrMessage.isNull() && !attrMessage.value().isEmpty()) { message = string(attrMessage.value()); } else { throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup("Transition without message.")); } QDomAttr attrPattern = e.attributeNode("target"); if (!attrPattern.isNull() && !attrPattern.value().isEmpty()) { string patternname = string(attrPattern.value()); ActionPatternMap::const_iterator iter = _apMap.find(patternname); if (iter != _apMap.end()) addTransition(message, iter->second); else { std::string error("ActionPattern for transition not registered: " + message + " --> " + patternname + "."); throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup(error.c_str())); } } else throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup("Transition without target.")); } } n = n.nextSibling(); } }
BaseMoveSlot::BaseMoveSlot( const QGraphicsScene& scene, iscore::CommandStack& stack, BaseStateMachine& sm): QState{&sm}, m_sm{sm}, m_dispatcher{stack}, m_ongoingDispatcher{stack}, m_scene{scene} { /// 2. Setup the sub-state machine. m_waitState = new QState{&m_localSM}; m_localSM.setInitialState(m_waitState); // Two states : one for moving the content of the slot, one for resizing with the handle. { auto dragSlot = new DragSlotState{m_dispatcher, m_sm, m_scene, &m_localSM}; // Enter the state make_transition<ClickOnSlotOverlay_Transition>( m_waitState, dragSlot, *dragSlot); dragSlot->addTransition(dragSlot, SIGNAL(finished()), m_waitState); } { auto resizeSlot = new ResizeSlotState{m_ongoingDispatcher, m_sm, &m_localSM}; make_transition<ClickOnSlotHandle_Transition>( m_waitState, resizeSlot, *resizeSlot); resizeSlot->addTransition(resizeSlot, SIGNAL(finished()), m_waitState); } // 3. Map the external events to internal transitions of this state machine. auto on_press = new Press_Transition; this->addTransition(on_press); connect(on_press, &QAbstractTransition::triggered, this, [&] () { auto item = m_scene.itemAt(m_sm.scenePoint, QTransform()); if(auto overlay = dynamic_cast<SlotOverlay*>(item)) { m_localSM.postEvent(new ClickOnSlotOverlay_Event{ iscore::IDocument::path(overlay->slotView().presenter.model())}); } else if(auto handle = dynamic_cast<SlotHandle*>(item)) { m_localSM.postEvent(new ClickOnSlotHandle_Event{ iscore::IDocument::path(handle->slotView().presenter.model())}); } }); // Forward events auto on_move = new Move_Transition; this->addTransition(on_move); connect(on_move, &QAbstractTransition::triggered, [&] () { m_localSM.postEvent(new Move_Event); }); auto on_release = new Release_Transition; this->addTransition(on_release); connect(on_release, &QAbstractTransition::triggered, [&] () { m_localSM.postEvent(new Release_Event); }); m_localSM.start(); }
bool FSMDescrip::loadFromXML(const std::string& xmlName, bool verbose) { logger << Logger::INFO_MSG << "Loading behavior from xml: " << xmlName; TiXmlDocument xml(xmlName); bool loadOkay = xml.LoadFile(); if (!loadOkay) { logger << Logger::ERR_MSG << "Could not load behavior configuration xml ("; logger << xmlName << ") due to xml syntax errors.\n"; logger << "\t" << xml.ErrorDesc(); return false; } TiXmlElement* popNode = xml.RootElement(); if (!popNode) { logger << Logger::ERR_MSG << "Root element does not exist."; return false; } if (popNode->ValueStr() != "BFSM") { logger << Logger::ERR_MSG << "Root element value should be \"BFSM\"."; return false; } std::string absPath; os::path::absPath(xmlName, absPath); std::string junk; os::path::split(absPath, _behaviorFldr, junk); logger << Logger::INFO_MSG << "Behavior root: " << _behaviorFldr; TiXmlElement* child; for (child = popNode->FirstChildElement(); child; child = child->NextSiblingElement()) { if (child->ValueStr() == "GoalSet") { int i; if (!child->Attribute("id", &i)) { logger << Logger::ERR_MSG << "GoalSet requires an \"id\" property."; return false; } size_t setID = static_cast<size_t>(i); // confirm that the id doesn't already exist if (_goalSets.find(setID) != _goalSets.end()) { logger << Logger::WARN_MSG << "Found multiple GoalSets with the same id: "; logger << setID << ".\n\tGoal definitions will be merged!"; } else { _goalSets[setID] = new GoalSet(); } TiXmlElement* goalNode; for (goalNode = child->FirstChildElement(); goalNode; goalNode = goalNode->NextSiblingElement()) { if (goalNode->ValueStr() == "Goal") { Goal* goal = parseGoal(goalNode, _behaviorFldr); if (goal == 0x0) { logger << Logger::ERR_MSG << "Error parsing a goal description."; return false; } // Make sure that this goal doesn't duplicate previous goal ids if (!_goalSets[setID]->addGoal(goal->getID(), goal)) { logger << Logger::ERR_MSG << "GoalSet " << setID; logger << " has two goals with the identifier: " << goal->getID(); logger << " (second appears on line " << goalNode->Row() << ")."; return false; } } else { logger << Logger::WARN_MSG << "Found a child tag of the GoalSet that " "is not a \"Goal\" tag on line " << goalNode->Row() << ". " "It will be ignored."; } } } else if (child->ValueStr() == "State") { if (!parseState(child, _behaviorFldr, _states)) { return false; } } else if (child->ValueStr() == "Transition") { std::string from; Transition* trans = parseTransition(child, _behaviorFldr, from); if (trans == 0x0) { return false; } addTransition(from, trans); } else if (child->ValueStr() == "VelModifier") { VelModifier* vel = parseVelModifier(child, _behaviorFldr); if (vel == 0x0) { return false; } else { _velModifiers.push_back(vel); } } else if (child->ValueStr() == "Task") { Task* task = parseTask(child, _behaviorFldr); if (task == 0x0) { logger << Logger::WARN_MSG << "User-specified Task on line "; logger << child->Row() << " couldn't be instantiated. " "It is being ignored."; } else { _tasks.push_back(task); } } else if (child->ValueStr() == "EventSystem") { if (!EVENT_SYSTEM->parseEvents(child, _behaviorFldr)) { return false; } } else { logger << Logger::ERR_MSG << "Unrecognized tag as child of <Population>: <"; logger << child->ValueStr() << ">."; return false; } } return true; }
/* Creer un automate a partir d'un fichier texte * Valeur de retour : Automate cree */ bool parse(FILE *data, struct fsm *fsm) { char *param, *tmp; char type[TYPE_SIZE], s[LINE_SIZE]; bool alphabet = false; struct state *st, *st2; struct transition *tr; int i = 0, j; char **trans = NULL; fsm->alphabet = NULL; fsm->initials = NULL; fsm->states = NULL; fsm->ilen = fsm->alen = fsm->slen = 0; while(EOF != fscanf(data, "%18s%255[^\n]", type, s)) { /* TYPE_SIZE et LINE_SIZE */ param = s; while((*param == ' ' || *param == '\t') && *param != '\0') { param++; } if(!(*param)) { fprintf(stderr, "parse: `%s %s': Invalid format.\n", type, s); return false; } if(!strcmp(type, "alphabet_terminal")) { alphabet = true; tmp = strtok(param, " "); while(tmp != NULL) { if(!addAlphabet(fsm, tmp)) return false; tmp = strtok(NULL, " "); } } else if(!strcmp(type, "initial")) { tmp = strtok(param, " "); while(tmp != NULL) { if(!addInitial(fsm, tmp)) return false; tmp = strtok(NULL, " "); } } else if(!strcmp(type, "terminal")) { tmp = strtok(param, " "); while(tmp != NULL) { if(!addState(fsm, tmp, true)) return false; tmp = strtok(NULL, " "); } } else { i = 0; trans = NULL; tmp = strtok(param, " "); if(((trans = realloc(trans, (i+1)*sizeof(char *))) == NULL) || ((trans[i] = malloc((strlen(tmp)+1)*sizeof(char))) == NULL)) { fprintf(stderr, "parse: Memory allocation failed.\n"); return false; } strcpy(trans[i++], tmp); if((tmp = strtok(NULL, " ")) == NULL) { fprintf(stderr, "parse: `%s %s': Invalid format; destination stateis not specified.\n", type, s); return false; } do { if(((trans = realloc(trans, (i+1)*sizeof(char *))) == NULL) || ((trans[i] = malloc((strlen(tmp)+1)*sizeof(char))) == NULL)) { fprintf(stderr, "parse: Memory allocation failed.\n"); return false; } strcpy(trans[i++], tmp); } while((tmp = strtok(NULL, " ")) != NULL); if(((st = addState(fsm, type, false)) == NULL) || ((st2 = addState(fsm, trans[i-1], false)) == NULL)) { return false; } for(j = 0; j < i-1; j++) { if(alphabet && (!containsLetter(fsm, trans[j])) && strcmp(trans[j], EPSILON)) { fprintf(stderr, "parse: `%s' does not belong to the alphabet.\n", trans[j]); for(j = 0; j < i; j++) free(trans[j]); free(trans); return false; } else if(!alphabet && strcmp(trans[j], EPSILON)) { if(!addAlphabet(fsm, trans[j])) return false; } if(((tr = createTransition(trans[j], st2)) == NULL) || (!addTransition(st, tr))) return false; } for(j = 0; j < i; j++) free(trans[j]); free(trans); } } return true; }
Transition *Automaton::addLazyTransition(State *start, State *end) { Transition * newTransition=addTransition(start,end); newTransition->type=TransitionType::LAZY; return newTransition; }
void DFA::readText(Source &r) { reset(); // TextReader r(path); StringReader tk; String lineStr; // storage for strings parsed from line; moved out // of main loop to minimize object construction/destruction String stateA; String stateB; String symbol; // keep track of what will become the start state int startSt = -1; while (!r.eof()) { r >> lineStr; // r.readLine(lineStr); tk.begin(lineStr); // is this line blank? if (tk.eof()) continue; /* parse line as <final state> <initial state> <next state> <transition symbol> */ const char *errMsg = "Problem with format of source line"; int s0 = -1; int s1 = -1; try { tk.readWord(stateA); s0 = Utils::parseInt(stateA); // if no more data on this line, it's a <final state> if (tk.eof()) { makeStateFinal(s0); } else { // read the next state & transition symbol tk.readWord(stateB); s1 = Utils::parseInt(stateB); tk.readWord(symbol); // check validity of input... if (symbol.length() != 1) throw Exception(errMsg); // add a transition symbol between these states; if a symbol // already exists, it will throw an exception (it's supposed // to be a DFA, not an NFA) // if the states don't exist, they will be created. addTransition(s0,s1,symbol.charAt(0)); } } catch (StringReaderException &e) { // REF(e); throw Exception(errMsg); } catch (NumberFormatException &e) { // REF(e); throw Exception(errMsg); } // replace startState if necessary if (startSt < 0 || s0 == 0) startSt = s0; } if (startSt >= 0) setStartState(startSt); }
MoveSlotToolState::MoveSlotToolState(const ScenarioStateMachine& sm): GenericStateBase{sm}, m_dispatcher{m_sm.commandStack()}, m_ongoingDispatcher{m_sm.commandStack()} { /// 1. Set the scenario in the correct state with regards to this tool. connect(this, &QState::entered, [&] () { for(TemporalConstraintPresenter* constraint : m_sm.presenter().constraints()) { if(!constraint->rack()) continue; constraint->rack()->setDisabledSlotState(); } }); connect(this, &QState::exited, [&] () { for(TemporalConstraintPresenter* constraint : m_sm.presenter().constraints()) { if(!constraint->rack()) continue; constraint->rack()->setEnabledSlotState(); } }); /// 2. Setup the sub-state machine. m_waitState = new QState{&m_localSM}; m_localSM.setInitialState(m_waitState); // Two states : one for moving the content of the slot, one for resizing with the handle. { auto dragSlot = new DragSlotState{m_dispatcher, m_sm, m_sm.scene(), &m_localSM}; // Enter the state make_transition<ClickOnSlotOverlay_Transition>( m_waitState, dragSlot, *dragSlot); dragSlot->addTransition(dragSlot, SIGNAL(finished()), m_waitState); } { auto resizeSlot = new ResizeSlotState{m_ongoingDispatcher, m_sm, &m_localSM}; make_transition<ClickOnSlotHandle_Transition>( m_waitState, resizeSlot, *resizeSlot); resizeSlot->addTransition(resizeSlot, SIGNAL(finished()), m_waitState); } // 3. Map the external events to internal transitions of this state machine. auto on_press = new Press_Transition; this->addTransition(on_press); connect(on_press, &QAbstractTransition::triggered, [&] () { auto item = m_sm.scene().itemAt(m_sm.scenePoint, QTransform()); if(auto overlay = dynamic_cast<SlotOverlay*>(item)) { m_localSM.postEvent(new ClickOnSlotOverlay_Event{ iscore::IDocument::path(overlay->slotView().presenter.model())}); } else if(auto handle = dynamic_cast<SlotHandle*>(item)) { m_localSM.postEvent(new ClickOnSlotHandle_Event{ iscore::IDocument::path(handle->slotView().presenter.model())}); } }); // Forward events auto on_move = new Move_Transition; this->addTransition(on_move); connect(on_move, &QAbstractTransition::triggered, [&] () { m_localSM.postEvent(new Move_Event); }); auto on_release = new Release_Transition; this->addTransition(on_release); connect(on_release, &QAbstractTransition::triggered, [&] () { m_localSM.postEvent(new Release_Event); }); }
Transition *Automaton::addLoop(State *start, State *end) { Transition * newTransition=addTransition(start,end); newTransition->type=TransitionType::EMPTY; return newTransition; }
bool Camera::update(sf::Time dt) { if(!transitioning()) { if(focus_) { sf::FloatRect camBounds = bounds(), focusBounds = focus_->bounds(); if(focusBounds.left < camBounds.left) { addTransition(Left); } else if(focusBounds.left + focusBounds.width > camBounds.left + camBounds.width) { addTransition(Right); } if(focusBounds.top < camBounds.top) { addTransition(Up); } else if(focusBounds.top + focusBounds.height > camBounds.top + camBounds.height) { addTransition(Down); } } if(!transitioning()) { if(focus_) focus_->setTransitioning(false); return false; } } if(focus_) focus_->setTransitioning(true); float delta = 0,target = 0; Direction transition = transitions_.front(); sf::Vector2f size = view_.getSize(); if(transition == Left || transition == Right) { target = size.x; } else { target = size.y; } delta = target/transitionTime_*dt.asSeconds(); if(distanceMoved_+delta > target) { delta = target-distanceMoved_; distanceMoved_ = 0; transitions_.pop(); } else { distanceMoved_ += delta; } switch(transition) { case Left: view_.move(-delta,0); break; case Right: view_.move(delta,0); break; case Up: view_.move(0,-delta); break; case Down: view_.move(0,delta); break; default: break; } sf::FloatRect camBounds = bounds(); sf::FloatRect focusBounds = focus_->bounds(); if(transition == Right && focusBounds.left < camBounds.left) focus_->move(camBounds.left-focusBounds.left,0); else if(transition == Left && focusBounds.left + focusBounds.width > camBounds.left + camBounds.width) focus_->move(camBounds.left+camBounds.width- (focusBounds.left+focusBounds.width),0); else if(transition == Down && focusBounds.top < camBounds.top) focus_->move(0,camBounds.top-focusBounds.top); else if(transition == Up && focusBounds.top + focusBounds.height > camBounds.top + camBounds.height) focus_->move(0,camBounds.top+camBounds.height- (focusBounds.top+focusBounds.height)); return true; }
Transition *Automaton::addEndString(State *start, State *end) { Transition * newTransition=addTransition(start,end); newTransition->type=TransitionType::ENDSTRING; return newTransition; }
int Trajectory::step(double maxTime, const void* pars, rng::RngStream* rng, bool adjZero) { // get array of next event rates double nextTime = 0.0; double transTime = 0.0; double r = 0.0; int nextEvent = 0; int num_events = 0; double dw = 0.0; double rate = 0.0; double unrate = 0.0; int ret = 0; const TransitionType* nextTrans; // set time to EpiState curState.time = time; // calculate all rates double totalRate = model->calculateTransRates(curState,transRates,trueRates); double totalTrue = std::accumulate(trueRates.begin(),trueRates.end(),0.0); while (ret <= 0) { if (totalRate <= 0.0) { time = maxTime; ret = 4; break; } // sample next event time rng->uniform(1,&r); nextTime = -1.0/totalRate * log(r); if (time+nextTime < maxTime) { // sample next event type and calculate rate of the event nextEvent = model->chooseTransition(rng,transRates); // get rate of chosen event (transRates is a cumulative array) rate = transRates[nextEvent] - ((nextEvent>0) ? transRates[nextEvent-1] : 0.0); // get the appropriate transition nextTrans = model->getTType(nextEvent); // - time interval transTime = time+nextTime - lastEventTime(); // generate the transition StateTransition st(transTime,*nextTrans,curState,pars,nextEvent,time+nextTime); // get potential new state (without copying branch information) EpiState newState; newState.copyNoBranches(curState); newState += st.trans; // get probability of new state newState.nextTime = nextTime; dw = nextTrans->applyProb(newState,model->getPars()); if (dw > 0.0 || ! adjZero) // check if the proposed state is feasible (prob > 0) { // if yes, // add branch transformations if (model->do_branches) { curState.nextTime = nextTime; nextTrans->applyBranch(curState,rng,st,pars); dw *= exp(st.relprob); } // add transition to list if (store_trans) transitions.push_back(st); // adapt state addTransition(st); // multiply probability updateProb(dw); // updateLogProb(st.relprob); // advance time time += nextTime; ++num_events; #ifdef DEBUG if (ret < 0) { cout << ascii::cyan << " legal event" << " (" << nextEvent << ")." << " w = " << dw << ", penalty = " << unrate << ", total rate = " << totalRate << "." << ascii::end << endl; } #endif ret = 1; // exit loop } else { // if no, // make this transition illegal in this particular step #ifdef DEBUG cout << ascii::cyan << " illegal event (" << nextEvent << ")." << " w = " << dw << ", penalty = " << rate << ", total rate = " << totalRate << "." << ascii::end << endl; #endif // adjust cumulative rates for (size_t i = nextEvent; i < transRates.size(); ++i) { transRates[i] -= rate; } totalRate = transRates.back(); // condition on not seeing this event unrate += rate; // redo loop with modified rates ret = -1; } } else { #ifdef DEBUG if (ret < 0) { cout << "No event. Total rate = " << totalRate << "." << endl; } #endif nextTime = maxTime - time; time = maxTime; ret = 2; // exit loop } } if (totalRate < 0.0) { #ifdef DEBUG cout << "\033[1;31m"; cout << "Negative rate (" << ret << "): " << totalRate << " ES = " << curState; cout << "\033[0m" << endl; #endif return -1; } // condition on the illegal events ('prob' is in logarithmic scale) // 'unrate' is the sum of all the rates that were conditioned on not // happening // if (unrate > 0.0) { // updateLogProb(-unrate*nextTime); double dR = totalTrue - totalRate; #ifdef DEBUG if (dR != 0) { cout << " difference in rates: " << totalTrue << " - " << totalRate << endl; } #endif updateLogProb(-dR*nextTime); } return ret; // return num_events; // return (ret != 2) ? num_events : -2; }
Transition *Automaton::addBeginLine(State *start, State *end) { Transition * newTransition=addTransition(start,end); newTransition->type=TransitionType::BEGINLINE; return newTransition; }
/*! Adds the given \a transition. The transition has this state as the source, and the given \a target as the target state. \sa removeTransition() */ void QtState::addTransition(QtAbstractTransition *transition, QtAbstractState *target) { addTransition(transition, QList<QtAbstractState*>() << target); }
RBOOL obsLib_addPattern ( HObs hObs, RPU8 pBytePattern, RU32 nBytePatternSize, RPVOID context ) { RBOOL isSuccess = FALSE; RU32 i = 0; PObsNode tmp = NULL; PObsNode next = NULL; PObsNode prev = NULL; PObsSig sig = NULL; _PHObs obs = (_PHObs)hObs; if( rpal_memory_isValid( hObs ) && NULL != pBytePattern && 0 != nBytePatternSize && NULL != obs->root ) { tmp = obs->root; prev = NULL; isSuccess = TRUE; for( i = 0; i < nBytePatternSize; i++ ) { if( NULL == ( next = getNextNode( tmp, pBytePattern[ i ] ) ) ) { // We need to forge a new state and add a FSM transition to it if( NULL == ( next = newNode() ) || NULL == ( tmp = addTransition( prev, tmp, next, pBytePattern[ i ] ) ) ) { isSuccess = FALSE; break; } // If this is the first node, we may need to update // the handle with the new root node pointer since // it could have gotten realloced. if( NULL == prev ) { obs->root = tmp; obs->currentState = obs->root; } } // Follow on to the next state prev = tmp; tmp = next; } if( isSuccess ) { // All went well, in the last state, record the hit if( NULL != ( sig = newSig( pBytePattern, nBytePatternSize, context ) ) ) { if( !addHitToNode( tmp, sig ) ) { freeSig( sig ); isSuccess = FALSE; } else { obs->nPatterns++; } } else { isSuccess = FALSE; } } } return isSuccess; }