bool State8::transition(Automaton &automaton, Symbol *symbol) { switch (symbol->getId()) { /* * id : E14 */ case S_VARIABLE: automaton.addVariableToCurrentDeclarationVar((SymbolVariable *) symbol); automaton.transition(symbol, new State14()); return true; /* * V : E13 */ case SYMBOL_UNTERMINAL_V: automaton.transition(symbol, new State13()); return true; default: throw ErrorLexicalUnexpectedSymbol(symbol->toString(), symbol->getNumLineDetection(), symbol->getNumCharDetection()); } }
int main(int argc, char** argv) { Automaton automaton; if(argc == 2) { InputFromFile ifile(argv[1]); automaton.setInput(ifile.readFile()); automaton.run(); } }
vector<Value*> AssertionSiteInstrumenter::CollectArgs( Instruction *Before, const Automaton& A, Module& Mod, IRBuilder<>& Builder) { // Find named values to be passed to instrumentation. std::map<string,Value*> ValuesInScope; for (auto G = Mod.global_begin(); G != Mod.global_end(); G++) ValuesInScope[G->getName()] = G; auto *Fn = Before->getParent()->getParent(); for (auto& Arg : Fn->getArgumentList()) ValuesInScope[Arg.getName()] = &Arg; auto& EntryBlock(*Fn->begin()); for (auto& I : EntryBlock) { auto *Inst = dyn_cast<AllocaInst>(&I); if (!Inst) break; ValuesInScope[Inst->getName()] = Builder.CreateLoad(Inst); } int ArgSize = 0; for (auto& Arg : A.getAssertion().argument()) if (!Arg.free()) ArgSize = std::max(ArgSize + 1, Arg.index()); vector<Value*> Args(ArgSize, NULL); for (auto& Arg : A.getAssertion().argument()) { if (Arg.free()) continue; string Name(BaseName(Arg)); if (ValuesInScope.find(Name) == ValuesInScope.end()) { string s; raw_string_ostream Out(s); for (auto v : ValuesInScope) { Out << " \"" << v.first << "\": "; v.second->getType()->print(Out); Out << "\n"; } panic("assertion references non-existent variable '" + BaseName(Arg) + "'; was it defined under '#ifdef TESLA'?\n\n" "Variables in scope are:\n" + Out.str()); } Args[Arg.index()] = GetArgumentValue(ValuesInScope[Name], Arg, Builder, true); } return Args; }
void ContactLocalProductPlugin::extraInit(Simulator *simulator){ update(xmlData,true); Automaton * cellTypePluginAutomaton = potts->getAutomaton(); if (cellTypePluginAutomaton){ ASSERT_OR_THROW("The size of matrix of contact specificity coefficients has must equal max_cell_type_id+1. You must list specificity coefficients between all cel types", contactSpecificityArray.size() == ((unsigned int)cellTypePluginAutomaton->getMaxTypeId()+1) ); } }
Automaton* Converter::convert() { Automaton* result = new Automaton(); populateStates(); populateTransitions(); for (int i = 0; i < this->totalStates; i++) { result->addState(*this->newStates[i]); } result->setStartState(this->newStates[1]); return result; }
bool State37::transition(Automaton &automaton, Symbol *symbol) { switch (symbol->getId()) { /* * R9 : C -> id = val * ; | R9 * , | R9 */ case SYMBOL_UNIT_SEMICOLON: case SYMBOL_UNIT_COMMA: automaton.reduction(3, new SymbolUnterminal(SYMBOL_UNTERMINAL_C)); return true; case S_VARIABLE: throw ErrorLexicalMissingSymbol(symbol->getNumLineDetection(), symbol->getNumCharDetection(), new SymbolUnit(SYMBOL_UNIT_COMMA)); case S_INSTRUCTION_READ: case S_INSTRUCTION_WRITE: case S_DECLARATION_CONST: case S_DECLARATION_VAR: case SYMBOL_UNIT_DOLLAR: throw ErrorLexicalMissingSymbol(symbol->getNumLineDetection(), symbol->getNumCharDetection(), new SymbolUnit(SYMBOL_UNIT_SEMICOLON)); default: throw ErrorLexicalUnexpectedSymbol(symbol->toString(), symbol->getNumLineDetection(), symbol->getNumCharDetection()); } }
int main() { string S; getline(cin, S); int poz = 0; Automaton T = solve(S, poz, 0); Automaton V = T.removeEmptyTransitions().makeDeterminist().minimize(); cout << T << "\n"; cout << T.removeEmptyTransitions().makeDeterminist() << "\n"; cout << V << "\n"; while (cin >> S) if (V.check(S)) cout << "Bun\n"; else cout << "Rau\n"; }
bool State27::transition(Automaton &automaton, Symbol *symbol) { switch (symbol->getId()) { /* * val : E37 */ case S_NUMBER: automaton.addConstantValueToCurrentDeclarationConst((SymbolNumber *) symbol); automaton.transition(symbol, new State37()); return true; default: throw ErrorLexicalUnexpectedSymbol(symbol->toString(), symbol->getNumLineDetection(), symbol->getNumCharDetection()); } }
void EventTranslator::CallUpdateState(const Automaton& A, uint32_t Symbol) { std::vector<Value*> Args; Args.push_back(InstrCtx.TeslaContext(A.getAssertion().context())); Args.push_back(InstrCtx.ExternalDescription(A)); Args.push_back(ConstantInt::get(InstrCtx.Int32Ty, Symbol)); Args.push_back(Key); Builder.CreateCall(InstrCtx.UpdateStateFn(), Args); }
Automaton solve(string &S, int &position, int level) { if (level == 0) { Automaton aux = solve(S, position, 1); while (position < int(S.size()) and S[position] == '+') { Automaton next = solve(S, ++position, 1); aux += next; } return aux; } if (level == 1) { Automaton aux = solve(S, position, 2); while (position < int(S.size()) and S[position] == '|') { Automaton next = solve(S, ++position, 2); aux |= next; } return aux; } if (level == 2) { Automaton aux = solve(S, position, 3); while (position < int(S.size()) and S[position] == '*') { aux.star(); ++position; } return aux; } if (S[position] == '(') { Automaton aux = solve(S, ++position, 0); ++position; return aux; } Automaton aux(2, dictionary); aux.setFinal(1); aux.setStart(0); aux.addTransition(0, 1, S[position]); ++position; return aux; }
void Grid::DrawWithMap(Automaton &a) { for (int i=0; i<cellCount; i++) for(int j=0; j<cellCount; j++) { statecode cell_state = a(i,j); statecode ill_state = a.getIllState(); double lcolor[3]; double density = (double) cell_state / ill_state; std::fill(lcolor, lcolor+3, density); FillCell(i, j, lcolor); } }
void State::print(const Automaton& automaton) const { std::cout << "Nom(" << name << ") "; if (isInitial()) { std::cout << "[initial] "; } if (isFinal()) { std::cout << "[final] "; } std::cout << std::endl; std::cout << "\t== Transitions" << std::endl; TransitionSet::const_iterator it; for (it = outTransitions.begin(); it != outTransitions.end(); ++it) { std::cout << "\t\tavec(" << it->condition << ") => " << automaton.findStateName(it->target) << std::endl; } }
int main (int argc, char *argv[]) { QCoreApplication app (argc, argv); bool generate_dot = false; bool generate_report = false; bool no_lines = false; bool debug_info = true; bool troll_copyright = false; QString file_name = 0; QStringList args = app.arguments (); args.removeFirst (); foreach (QString arg, args) { if (arg == QLatin1String ("-h") || arg == QLatin1String ("--help")) help_me (); else if (arg == QLatin1String ("-v") || arg == QLatin1String ("--verbose")) generate_report = true; else if (arg == QLatin1String ("--dot")) generate_dot = true; else if (arg == QLatin1String ("--no-lines")) no_lines = true; else if (arg == QLatin1String ("--no-debug")) debug_info = false; else if (arg == QLatin1String ("--troll")) troll_copyright = true; else if (file_name.isEmpty ()) file_name = arg; else qerr << "*** Warning. Ignore argument `" << arg << "'" << endl; } if (file_name.isEmpty ()) { help_me (); exit (EXIT_SUCCESS); } Grammar grammar; Recognizer p (&grammar, no_lines); if (! p.parse (file_name)) exit (EXIT_FAILURE); if (grammar.rules.isEmpty ()) { qerr << "*** Fatal. No rules!" << endl; exit (EXIT_FAILURE); } else if (grammar.start == grammar.names.end ()) { qerr << "*** Fatal. No start symbol!" << endl; exit (EXIT_FAILURE); } grammar.buildExtendedGrammar (); grammar.buildRuleMap (); Automaton aut (&grammar); aut.build (); CppGenerator gen (p, grammar, aut, generate_report); gen.setDebugInfo (debug_info); gen.setTrollCopyright (troll_copyright); gen (); if (generate_dot) { DotGraph genDotFile (qout); genDotFile (&aut); } else if (generate_report) { ParseTable genParseTable (qout); genParseTable(&aut); } return EXIT_SUCCESS; }
Automaton * Automaton::getDeterministic() { Automaton * b = new Automaton; std::vector< std::vector< int > > mEmptyTransitions; std::vector< int > vEmptyIn; std::vector< int > vEmptyOut; int i, j, removed; b->vStates = vStates; b->vFinal = vFinal; b->vSymbols = vSymbols; b->mTransitions = mTransitions; //creates the mEmptyTransitions table vEmptyIn.resize(getNStates()); vEmptyOut.resize(getNStates()); mEmptyTransitions.resize(getNStates()); for(i = 0; i < getNStates(); i++) mEmptyTransitions[i].resize(getNStates()); //initialize mEmptyTransitions for(i = 0; i < mEmptyTransitions.size(); i++){ vEmptyIn[i] = 0; vEmptyOut[i] = 0; for(j = 0; j < mEmptyTransitions[i].size(); j++) mEmptyTransitions[i][j] = 0; } //fills mEmptyTransitons j = findSymbolId(""); if(j != -1) { for(int i = 0; i < getNStates(); i++) { for(std::list<int>::iterator it = mTransitions[i][j].begin(); it != mTransitions[i][j].end(); it++) { vEmptyIn[*it]++; vEmptyOut[i]++; mEmptyTransitions[i][*it]++; } } } //finds a state 'i' with incoming empty transitions, but no outgoing empty transitions, //copy its transtions to states 'j' able to reach 'i' and removes these empty transitions do { removed = 0; for(i = 0; i < getNStates(); i++) { if((vEmptyIn[i] > 0) && (vEmptyOut[i] == 0)) { for(j = 0; j < getNStates(); j++) { if(i == j) continue; if(mEmptyTransitions[j][i] > 0) { b->copyOutgoingTransitions(i, j); b->removeIncomingEmptyTransitions(i); if(b->vFinal[i] == true) b->vFinal[j] = true; mEmptyTransitions[j][i]--; vEmptyIn[i]--; vEmptyOut[j]--; removed++; } } } } } while(removed > 0); //finds a state 'i' that has a non-determinism (two or more outputs for the same symbol), //creates a state representing all those symbols and change the transition to this one do { removed = 0; for(i = 0; i < b->getNStates(); i++) { for(j = 0; j < b->getNSymbols(); j++) { if(b->mTransitions[i][j].size() > 1) { int newStateId; std::string newStateName; bool isFinal; //fills newStateName and isFinal newStateName = b->vStates[mTransitions[i][j].front()]; std::list<int>::iterator it = b->mTransitions[i][j].begin(); isFinal = vFinal[*it]; ++it; for(; it != b->mTransitions[i][j].end(); it++) { newStateName += "_" + b->vStates[*it]; isFinal = isFinal || vFinal[*it]; } //guarantees the newStateName is unique while(b->findStateId(newStateName) != -1) newStateName += '_'; //adds newStateName to b b->addState(newStateName, isFinal); newStateId = b->findStateId(newStateName); //copy the old state's outgoing transtions to the new state for(std::list<int>::iterator it = b->mTransitions[i][j].begin(); it != b->mTransitions[i][j].end(); it++) b->copyOutgoingTransitions(*it, newStateId); //removes the transitions going to the old states and adds a transtion going to the new one b->mTransitions[i][j].clear(); b->mTransitions[i][j].push_back(newStateId); removed++; } } } } while(removed > 0); return b; }
void ConnectivityGlobalPlugin::update(CC3DXMLElement *_xmlData, bool _fullInitFlag) { if (potts->getDisplayUnitsFlag()) { Unit energyUnit = potts->getEnergyUnit(); CC3DXMLElement * unitsElem = _xmlData->getFirstElement("Units"); if (!unitsElem) { //add Units element unitsElem = _xmlData->attachElement("Units"); } if (unitsElem->getFirstElement("PenaltyUnit")) { unitsElem->getFirstElement("PenaltyUnit")->updateElementValue(energyUnit.toString()); } else { CC3DXMLElement * energyElem = unitsElem->attachElement("PenaltyUnit", energyUnit.toString()); } } penaltyVec.clear(); Automaton *automaton = potts->getAutomaton(); ASSERT_OR_THROW("CELL TYPE PLUGIN WAS NOT PROPERLY INITIALIZED YET. MAKE SURE THIS IS THE FIRST PLUGIN THAT YOU SET", automaton) set<unsigned char> cellTypesSet; map<unsigned char, double> typeIdConnectivityPenaltyMap; if (_xmlData->getFirstElement("DoNotPrecheckConnectivity")) { doNotPrecheckConnectivity = true; } if (_xmlData->getFirstElement("FastAlgorithm")) { fast_algorithm = true; changeEnergyFcnPtr = &ConnectivityGlobalPlugin::changeEnergyFast; } CC3DXMLElementList penaltyVecXML = _xmlData->getElements("Penalty"); CC3DXMLElementList connectivityOnVecXML = _xmlData->getElements("ConnectivityOn"); ASSERT_OR_THROW("You cannot use Penalty and ConnectivityOn tags together. Stick to one convention", !(connectivityOnVecXML.size() && penaltyVecXML.size())); // previous ASSERT_OR_THROW will encure that only one of the subsequent for loops be executed for (int i = 0; i < penaltyVecXML.size(); ++i) { typeIdConnectivityPenaltyMap.insert(make_pair(automaton->getTypeId(penaltyVecXML[i]->getAttribute("Type")), penaltyVecXML[i]->getDouble())); //inserting all the types to the set (duplicate are automatically eleminated) to figure out max value of type Id cellTypesSet.insert(automaton->getTypeId(penaltyVecXML[i]->getAttribute("Type"))); } for (int i = 0; i < connectivityOnVecXML.size(); ++i) { typeIdConnectivityPenaltyMap.insert(make_pair(automaton->getTypeId(connectivityOnVecXML[i]->getAttribute("Type")), 1.0)); //inserting all the types to the set (duplicate are automatically eleminated) to figure out max value of type Id cellTypesSet.insert(automaton->getTypeId(connectivityOnVecXML[i]->getAttribute("Type"))); } //Now that we know all the types used in the simulation we will find size of the penaltyVec vector<unsigned char> cellTypesVector(cellTypesSet.begin(), cellTypesSet.end());//coping set to the vector int size = 0; if (cellTypesVector.size()) { size = *max_element(cellTypesVector.begin(), cellTypesVector.end()); } maxTypeId = size; size += 1;//if max element is e.g. 5 then size has to be 6 for an array to be properly allocated int index; penaltyVec.assign(size, 0.0); //inserting connectivity penalty values to penaltyVec; for (map<unsigned char, double>::iterator mitr = typeIdConnectivityPenaltyMap.begin(); mitr != typeIdConnectivityPenaltyMap.end(); ++mitr) { penaltyVec[mitr->first] = fabs(mitr->second); } cerr << "size=" << size << endl; for (int i = 0; i < size; ++i) { cerr << "penaltyVec[" << i << "]=" << penaltyVec[i] << endl; } //Here I initialize max neighbor index for direct acces to the list of neighbors boundaryStrategy = BoundaryStrategy::getInstance(); maxNeighborIndex = 0; maxNeighborIndex = boundaryStrategy->getMaxNeighborIndexFromNeighborOrder(1); cerr << "ConnectivityGlobal maxNeighborIndex=" << maxNeighborIndex << endl; WatchableField3D<CellG *> *cellFieldG = (WatchableField3D<CellG *> *)potts->getCellFieldG(); Dim3D fieldDim = cellFieldG->getDim(); // max_neighbor_index_local_search is different depending whether we are on hex or cartesian lattice and if this is 2D or 3D simulation if (boundaryStrategy->getLatticeType() == HEXAGONAL_LATTICE) { // on hex lattice in 2D and 3D nearest neighbors "completely cover" a given pixel max_neighbor_index_local_search = boundaryStrategy->getMaxNeighborIndexFromNeighborOrder(1); } else { if (fieldDim.x == 1 || fieldDim.y == 1 || fieldDim.z == 1) { //2D simulation max_neighbor_index_local_search = boundaryStrategy->getMaxNeighborIndexFromNeighborOrder(2); } else { //3D max_neighbor_index_local_search = boundaryStrategy->getMaxNeighborIndexFromNeighborOrder(3); } } }
void ConnectivityGlobalPlugin::update(CC3DXMLElement *_xmlData, bool _fullInitFlag){ if(potts->getDisplayUnitsFlag()){ Unit energyUnit=potts->getEnergyUnit(); CC3DXMLElement * unitsElem=_xmlData->getFirstElement("Units"); if (!unitsElem){ //add Units element unitsElem=_xmlData->attachElement("Units"); } if(unitsElem->getFirstElement("PenaltyUnit")){ unitsElem->getFirstElement("PenaltyUnit")->updateElementValue(energyUnit.toString()); }else{ CC3DXMLElement * energyElem = unitsElem->attachElement("PenaltyUnit",energyUnit.toString()); } } penaltyVec.clear(); Automaton *automaton = potts->getAutomaton(); ASSERT_OR_THROW("CELL TYPE PLUGIN WAS NOT PROPERLY INITIALIZED YET. MAKE SURE THIS IS THE FIRST PLUGIN THAT YOU SET", automaton) set<unsigned char> cellTypesSet; map<unsigned char,double> typeIdConnectivityPenaltyMap; if(_xmlData->getFirstElement("DoNotPrecheckConnectivity")){ doNotPrecheckConnectivity=true; } CC3DXMLElementList penaltyVecXML=_xmlData->getElements("Penalty"); for (int i = 0 ; i<penaltyVecXML.size(); ++i){ typeIdConnectivityPenaltyMap.insert(make_pair(automaton->getTypeId(penaltyVecXML[i]->getAttribute("Type")),penaltyVecXML[i]->getDouble())); //inserting all the types to the set (duplicate are automatically eleminated) to figure out max value of type Id cellTypesSet.insert(automaton->getTypeId(penaltyVecXML[i]->getAttribute("Type"))); } //Now that we know all the types used in the simulation we will find size of the penaltyVec vector<unsigned char> cellTypesVector(cellTypesSet.begin(),cellTypesSet.end());//coping set to the vector int size=0; if (cellTypesVector.size()){ size= * max_element(cellTypesVector.begin(),cellTypesVector.end()); } maxTypeId=size; size+=1;//if max element is e.g. 5 then size has to be 6 for an array to be properly allocated int index ; penaltyVec.assign(size,0.0); //inserting connectivity penalty values to penaltyVec; for(map<unsigned char , double>::iterator mitr=typeIdConnectivityPenaltyMap.begin() ; mitr!=typeIdConnectivityPenaltyMap.end(); ++mitr){ penaltyVec[mitr->first]=fabs(mitr->second); } cerr<<"size="<<size<<endl; for(int i = 0 ; i < size ; ++i){ cerr<<"penaltyVec["<<i<<"]="<<penaltyVec[i]<<endl; } //Here I initialize max neighbor index for direct acces to the list of neighbors boundaryStrategy=BoundaryStrategy::getInstance(); maxNeighborIndex=0; maxNeighborIndex=boundaryStrategy->getMaxNeighborIndexFromNeighborOrder(1); cerr<<"ConnectivityGlobal maxNeighborIndex="<<maxNeighborIndex<<endl; }
/** * Computes the final states from automaton * * @param aut: Automaton for matrix * @return: final states of automaton corresponding to final formula */ BaseFinalStatesType getBaseFinalStates(Automaton & aut) { return aut.GetFinalStates(); }
/** * Implementation of workset-based algorithm for deciding whether the given * macro-state is final or not. Macro-state is final if all its substates are * non-final * * @param aut: automaton // FOR NOW! may be replaced by cache * @param state: macro state we are checking * @param level: level of projection * @return True if the macro-state is final */ bool StateIsFinal(Automaton & aut, TStateSet* state, unsigned level, PrefixListType & prefix) { // return whether the state is final in automaton if (level == 0) { LeafStateSet* leaf = reinterpret_cast<LeafStateSet*>(state); StateType q = leaf->state; return aut.IsStateFinal(q); // level > 0 } else { StateSetList worklist; StateSetList processed; MacroStateSet* macroState = reinterpret_cast<MacroStateSet*>(state); // Look into Cache bool isFinal; #ifdef USE_STATECACHE if(StateCache.retrieveFromCache(macroState, isFinal, level)) { return isFinal; } #endif // enqueue initial states StateSetList states = macroState->getMacroStates(); for (auto state : states) { worklist.push_back(state); } while (worklist.size() != 0) { TStateSet* q = worklist.back(); worklist.pop_back(); processed.push_back(q); if (StateIsFinal(aut, q, level - 1, prefix)) { #ifdef USE_STATECACHE StateCache.storeIn(macroState, false, level); #endif return false; } else { // Enqueue all its successors MacroStateSet* zeroSuccessor = GetZeroPost(aut, q, level-1, prefix); if ((level - 1) == 0) { StateSetList s = zeroSuccessor->getMacroStates(); for(auto it = s.begin(); it != s.end(); ++it) { if(isNotEnqueued(processed, *it, level-1)) { StateType leafState = reinterpret_cast<LeafStateSet*>(*it)->state; worklist.push_back(*it); } } } else { if (isNotEnqueued(processed, zeroSuccessor, level-1)) { worklist.push_back(zeroSuccessor); } } } } #ifdef USE_STATECACHE StateCache.storeIn(macroState, true, level); #endif return true; } }
/** * Performs a decision procedure of automaton corresponding to the formula phi * This takes several steps, as first we compute the final states of the * corresponding subset construction automaton and then try to find some * example and counterexample for the automaton/formula * * It holds, that formula is unsatisfiable if there does not exist such * example, valid if there does not exists a unsatisfiable counterexample * and else it is satisfiable. * * @param formulaPrefixSet: set of second-order variables corresponding to * the prefix of the closed formula phi * @param negFormulaPrefixSet: set of second-order variables corresponding to * the prefix of the closed negation of formula phi * @return: Decision procedure results */ int decideWS1S(Automaton & aut, PrefixListType formulaPrefixSet, PrefixListType negFormulaPrefixSet) { // Number of determinizations unsigned formulaDeterminizations = formulaPrefixSet.size(); unsigned negFormulaDeterminizations = negFormulaPrefixSet.size(); unsigned cacheSize = (formulaDeterminizations >= negFormulaDeterminizations) ? formulaDeterminizations : negFormulaDeterminizations; #if (USE_STATECACHE == true) StateCache.extend(cacheSize); #endif #if (USE_BDDCACHE == true) BDDCache.extend(cacheSize); #endif if(options.dump) { std::cout << "[*] Commencing decision procedure for WS1S\n"; } // Construct initial state of final automaton MacroStateSet* initialState = constructInitialState(aut, formulaDeterminizations); MacroStateSet* negInitialState = constructInitialState(aut, negFormulaDeterminizations); // Compute the final states StateHT allStates; aut.RemoveUnreachableStates(&allStates); // checks if there exists a satisfying example in formula bool hasExample = existsSatisfyingExample(aut, initialState, formulaPrefixSet); if(options.dump) { if(hasExample) { std::cout << "[!] Found Satisfying example in formula\n"; } else { std::cout << "[-] Satisfying example not found in formula\n"; delete initialState; delete negInitialState; return UNSATISFIABLE; } } // checks if there exists a unsatisfying example in formula bool hasCounterExample = existsUnsatisfyingExample(aut, negInitialState, negFormulaPrefixSet); if(options.dump) { if(hasCounterExample) { std::cout << "[!] Found Unsatisfying example in formula\n"; } else { std::cout << "[-] Unsatisfying example not found in formula\n"; } } int answer; // No satisfiable solution was found if(!hasExample) { answer = UNSATISFIABLE; // There exists a satisfiable solution and does not exist an unsatisfiable solution } else if (!hasCounterExample) { answer = VALID; // else there only exists a satisfiable solution } else if (hasExample) { answer = SATISFIABLE; // THIS SHOULD NOT HAPPEN } else { answer = -1; } delete initialState; delete negInitialState; return answer; }