public static DeterministicAutomata NfaToDfaConverter(Automata nfa) { var transitions = new List <Tuple <List <string>, char, List <string> > >(); var lambdaStates = new List <List <string> >(); foreach (var state in nfa.States) { var achieved = LambdaDepth(state, nfa.Transitions); lambdaStates.Add(achieved); } var stateBegin = lambdaStates.Where(x => x.Intersect(nfa.InitialNode).Any()).FirstOrDefault(); ReadState(string.Join("", stateBegin.ToArray()), nfa.Alphabet, nfa.Transitions); var dfa = new DeterministicAutomata(); dfa.Alphabet = nfa.Alphabet; dfa.FinalNodes = Transitions.Where(x => x.Item1.Any(y => nfa.FinalNodes.Contains(y.ToString()))).Select(x => x.Item1).Distinct().Union(FinalLambdaStates).ToList(); dfa.InitialNode = string.Join("", stateBegin.ToArray()); dfa.States = Transitions.Where(x => !string.IsNullOrWhiteSpace(x.Item3)).Select(x => { return(x.Item1); }).Union(Transitions.Where(x => !string.IsNullOrWhiteSpace(x.Item3)).Select(x => { return(x.Item3); })).Distinct().ToList(); dfa.Transitions = Transitions; return(dfa); }
public void Evaluate() { //execute user/gui-forced time if (FForceCurrentTime) { FStartTime = FHostTime; } if (FIsRunning) { double deltaTime = (FHostTime - FOldTime) * FSpeed; FCurrentTimes[0] += deltaTime; } FOldTime = FHostTime; if (Automata != null) { if (FForceCurrentTime) { Automata.ForceStateFromCurrentTime(FCurrentTimes[0]); } EvaluateAutomata(); } FForceCurrentTime = false; }
public static Automata <string> ExampleSlide8Lesson2() { char[] alphabet = { 'a', 'b' }; Automata <string> m = new Automata <string>(alphabet); m.AddTransition(new Transition <string>("q0", 'a', "q1")); m.AddTransition(new Transition <string>("q0", 'b', "q4")); m.AddTransition(new Transition <string>("q1", 'a', "q4")); m.AddTransition(new Transition <string>("q1", 'b', "q2")); m.AddTransition(new Transition <string>("q2", 'a', "q3")); m.AddTransition(new Transition <string>("q2", 'b', "q4")); m.AddTransition(new Transition <string>("q3", 'a', "q1")); m.AddTransition(new Transition <string>("q3", 'b', "q2")); // the error state, loops for a and b: m.AddTransition(new Transition <string>("q4", 'a')); m.AddTransition(new Transition <string>("q4", 'b')); // only on start state in a dfa: m.DefineAsStartState("q0"); // two final states: m.DefineAsFinalState("q2"); m.DefineAsFinalState("q3"); return(m); }
private void ImportFileDialog_FileOk(object sender, CancelEventArgs e) { try { switch (CurrentTypeImport) { case ImportType.automata_txt: Automata = AutomataService.GetFromFile(ImportFileDialog.FileName); break; case ImportType.words_in: Words = WordService.GetFromFile(ImportFileDialog.FileName); outFileName = GetOutFileName(ImportFileDialog.FileName); break; default: throw new NotSupportedException("ImportAction não deifnida."); } MessageBox.Show(string.Format("Arquivo importado com sucesso!")); } catch (Exception error) { MessageBox.Show(error.Message); } RefreshViewState(); }
public void TestAutomataAFD() { Automata <int, char> testAutomata = GenerateTestAutomataAFN(); List <char> transictionList = new List <char>(new char[] { 'a', 'b', 'e' }); testAutomata = Automata <int, char> .AFNtoAFD(testAutomata, transictionList, 'e'); State <int, char> state0 = testAutomata.InitialState; Assert.AreEqual(0, state0.StateValue, "Valor do estado 0 diferente de 0, valor = " + state0.StateValue); State <int, char> stateAux = state0.Transictions[0].NextState; Assert.AreEqual(2, stateAux.StateValue, "Valor do estado 2 diferente de 2, valor = " + stateAux.StateValue); Assert.AreEqual(2, stateAux.Transictions.Count, "Valor do estado 2 diferente de 2, valor = " + stateAux.StateValue); stateAux = stateAux.Transictions[0].NextState; Assert.AreEqual(3, stateAux.StateValue, "Valor do estado 3 diferente de 3, valor = " + stateAux.StateValue); Assert.AreEqual(1, stateAux.Transictions.Count, "Valor do estado 1 diferente de 1, valor = " + stateAux.StateValue); stateAux = stateAux.Transictions[0].NextState; Assert.AreEqual(4, stateAux.StateValue, "Valor do estado 4 diferente de 4, valor = " + stateAux.StateValue); Assert.IsTrue(stateAux.IsFinal, "Estado 4 não é final!"); GrammarDeterministicAutomata automata = new GrammarDeterministicAutomata(); Assert.IsNotNull(automata, "Automato determinístico retornou nulo"); //TODO mais testes }
public static Automata <string> DfaTEST3() { char[] alphabet = { 'a', 'b' }; Automata <string> m = new Automata <string>(alphabet); m.AddTransition(new Transition <string>("A", 'a', "B")); //Toggle test for missing symbol m.AddTransition(new Transition <string>("A", 'b', "C")); //Toggle test for multiple of the same symbol //m.AddTransition(new Transition<string>("A", 'b', "A")); m.AddTransition(new Transition <string>("B", 'b', "C")); m.AddTransition(new Transition <string>("B", 'a', "A")); m.AddTransition(new Transition <string>("C", 'a', "C")); m.AddTransition(new Transition <string>("C", 'b', "C")); m.DefineAsStartState("A"); m.DefineAsFinalState("C"); return(m); }
public static String Serialize(Automata automata) { String serializedAutomata = ""; automata.GetStates().ToList().ForEach( x => serializedAutomata += SerializeState(x) + COMMA_SEPARATOR_CHAR ); serializedAutomata += NEWLINE_CHAR; automata.GetSymbols().ToList().ForEach( x => serializedAutomata += x + COMMA_SEPARATOR_CHAR ); serializedAutomata += NEWLINE_CHAR; serializedAutomata += SerializeState(automata.GetInitialState()) + NEWLINE_CHAR; automata.GetFinalStates().ToList().ForEach( x => serializedAutomata += SerializeState(x) + COMMA_SEPARATOR_CHAR ); serializedAutomata += NEWLINE_CHAR; automata.GetTransitions().ToList().ForEach( x => serializedAutomata += SerializeTransition(x) + NEWLINE_CHAR ); serializedAutomata += EOF_STR; return(serializedAutomata); }
private static Transition DeserializeTransition(String plainText, Automata automata) { String[] transitionMembers = plainText.Replace("(", "").Replace(")", "").Split(','); if (transitionMembers.Length != 3) { throw new AutomataSerializerException($"Invalid transition: '{plainText}'"); } String stateFrom = transitionMembers[0].Trim(); String input = transitionMembers[1]; String stateTo = transitionMembers[2].Trim(); if (input != Automata.SYMBOL_SPONTANEOUS_TRANSITION) { automata.EnsureContainsSymbol(input); } automata.EnsureContainsState(stateFrom); automata.EnsureContainsState(stateTo); return(new Transition( automata.GetStateLike(stateFrom), input, automata.GetStateLike(stateTo) )); }
public IEnumerator CheckStrings(Automata machine) { int readyForNext = 0; for (int i = 0; i < mustAccept.Count;) { if (readyForNext == i) { machine.StartCheckingInput(mustAccept[i]); readyForNext++; } if (machine.IsAnswerReady) { AutomataManager.Instance.ApplyInputCheck(i, machine.Result, true); i++; } yield return(null); } readyForNext = 0; for (int i = 0; i < mustNotAccept.Count;) { if (readyForNext == i) { machine.StartCheckingInput(mustNotAccept[i]); readyForNext++; } if (machine.IsAnswerReady) { AutomataManager.Instance.ApplyInputCheck(i, machine.Result, false); i++; } yield return(null); } checkingCoroutine = null; }
public bool StartDFA(Automata dfa, string input) { //从[state,index]处开始跑 bool runDFA(State state, int index) { if (index == input.Length) { if (dfa.terminators.Exists(terminator => state == terminator)) { return(true); } else { return(false); } } State next = null; if (null != (next = state.Transfer(input[index]))) { return(runDFA(next, index + 1)); } return(false); } return(runDFA(dfa.entry, 0)); }
public override void Update() { for (int x = -1; x <= 1; ++x) { for (int y = -1; y <= 1; ++y) { if (x == 0 && y == 0) { continue; } Vector2 pos = position + new Vector2(x, y); Particle p = grid.GetParticle(pos); if (active && p.id() == ePARTICLE.EMPTY) { Automata a = new Automata(); a.active = false; grid.AddParticle(a, pos); a.willActivate = a.shouldActivate(); } } } willActivate = shouldActivate(); //GD.Print(position, count, willActivate); }
public void Initialize() { string inp = ""; switch (automataType) { case AutomataType.dfa: _machine = new DFA(); inputAlphabet = UIManager.Instance.GetLanguageAlphabet().ToCharArray(); break; case AutomataType.DPDA: _machine = new DPDA(); inp = UIManager.Instance.GetLanguageAlphabet() + "λ"; inputAlphabet = (inp + "$").ToCharArray(); machineAlphabet = (UIManager.Instance.GetMachineAlphabet() + inp + "zZ").ToCharArray(); break; case AutomataType.Turing: gameObject.AddComponent <TuringHelper>(); _machine = new Turing(); inp = UIManager.Instance.GetLanguageAlphabet() + UIManager.Instance.GetMachineAlphabet() + "□"; inputAlphabet = inp.ToCharArray(); machineAlphabet = inputAlphabet; break; } }
public MainViewVM() { _user = _manager.User; _automata = _manager.Automata; _user.PropertyChanged += (s, a) => { RaisePropertyChanged(nameof(CheckAmount)); }; _automata.PropertyChanged += (s, a) => { RaisePropertyChanged(nameof(Credit)); }; //Кошелек пользователя UserWallet = new ObservableCollection <MoneyVM>(_user.UserWallet.Select(ms => new MoneyVM(ms))); Watch(_user.UserWallet, UserWallet, um => um.MoneyStack); //покупки пользователя CustomPurchases = new ObservableCollection <ProductVM>(_user.CustomPurchases.Select(ub => new ProductVM(ub))); Watch(_user.CustomPurchases, CustomPurchases, ub => ub.ProductStack); //деньги автомата AutomataBank = new ObservableCollection <MoneyVM>(_automata.AutomataBank.Select(a => new MoneyVM(a, _manager))); Watch(_automata.AutomataBank, AutomataBank, a => a.MoneyStack); //товары автомата ProductsInAutomata = new ObservableCollection <ProductVM>( _automata.ProductsInAutomata.Select(ap => new ProductVM(ap, _manager))); Watch(_automata.ProductsInAutomata, ProductsInAutomata, p => p.ProductStack); GetChange = new DelegateCommand(() => _manager.GetChange()); }
/// <summary> /// Run the verification and get the result. /// </summary> /// <returns></returns> public override void RunVerification() { if (SelectedEngineName == Constants.ENGINE_ANTICHAIN_DEPTH_FIRST_SEARCH) { Automata spec = BuildAutomata(InitSpecStep); TraceInclusionCheckDFSAntiChain(spec); } else { if (SelectedEngineName == Constants.ENGINE_ANTICHAIN_BREADTH_FIRST_SEARCH) { Automata spec = BuildAutomata(InitSpecStep); TraceInclusionCheckBFSAntiChain(spec); } else { DeterministicAutomata auto = BuildDeterministicAutomata(InitSpecStep); if (SelectedEngineName == Constants.ENGINE_REFINEMENT_DEPTH_FIRST_SEARCH) { TraceInclusionCheckDFS(auto); } else { TraceInclusionCheckBFS(auto); } } } }
public static Automata <string> ExampleSlide14Lesson2() { char[] alphabet = { 'a', 'b' }; Automata <string> m = new Automata <string>(alphabet); m.AddTransition(new Transition <string>("A", 'a', "C")); m.AddTransition(new Transition <string>("A", 'b', "B")); m.AddTransition(new Transition <string>("A", 'b', "C")); m.AddTransition(new Transition <string>("B", 'b', "C")); m.AddTransition(new Transition <string>("B", "C")); m.AddTransition(new Transition <string>("C", 'a', "D")); m.AddTransition(new Transition <string>("C", 'a', "E")); m.AddTransition(new Transition <string>("C", 'b', "D")); m.AddTransition(new Transition <string>("D", 'a', "B")); m.AddTransition(new Transition <string>("D", 'a', "C")); m.AddTransition(new Transition <string>("E", 'a')); m.AddTransition(new Transition <string>("E", "D")); // only on start state in a dfa: m.DefineAsStartState("A"); // two final states: m.DefineAsFinalState("C"); m.DefineAsFinalState("E"); return(m); }
public void TestSetSymbols() { Automata automata = new Automata(); String[] symbols = new String[] { "a", "b", "c" }; automata.SetSymbols(symbols); Assert.IsTrue(symbols.Length == automata.GetSymbols().Length); foreach (var x in symbols) { Assert.IsTrue(automata.ContainsSymbol(x)); } String[] newSymbols = new String[] { "d", "e", "f", "g", "h", "i", "j", "k" }; automata.SetSymbols(newSymbols); Assert.IsTrue(newSymbols.Length == automata.GetSymbols().Length); foreach (var x in newSymbols) { Assert.IsTrue(automata.ContainsSymbol(x)); } }
public void TestClearSymbols() { Automata automata = new Automata(); String[] symbols = new String[] { "a", "b", "c" }; automata.SetSymbols(symbols); Assert.IsTrue(symbols.Length == automata.GetSymbols().Length); foreach (var x in symbols) { Assert.IsTrue(automata.ContainsSymbol(x)); } automata.ClearSymbols(); Assert.AreEqual(0, automata.GetSymbols().Length); foreach (var x in symbols) { Assert.IsFalse(automata.ContainsSymbol(x)); } }
public AutomataCard(Automata automata) { InitializeComponent(); AutomataNameText.Text = automata.Name; this.automata = automata; }
public void TestClearStates() { Automata automata = new Automata(); State[] states = new State[] { new State("x", false), new State("y", false), new State("z", true) }; automata.SetStates(states); Assert.IsTrue(states.Length == automata.GetStates().Length); foreach (var x in states) { Assert.IsTrue(automata.ContainsState(x)); } automata.ClearStates(); Assert.AreEqual(0, automata.GetStates().Length); foreach (var x in states) { Assert.IsFalse(automata.ContainsState(x)); } }
public void TestRemoveStates() { Automata automata = new Automata(); State[] states = new State[] { new State("x", false), new State("y", false), new State("z", true) }; String[] removeStates = new String[] { "y", "z" }; automata.AddStates(states); automata.RemoveStates(removeStates); List <String> expectedStates = states.ToList().Where( x => !removeStates.Contains(x.Name) ).ToList().Select( x => x.Name ).ToList(); Assert.IsTrue(expectedStates.Count == automata.GetStates().Length); foreach (var x in expectedStates) { Assert.IsTrue(automata.ContainsState(x)); } }
public void TestAddTransitions() { Automata automata = new Automata(); String[] symbols = new String[] { "a", "b", "c" }; State[] states = new State[] { new State("x", false), new State("y", false), new State("z", true) }; Transition[] transitions = new Transition[] { new Transition(states[0], symbols[0], states[1]), new Transition(states[1], symbols[1], states[2]), new Transition(states[2], symbols[2], states[0]), new Transition(states[0], symbols[0], states[2]), }; automata.SetAutomataType(AutomataType.AFNe); automata.SetSymbols(symbols); automata.SetStates(states); automata.SetInitialState(states[0]); automata.SetTransitions(transitions); Assert.IsTrue(transitions.Length == automata.GetTransitions().Length); foreach (var x in transitions) { Assert.IsTrue(automata.ContainsTransition(x)); } }
public AutomataVisualizer(Automata automata) { InitializeComponent(); isOneDimensional = automata.Neighborhood[0].Length == 1; ruleSet = automata.RuleSet; cellSize = automata.CellSize; // Size of gameField in cells width = (int)GameField.Width / cellSize; height = (int)GameField.Height / cellSize; timer.Tick += (object sender, EventArgs e) => UpdateAutomata(); timer.Interval = new TimeSpan((int)(DelaySlider.Value * TimeSpan.TicksPerSecond)); Cell[][] startingField = CellListGenerator.Generate(width, isOneDimensional ? 1 : height); gameField = new GameField( startingField, automata.Neighborhood, automata.IsInfinite ); CurrentGenerationLabel.Content = $"{gameField.CurrentGeneration}"; if (isOneDimensional) { ClearFieldButton.IsEnabled = false; } DrawAutomata(); }
/// <summary> /// Run the verification and get the result. /// </summary> /// <returns></returns> public override void RunVerification() { if (SelectedEngineName == Constants.ENGINE_FD_REFINEMENT_ANTICHAIN_DEPTH_FIRST_SEARCH) { Automata spec = BuildAutomataWithRefusalsAndDiv(InitSpecStep); FailuresDivergenceInclusionCheckDFSAntichain(spec); } else { if (SelectedEngineName == Constants.ENGINE_FD_REFINEMENT_ANTICHAIN_BREADTH_FIRST_SEARCH) { Automata spec = BuildAutomataWithRefusalsAndDiv(InitSpecStep); FailuresDivergenceInclusionCheckBFSAntichain(spec); } else { DeterministicAutomata auto = BuildDeterministicAutomataWithRefusalsAndDiv(InitSpecStep); if (SelectedEngineName == Constants.ENGINE_FD_REFINEMENT_DEPTH_FIRST_SEARCH) { FailuresDivergenceInclusionCheckDFS(auto); } else { FailuresDivergenceInclusionCheckBFS(auto); } } } }
public void TestRemoveSymbols() { Automata automata = new Automata(); String[] symbols = new String[] { "a", "b", "c" }; String[] removeSymbols = new String[] { symbols[0], symbols[1] }; automata.AddSymbols(symbols); automata.RemoveSymbols(removeSymbols); List <String> expectedSymbols = new List <String>(); symbols.ToList().ForEach( x => { if (!removeSymbols.Contains(x)) { expectedSymbols.Add(x); } } ); Assert.IsTrue(expectedSymbols.Count == automata.GetSymbols().Length); foreach (var x in expectedSymbols) { Assert.IsTrue(automata.ContainsSymbol(x)); } }
public RegexAutomata(Automata automata) { this.Alphabet = new List <char>(automata.alphabet); this.StartNode = new RegexNode("qStart"); this.FinalNode = new RegexNode("qFinal", true); CreateRegexNodes(automata.nodes); }
public static Automata Parse(this Automata automata, IEnumerable <string> automataData) { // valida se o parser pode ser começado automata.ParseAutomataDataScopeValidate(automataData); var states = automataData.ElementAt(1).Split(','); var alphabet = automataData.ElementAt(2).Split(','); var q0 = automataData.ElementAt(3); var f = automataData.ElementAt(4).Split(','); automata.States = states.Select(StringFormat).ToList(); automata.Alphabet = alphabet.Select(StringFormat).ToList(); automata.Q0 = q0.StringFormat(); automata.F = f.Select(StringFormat).ToList(); var transitions = automataData.Skip(5); foreach (var transition in transitions) { if (transition.Contains("####")) { break; } else { automata.AddTransition(new Transition().Parse(transition)); } } return(automata); }
//Compila el codigo, analiza y pinta private void compilarToolStripMenuItem1_Click(object sender, EventArgs e) { try { compilado = true; listaNodos.Clear(); analizarAutomata = new Automata(); //Analiza si el codigo esta vacio if (!rtbCodigo.Text.Equals("")) { listaTokens.Clear(); //Carga la lista de los tokens validos listaTokens = analizarAutomata.generarTokens(rtbCodigo.Text); //Compila compilar(); } else { MessageBox.Show("El codigo esta vacio o no es valido"); compilado = false; } } catch (Exception) { MessageBox.Show("El codigo introducido no es valido"); compilado = false; } }
private void button1_Click(object sender, EventArgs e) { Archivo file = new Archivo(); Automata scanner = new Automata(); try { file.ObtenerUbicacion(); scanner.DescomponerDatos(file.LeerArchivo()); } catch { MessageBox.Show("ERROR EN LA LECTURA DEL ARCHIVO, NO POSEE EL FORMATO ESTABLECIDO"); } string ER = ""; for (int x = 0; x < scanner.LTokens.Count; x++) { ER += "(" + scanner.LTokens[x].ER[1] + ")" + "|"; } ER = ER.TrimEnd('|'); ER = "(" + ER + ")·#"; try { ArrayList entrada = SepararSimbolos(ER); ArrayList salida = InfijoASufijo(entrada); CalcularAFD(salida); MessageBox.Show("AFD Creado"); } catch { MessageBox.Show("Error al buscar nombre de alfabeto"); } }
public void have_next_generation_after_evolve() { var automata = new Automata(GivenCells(), rule); automata.Evolve(); automata.HistoryOfGenerations.Count.Should().Be(2); }
public Automata<String> Minimization(Automata<String> Automaton) { AutomataConverter c = new AutomataConverter(); Automata<String> miniantwoord = c.NDFAToDFA(c.reverseAutomata(c.NDFAToDFA(c.reverseAutomata(Automaton)))); return c.renameStates(miniantwoord); }
public void apply_given_rule_to_each_neighborhood_during_evolution() { var automata = new Automata(GivenCells(), rule); automata.Evolve(); rule.Received(3).Apply(Arg.Any <Neighborhood>()); }
public Automata<String> DFAToNDFA(Automata<String> Automata) { SortedSet<char> alphabet = Automata.getAlphabet(); Automata<String> ndfa = new Automata<String>(alphabet); foreach (var state in Automata.getStates()) { } return ndfa; }
public void run(Automata a, Transition trans) { if (full != null){ full(a,trans); } if (automata != null){ automata(a); } if (neutral != null){ neutral(); } }
public bool run(Automata a, Transition trans) { if (full != null){ if (!full(a,trans)) return false; } if (automata != null){ if (!automata(a)) return false; } if (neutral != null){ if (!neutral()) return false; } return true; }
public Automata<String> NDFAToDFA(Automata<String> Automata) { SortedSet<char> alphabet = Automata.getAlphabet(); Automata<String> dfa = new Automata<String>(alphabet); foreach (String state in Automata.getStates()) { foreach (var letter in alphabet) { foreach (var item in Automata.getToStates(state, letter)) { Console.WriteLine("State: " + state + " met Letter: " + letter + " kan ik hier komen: " + item); } } } return dfa; }
// Use this for initialization void Start () { StrawberryStateMachine berry_state = StrawberryStateMachine.main; automata = gameObject.GetComponent<Automata> (); visibility = gameObject.GetComponent<ObjectVisibility>(); Initialize(); drag = gameObject.GetComponent<DragHandle>(); drag.register_incoming (berry_state.fsm.transition("field_drag")) .register_incoming (berry_state.fsm.transition("fall_drag")) .register_incoming (berry_state.fsm.transition("hand_drag")) .register_state (berry_state.fsm.state("drag")) .register_outgoing(berry_state.fsm.transition("drag_fall")); foreach(BasketComponent basket in BasketComponent.baskets){ drag.register_incoming(basket.remove); } }
public void run(Automata a, State s) { if (limit < 0 || times_ran < limit){ if (full != null){ full(a,s); } if (automata != null){ automata(a); } if (state != null){ state(s); } if (neutral != null){ neutral(); } times_ran++; } }
public static void BevatWoord() { Console.Clear(); Console.WriteLine("1. Bevat woord"); Automata <string> a = new Automata<string>(); AutomataConverter c = new AutomataConverter(); var ans = Console.ReadLine(); int choice=0; if (int.TryParse(ans, out choice)) { switch (choice) { case 1: Console.Clear(); Console.WriteLine("De volgende NDFA/DFA is gegenereerd:"); a = c.renameStates(Tester.generateRandomNdfa()); // a.printTransitions(); Tester.generateAutomataImage(a); Console.WriteLine("Geef een string mee en kijk of hij word geaccepteerd. (BV: aaabaabaaa)"); var input = Console.ReadLine(); if (a.isStringAccepted(input)) { Console.WriteLine("De string word geaccepteerd."); } else Console.WriteLine("De string word NIET geaccepteerd."); ResetToMenu(); break; default: Console.WriteLine("Deze optie is niet beschikbaar." + Environment.NewLine + "Druk op een knop om terug te gaan"); ResetToMenu(); break; } } else { Console.WriteLine("Vul alstublieft het nummer van de keuze in."+ Environment.NewLine + "Druk op een knop om terug te gaan"); ResetToMenu(); } }
private void FailuresDivergenceInclusionCheckDFSAntichain(Automata spec) { List<ConfigurationBase> toReturn = new List<ConfigurationBase>(); Stack<ConfigurationBase> pendingImpl = new Stack<ConfigurationBase>(1000); Stack<NormalizedFAState> pendingSpec = new Stack<NormalizedFAState>(1000); //The following are for identifying a counterexample trace. Stack<int> depthStack = new Stack<int>(1000); depthStack.Push(0); List<int> depthList = new List<int>(1000); //The above are for identifying a counterexample trace. NormalizedFAState initialSpec = (new NormalizedFAState(spec.InitialState)).TauReachable(); //implementation initial state pendingImpl.Push(InitialStep); //specification initial state pendingSpec.Push(initialSpec); AntiChain antichain = new AntiChain(); antichain.Add(InitialStep.GetID(), initialSpec.States); while (pendingImpl.Count > 0) { if (CancelRequested) { VerificationOutput.NoOfStates = antichain.GetNoOfStates(); return; } ConfigurationBase currentImpl = pendingImpl.Pop(); NormalizedFAState currentSpec = pendingSpec.Pop(); //The following are for identifying a counterexample trace. int depth = depthStack.Pop(); if (depth > 0) { while (depthList[depthList.Count - 1] >= depth) { int lastIndex = depthList.Count - 1; depthList.RemoveAt(lastIndex); toReturn.RemoveAt(lastIndex); } } toReturn.Add(currentImpl); depthList.Add(depth); //The above are for identifying a counterexample trace. if (currentSpec.IsDiv()) { VerificationOutput.NoOfStates = antichain.GetNoOfStates(); VerificationOutput.VerificationResult = VerificationResultType.VALID; FailureType = RefinementCheckingResultType.Valid; return; } bool implIsDiv = currentImpl.IsDivergent(); if (implIsDiv) { VerificationOutput.NoOfStates = antichain.GetNoOfStates(); VerificationOutput.CounterExampleTrace = toReturn; VerificationOutput.VerificationResult = VerificationResultType.INVALID; FailureType = RefinementCheckingResultType.DivCheckingFailure; return; } IEnumerable<ConfigurationBase> nextImpl = currentImpl.MakeOneMove(); VerificationOutput.Transitions += nextImpl.Count(); List<string> implRefusal = new List<string>(); bool hasTau = false; //for (int i = 0; i < nextImpl.Length; i++) foreach (ConfigurationBase next in nextImpl) { NormalizedFAState nextSpec = currentSpec; if (next.Event != Constants.TAU) { implRefusal.Add(next.Event); //nextSpec = currentSpec.Post[nextImpl[i].Event]; nextSpec = currentSpec.NextWithTauReachable(next.Event); //The following checks if a violation is found. //First, check for trace refinement, which is necessary for all other refinement as well. if (nextSpec.States.Count == 0) { toReturn.Add(next); VerificationOutput.NoOfStates = antichain.GetNoOfStates(); VerificationOutput.CounterExampleTrace = toReturn; VerificationOutput.VerificationResult = VerificationResultType.INVALID; FailureType = RefinementCheckingResultType.TraceRefinementFailure; return; } } else { hasTau = true; } if (!antichain.Add(next.GetID(), nextSpec.States)) { pendingImpl.Push(next); pendingSpec.Push(nextSpec); depthStack.Push(depth + 1); } } //if the implememtation state is stable, then check for failures inclusion if (!hasTau) { //enabledS is empty if and only if the spec state is divergent. if (!RefusalContainment(implRefusal, currentSpec.GetFailuresNegate())) { VerificationOutput.NoOfStates = antichain.GetNoOfStates(); VerificationOutput.CounterExampleTrace = toReturn; VerificationOutput.VerificationResult = VerificationResultType.INVALID; FailureType = RefinementCheckingResultType.FailuresRefinementFailure; return; } } } VerificationOutput.NoOfStates = antichain.GetNoOfStates(); VerificationOutput.VerificationResult = VerificationResultType.VALID; FailureType = RefinementCheckingResultType.Valid; }
public void invoke_update_own(Automata a){ foreach (StateEvent e in update_own_actions) { e.run(a,this); } }
public void invoke_entry(Automata a){ visitors.Add(a); foreach (StateEvent e in entry_actions) { e.run(a,this); } }
public static void testRegularExpressionThompson2() { //This is the regular expression ( (a|b|c|d)|(ab|ad|bc) )+ (aab) (c|cad|cb)* RegularExpression exp1, exp2, exp3, exp4, a, b, c, d, ab, ad, bc, abb, cad, cb,all; a = new RegularExpression("a"); b = new RegularExpression("b"); c = new RegularExpression("c"); d = new RegularExpression("d"); ab = new RegularExpression("ab"); ad = new RegularExpression("ad"); bc = new RegularExpression("bc"); abb = new RegularExpression("abb"); cad = new RegularExpression("cad"); cb = new RegularExpression("cb"); // (a|b|c|d) exp1 = (a.or(b).or(c).or(d)); // (ab|ad|bc) exp2 = (ab.or(ad).or(bc)); // (c|cad|cb)* exp3 = (c.or(cad).or(cb).star()); // ( (a|b|c|d) | (ab|ad|bc) )+ exp4 = (exp1.or(exp2).plus()); // Merge all = exp4.dot(abb.dot(exp3)); Automata<String> auto = new Automata<String>(); int num = 0; all.regexToNDFA(ref num, ref auto); generateAutomataImage(auto); return; }
public void invoke_exit(Automata a){ visitors.Remove(a); foreach (StateEvent e in exit_actions) { e.run(a,this); } }
void UpdatePhysics(Automata a){ Rigidbody body = a.gameObject.GetComponent<Rigidbody> (); if (body != null) { if (!GameStateManager.main.basket_physics_enabled()){ body.isKinematic = true; } else { body.isKinematic = false; } } }
public static void RegExToNdfaDfa() { Console.Clear(); Console.WriteLine("1. RegEx -> NDFA"); var ans = Console.ReadLine(); int choice=0; Automata<String> auto = new Automata<String>(); int num = 0; if (int.TryParse(ans, out choice)) { switch (choice) { case 1: Console.Clear(); char[] alfabet = { 'a', 'b', 'c' }; RegularExpression b = Tester.generateRandomRegex(alfabet, 5); Console.WriteLine(b.ToString() + Environment.NewLine + "Geeft:"); b.regexToNDFA(ref num, ref auto); auto.printTransitions(); Tester.generateAutomataImage(auto); ResetToMenu(); break; default: Console.WriteLine("Deze optie is niet beschikbaar." + Environment.NewLine + "Druk op een knop om terug te gaan"); ResetToMenu(); break; } } else { Console.WriteLine("Vul alstublieft het nummer van de keuze in."+ Environment.NewLine + "Druk op een knop om terug te gaan"); ResetToMenu(); } }
public static Automata<String> testMinimalization(Automata<String> automata) { AutomataMinimalization m = new AutomataMinimalization(); return m.Minimization(automata); }
public static Automata<String> TestDFA2() { char [] alphabet = {'a', 'b'}; Automata<String> m = new Automata<String>(alphabet); m.addTransition( new Transition<String> ("q0", 'a', "q2") ); m.addTransition( new Transition<String> ("q0", 'b', "q3") ); m.addTransition( new Transition<String> ("q1", 'a', "q3") ); m.addTransition( new Transition<String> ("q1", 'b', "q2") ); m.addTransition( new Transition<String> ("q2", 'a', "q0") ); m.addTransition( new Transition<String> ("q2", 'b', "q4") ); m.addTransition( new Transition<String> ("q3", 'a', "q1") ); m.addTransition( new Transition<String> ("q3", 'b', "q5") ); m.addTransition( new Transition<String> ("q4", 'a', "q6") ); m.addTransition( new Transition<String> ("q4", 'b', "q5") ); m.addTransition( new Transition<String> ("q5", 'a', "q2") ); m.addTransition( new Transition<String> ("q5", 'b', "q0") ); m.addTransition( new Transition<String> ("q6", 'a', "q4") ); m.addTransition( new Transition<String> ("q6", 'b', "q0") ); // only on start state in a dfa: m.defineAsStartState("q0"); // final states: m.defineAsFinalState("q1"); m.defineAsFinalState("q3"); m.defineAsFinalState("q4"); m.defineAsFinalState("q6"); return m; }
void Awake(){ if (a == null) { a = gameObject.GetComponent<Automata>(); } }
public static Automata<String> TestNDFA2() { char [] alphabet = {'a', 'b', 'c', 'd'}; Automata<String> m = new Automata<String>(alphabet); m.addTransition( new Transition<String> ("0", '$', "1") ); m.addTransition( new Transition<String> ("0", '$', "3") ); m.addTransition( new Transition<String> ("1", 'b', "2") ); m.addTransition( new Transition<String> ("3", 'a', "4") ); m.addTransition( new Transition<String> ("2", '$', "5") ); m.addTransition( new Transition<String> ("4", '$', "5") ); m.addTransition( new Transition<String> ("5", '$', "0") ); m.addTransition( new Transition<String> ("5", '$', "6") ); m.addTransition( new Transition<String> ("6", 'b', "7") ); m.addTransition( new Transition<String> ("7", 'c', "8") ); m.addTransition( new Transition<String> ("8", 'd', "9") ); // only on start state in a dfa: m.defineAsStartState("0"); // one final state: m.defineAsFinalState("9"); return m; }
public static Automata<String> TestProcedure2() { char [] alphabet = {'a', 'b'}; Automata<String> m = new Automata<String>(alphabet); m.addTransition( new Transition<String> ("A", 'a', "C") ); m.addTransition( new Transition<String> ("A", 'b', "B") ); m.addTransition( new Transition<String> ("A", 'b', "C") ); m.addTransition( new Transition<String> ("B", 'b', "C") ); m.addTransition( new Transition<String> ("B", "C") ); m.addTransition( new Transition<String> ("C", 'a', "D") ); m.addTransition( new Transition<String> ("C", 'a', "E") ); m.addTransition( new Transition<String> ("C", 'b', "D") ); m.addTransition( new Transition<String> ("D", 'a', "B") ); m.addTransition( new Transition<String> ("D", 'a', "C") ); m.addTransition( new Transition<String> ("E", 'a') ); m.addTransition( new Transition<String> ("E", "D") ); // only on start state in a dfa: m.defineAsStartState("A"); // two final states: m.defineAsFinalState("C"); m.defineAsFinalState("E"); return m; }
public static void testRegExpThompson() { RegularExpression exp1, exp2, exp3, exp4, exp5, a, b, c, all, why; a = new RegularExpression("a"); b = new RegularExpression("b"); c = new RegularExpression("c"); //exp 1 (baa) exp1 = new RegularExpression("baa"); //exp 2 (ac) exp2 = new RegularExpression("ac"); //exp 4 (baa)+ exp4 = exp1.plus(); //exp 5 (ac)* exp5 = exp2.star(); //exp 3 (a|b|c)* exp3 = (a.or(b).or(c)).star(); //all (a|b|c)* (baa)+ (ca)* all = exp3.dot(exp4.dot(exp5)); why = new RegularExpression("baa").plus().star().plus(); foreach (String o in all.getLanguage(5)) { Console.Write(o + " "); } Automata<String> auto = new Automata<String>(); int num = 0; why.regexToNDFA(ref num,ref auto); return; }
public static void generateAutomataImage(Automata<String> automata, string output_file="", string fileformat="svg") { string executable_file = ""; string file_opener = ""; bool no_open = false; if (output_file != "") no_open = true; bool windows = false; int p = (int) Environment.OSVersion.Platform; if ((p == 4) || (p == 6) || (p == 128)) { //UNIX if (output_file == "") if (InputOutput.IsRunningOnMac()) output_file = Path.GetTempPath() + "generatedAutomata." + fileformat; else output_file = "/tmp/tmp."+fileformat; executable_file = "dot"; if(InputOutput.IsRunningOnMac()) file_opener = "open"; else file_opener = "xdg-open"; } else { windows = true; if (output_file == "") { output_file = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); output_file = output_file + "\\img."+fileformat; } executable_file = "C:\\Program Files (x86)\\Graphviz2.38\\bin\\dot.exe"; } string dotinfo = automata.printGraphviz(); try { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.CreateNoWindow = false; startInfo.UseShellExecute = false; startInfo.FileName = executable_file; startInfo.RedirectStandardInput = true; startInfo.WindowStyle = ProcessWindowStyle.Hidden; startInfo.Arguments = " -T"+ fileformat +" -o " + output_file; Process exeProcess = new Process(); exeProcess.StartInfo = startInfo; exeProcess.Start (); //exeProcess.WaitForInputIdle(); StreamWriter writer = exeProcess.StandardInput; writer.Write (dotinfo); writer.Flush (); writer.WriteLine (); if(!windows) exeProcess.WaitForInputIdle(); writer.Close (); exeProcess.WaitForExit(); if (!no_open){ if (!windows) { Process openProcess = new Process(); openProcess.StartInfo.FileName = file_opener; openProcess.StartInfo.Arguments = output_file; openProcess.Start(); } else { Process.Start(output_file); } } } catch { Console.Write("Random exception"); } }
private static Automata BuildAutomataWithRefusalsAndDiv(ConfigurationBase InitSpecStep) { Dictionary<string, FAState> visited = new Dictionary<string, FAState>(); Stack<ConfigurationBase> working = new Stack<ConfigurationBase>(1024); working.Push(InitSpecStep); Automata auto = new Automata(); FAState init = auto.AddState(); auto.SetInitialState(init); visited.Add(InitSpecStep.GetID(), init); do { ConfigurationBase current = working.Pop(); FAState currentState = visited[current.GetID()]; if (current.IsDivergent()) { currentState.IsDiv = true; } else { IEnumerable<ConfigurationBase> list = current.MakeOneMove(); List<string> negateRefusal = new List<string>(); bool hasTau = false; //for (int i = 0; i < list.Length; i++) foreach (ConfigurationBase step in list) { //ConfigurationBase step = list[i]; if (step.Event == Constants.TAU) { hasTau = true; } else { negateRefusal.Add(step.Event); } FAState target; string nextID = step.GetID(); if (visited.ContainsKey(nextID)) { target = visited[nextID]; } else { target = auto.AddState(); working.Push(step); visited.Add(nextID, target); } auto.AddTransition(currentState, step.Event, target); } if (hasTau) { currentState.NegatedRefusal = null; } else { currentState.NegatedRefusal = negateRefusal; } } } while (working.Count > 0); return auto; }
public static Automata<String> TestDFA() { char [] alphabet = {'a', 'b'}; Automata<String> m = new Automata<String>(alphabet); m.addTransition( new Transition<String> ("q0", 'a', "q1") ); m.addTransition( new Transition<String> ("q0", 'b', "q4") ); m.addTransition( new Transition<String> ("q1", 'a', "q4") ); m.addTransition( new Transition<String> ("q1", 'b', "q2") ); m.addTransition( new Transition<String> ("q2", 'a', "q3") ); m.addTransition( new Transition<String> ("q2", 'b', "q4") ); m.addTransition( new Transition<String> ("q3", 'a', "q1") ); m.addTransition( new Transition<String> ("q3", 'b', "q2") ); // the error state, loops for a and b: m.addTransition( new Transition<String> ("q4", 'a') ); m.addTransition( new Transition<String> ("q4", 'b') ); // only on start state in a dfa: m.defineAsStartState("q0"); // two final states: m.defineAsFinalState("q2"); m.defineAsFinalState("q3"); return m; }
/// <summary> /// Sauvegarder l'automate dans un ficher /// </summary> /// <param name="Automate">L'automate à sauvegarder.</param> /// <param name="Path">le path du fichier</param> /// <returns>Le resultat du sauvegarde</returns> public AutomtateSaveResult Save(Automata Automate, String Path) { AutomtateSaveResult ret = new AutomtateSaveResult(); //StreamReader sr = null; StreamWriter sw = null; try { if (File.Exists(Path)) { File.Delete(Path); ret = AutomtateSaveResult.REPLACE; } // Le fichier n'existe pas. On le crée. sw = new StreamWriter(Path); sw.WriteLine("<Automate>"); sw.WriteLine(" <Name>{0}</Name>", Automate.Name); sw.WriteLine(" <Type>{0}</Type>", (int)Automate.getType()); sw.WriteLine(" <X>"); foreach (char car in Automate.X) sw.WriteLine(" <car>{0}</car>", car); sw.WriteLine(" </X>"); sw.WriteLine(" <S0>{0}</S0>", Automate.S0); sw.WriteLine(" <S>{0}</S>", Automate.S); sw.WriteLine(" <F>"); foreach (int fi in Automate.F) sw.WriteLine(" <fi>{0}</fi>", fi); sw.WriteLine(" </F>"); sw.WriteLine(" <I>"); for (int i = 0; i < Automate.S; i++) if (Automate.getType() == Automata.TYPE.Gfa) foreach (object motObj in ((Gfa)Automate).Read) { string mot = motObj.ToString(); foreach (int j in ((Gfa)Automate).getInstruction(i, mot)) sw.WriteLine(" <triplet>({0},{1},{2})</triplet>", i, mot, j); } else { foreach (char car in Automate.X) switch (Automate.getType()) { case Automata.TYPE.Dfa: if (((Dfa)Automate).getInstruction(i, car) != -1) sw.WriteLine(" <triplet>({0},{1},{2})</triplet>", i, car, ((Dfa)Automate).getInstruction(i, car)); break; case Automata.TYPE.Nfa: foreach (int j in ((Nfa)Automate).getInstruction(i, car)) sw.WriteLine(" <triplet>({0},{1},{2})</triplet>", i, car, j); break; case Automata.TYPE.PGfa: foreach (int j in ((PGfa)Automate).getInstruction(i, car)) sw.WriteLine(" <triplet>({0},{1},{2})</triplet>", i, car, j); break; case Automata.TYPE.Gfa: //deja fait break; default: break; } } sw.WriteLine(" </I>"); sw.WriteLine("</Automate>"); sw.Close(); sw = null; } catch (Exception ex) { ret = AutomtateSaveResult.ERROR; System.Windows.Forms.MessageBox.Show("Erreur lors de sauvegarde : \n"+ex.Message, "Erreur", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Stop); } finally { // Fermeture streamwriter if (sw != null) sw.Close(); if (ret != AutomtateSaveResult.REPLACE) ret = AutomtateSaveResult.NEW; } return ret; }
public static Automata<String> testConverter(Automata<String> ndfa) { AutomataConverter c = new AutomataConverter(); return c.NDFAToDFA(ndfa); }
void UnparentToBasket(Automata a){ a.gameObject.transform.SetParent(null, true); update_stats(); }
public static Automata<String> generateRandomNdfa() { int num = 0; Automata<String> auto = new Automata<String>(); char[] alfabet = { 'a', 'b'}; RegularExpression b = Tester.generateRandomRegex(alfabet, 5); Console.WriteLine(b.ToString() + Environment.NewLine + "Geeft:"); b.regexToNDFA(ref num, ref auto); return auto; }
public static Automata<String> TestNDFA() { char [] alphabet = {'a', 'b'}; Automata<String> m = new Automata<String>(alphabet); m.addTransition( new Transition<String> ("1", 'a', "2") ); m.addTransition( new Transition<String> ("2", 'b', "2") ); m.addTransition( new Transition<String> ("2", 'b', "4") ); m.addTransition( new Transition<String> ("1", 'a', "3") ); m.addTransition( new Transition<String> ("3", 'a', "2") ); m.addTransition( new Transition<String> ("3", 'a', "4") ); m.addTransition( new Transition<String> ("4", 'a', "3") ); // only on start state in a dfa: m.defineAsStartState("1"); // two final states: m.defineAsFinalState("3"); m.defineAsFinalState("4"); return m; }
public static Automata<String> testReverse(Automata<String> automata) { AutomataConverter c = new AutomataConverter(); Automata<String> a = c.reverseAutomata(automata); return a; }