private static string GetNonFinalRuleInfo <S>(int k, IAutomaton <S> aut, ITransducer <S> trans, int source, int target, List <S> rules, Func <S, string> describeS = null) { if (describeS == null) { describeS = aut.DescribeLabel; } string lab = ""; string info = ""; for (int i = 0; i < rules.Count; i++) { lab += (lab == "" ? "" : ", ") + describeS(rules[i]); if (trans != null) { info += string.Format("Rule{0}.Guard = \"{1}\" Rule{0}.Update = \"{2}\" Rule{0}.Yields = \"{3}\" ", i + 1, EncodeChars(trans.DescribeGuard(rules[i])), EncodeChars(trans.DescribeUpdate(rules[i])), EncodeChars(trans.DescribeYields(rules[i]))); } } if (k >= 0 && lab.Length > k) { lab = lab.Substring(0, k) + "..."; } lab = EncodeChars(lab); if (lab.Length > 50) { info += string.Format(" HiddenLabel = \"{0}\"", lab); lab = "..."; } return(string.Format("<Link Source=\"{0}\" Target=\"{1}\" Label=\"{2}\" Category=\"NonepsilonTransition\" {3}/>", source, target, lab, info)); }
public static ISet <int> GetEpsilonClosure(this IAutomaton @this, params int[] states) { var set = new HashSet <int>(); var queue = new Queue <int>(); foreach (var state in states) { queue.Enqueue(state); } while (queue.Any()) { var source = queue.Dequeue(); set.Add(source); var targets = @this.TransitionsBySource.GetOrDefault(source)? [CharSet.Epsilon] ?? Enumerable.Empty <int>(); foreach (var target in targets) { if (!set.Contains(target)) { queue.Enqueue(target); } } } return(set); }
public static IAutomaton Create(IAutomaton s1, IAutomaton s2) { // Attempt to simplify/canonicalise the resulting state as much as possible. if (s1 is RejectState) { return(s2); } if (s2 is RejectState) { return(s1); } if (s1.Equals(s2)) { return(s1); } if (s1 is OrState os) { return(Create(os.State1, Create(os.State2, s2))); } if (s1.GetHashCode() < s2.GetHashCode()) { return(new OrState(s2, s1)); } return(new OrState(s1, s2)); }
public static IAutomaton Create(IAutomaton s1, IAutomaton s2) { if (s1 is RejectState) { return(s1); } if (s2 is RejectState) { return(s2); } if (s1 is EmptyState) { return(s2); } if (s2 is EmptyState) { return(s1); } if (s1 is SeqState ss) { return(Create(ss.State1, Create(ss.State2, s2))); } return(new SeqState(s1, s2)); }
private string GetDFAInfo <S>(IAutomaton <S> fa) { StringBuilder sb = new(); sb.Append("|Q|="); sb.Append(fa.StateCount); sb.Append(" "); sb.Append('|'); sb.Append(DeltaCapital); sb.Append("|="); sb.Append(fa.TransitionCount); sb.Append(" "); sb.Append('|'); sb.Append(SigmalCapital); sb.Append("|="); sb.Append(fa.Alphabet.Length); sb.Append(" "); sb.Append(SigmalCapital); sb.Append('='); for (int i = 0; i < fa.Alphabet.Length; i++) { if (i > 0) { sb.Append(','); } sb.Append(fa.DescribeLabel(fa.Alphabet[i])); } return(sb.ToString()); }
private static string GetStateInfo <S>(IAutomaton <S> fa, int state) { StringBuilder sb = new(); sb.Append(fa.DescribeState(state)); return(sb.ToString()); }
public static IEnumerable <int> Step(this IAutomaton @this, IEnumerable <int> state, char character) { return(@this.GetEpsilonClosure(state.SelectMany(s => @this.TransitionsBySource .GetOrDefault(s, EmptyTargets) .ReadChar(character)) .ToArray())); }
private static bool MarkDistinguishables(bool?[,] pairs, IAutomaton automaton, int aIndex, int bIndex) { if (pairs[aIndex, bIndex] != null) { return(pairs[aIndex, bIndex].Value); } var aInputs = automaton.TransitionsBySource.GetOrDefault(aIndex, AutomatonExtensions.EmptyTargets).GetKeys().ToArray(); var bInputs = automaton.TransitionsBySource.GetOrDefault(bIndex, AutomatonExtensions.EmptyTargets).GetKeys().ToArray(); bool result; if (aInputs.Except(bInputs).Any() || bInputs.Except(aInputs).Any()) { result = true; } else { result = false; //set her to avoid stack overflow when entering a cycle! pairs[aIndex, bIndex] = false; pairs[bIndex, aIndex] = false; foreach (var c in aInputs) { var nextAIndex = automaton.TransitionsBySource[aIndex][c].First(); var nextBIndex = automaton.TransitionsBySource[bIndex][c].First(); //first, because DFA if (MarkDistinguishables(pairs, automaton, nextAIndex, nextBIndex)) { result = true; break; } } } pairs[aIndex, bIndex] = result; pairs[bIndex, aIndex] = result; return(result); }
/// <summary> /// Write the automaton in dgml format in the current directory. /// </summary> /// <param name="fa">the automaton to write</param> /// <param name="name">the name of the output file, if filename does not end with .dgml then .dgml is added as suffix</param> public static void SaveGraph <S>(int k, IAutomaton <S> fa, string name, Func <S, string> describeS = null) { string filename = name + (name.EndsWith(".dgml") ? "" : ".dgml"); System.IO.StreamWriter sw = new System.IO.StreamWriter(filename); AutomatonToDgml(k, fa, name, sw, describeS); sw.Close(); }
public Run(IStored <ScheduledTasks> tasks, IStored <ScheduledTasks> likes, Cli cli, IAutomaton automaton, ILog log) { _tweetTasks = tasks; _likeTasks = likes; _cli = cli; _automaton = automaton; _log = log; }
///// <summary> ///// Write the automaton in dot format. ///// </summary> ///// <param name="fa">the automaton to write</param> ///// <param name="faName">the name of the automaton</param> ///// <param name="filename">the name of the output file</param> ///// <param name="rankdir">the main direction of the arrows</param> ///// <param name="fontsize">the size of the font in labels</param> ///// <param name="descr">function that describes the labels as strings</param> //public static void AutomatonToDot<S>(Func<S, string> descr, IAutomaton<S> fa, string faName, string filename, RANKDIR rankdir, int fontsize) //{ // string filenamedot = (filename.EndsWith(".dot") ? filename : filename + ".dot"); // System.IO.StreamWriter sw = new System.IO.StreamWriter(filenamedot); // AutomatonToDot(descr, fa, faName, sw, rankdir, fontsize, false); // sw.Close(); //} /// <summary> /// Write the automaton in dot format. /// </summary> /// <param name="fa">the automaton to write</param> /// <param name="faName">the name of the automaton</param> /// <param name="filename">the name of the output file</param> /// <param name="rankdir">the main direction of the arrows</param> /// <param name="fontsize">the size of the font in labels</param> /// <param name="descr">function that describes the labels as strings</param> public static void AutomatonToDot <S>(Func <S, string> descr, IAutomaton <S> fa, string faName, string filename, RANKDIR rankdir, int fontsize, bool showName = false) { string fname = (filename.EndsWith(".dot") ? filename : filename + ".dot"); System.IO.StreamWriter sw = new System.IO.StreamWriter(fname); AutomatonToDot(descr, fa, faName, sw, rankdir, fontsize, showName); sw.Close(); }
///// <summary> ///// Write the automaton in dot format. ///// </summary> ///// <param name="fa">the automaton to write</param> ///// <param name="faName">the name of the automaton</param> ///// <param name="filename">the name of the output file</param> ///// <param name="rankdir">the main direction of the arrows</param> ///// <param name="fontsize">the size of the font in labels</param> ///// <param name="descr">function that describes the labels as strings</param> //public static void AutomatonToDot<S>(Func<S, string> descr, IAutomaton<S> fa, string faName, string filename, RANKDIR rankdir, int fontsize) //{ // string filenamedot = (filename.EndsWith(".dot") ? filename : filename + ".dot"); // System.IO.StreamWriter sw = new System.IO.StreamWriter(filenamedot); // AutomatonToDot(descr, fa, faName, sw, rankdir, fontsize, false); // sw.Close(); //} /// <summary> /// Write the automaton in dot format. /// </summary> /// <param name="fa">the automaton to write</param> /// <param name="faName">the name of the automaton</param> /// <param name="filename">the name of the output file</param> /// <param name="rankdir">the main direction of the arrows</param> /// <param name="fontsize">the size of the font in labels</param> /// <param name="descr">function that describes the labels as strings</param> public static void AutomatonToDot <S>(Func <S, string> descr, IAutomaton <S> fa, string faName, string filename, bool showName = false, Config config = null) { string fname = (filename.EndsWith(".dot") ? filename : filename + ".dot"); System.IO.StreamWriter sw = new System.IO.StreamWriter(fname); AutomatonToDot(descr, fa, faName, sw, showName, config ?? new Config()); sw.Close(); }
public static IAutomaton Create(IAutomaton child) { // Prevent some infinite recursions if (child is EmptyState || child is StarState) { return(child); } return(new StarState(child)); }
public static IAutomaton Create(IAutomaton s) { if (s is NotState ns) { return(ns.State); } return(new NotState(s)); }
public Relay(Actuator actuator, IAutomaton <T> automaton) { _automaton = automaton; _depQueue = new Dependent(UpdateQueue); _depQueue.Invalidated += delegate { actuator.RequestTrigger(this); }; _depQueue.OnGet(); }
private static void PrintScan(IAutomaton automaton) { for (int y = 0; y < automaton.Height; y++) { for (int x = 0; x < automaton.Width; x++) { Console.Write(automaton.Cells[y, x]); } Console.WriteLine(); } }
public void Remove(IAutomaton automaton) { if (!_objs.ContainsKey(automaton)) { return; } var obj = _objs[automaton]; Entity.Destroy(obj); _objs.Remove(automaton); }
public static void Print(this IAutomaton @this) { Console.WriteLine($"start: {@this.StartState}"); Console.WriteLine($"ends: {string.Join(",", @this.AcceptingStates)}"); foreach (var kv in @this.TransitionsBySource) { var source = kv.Key; foreach (var t in kv.Value) { Console.WriteLine($"{source} --{t.Key}--> {string.Join(",", t)}"); } } }
private static void FindFirstRepeatedLayout(IAutomaton automaton) { var prevTiles = new HashSet <string>(); while (true) { string tiles = automaton.GetTileString(); if (prevTiles.Contains(tiles)) { return; } prevTiles.Add(tiles); automaton.Advance(); } }
//[Theory] //[InlineData(3)] //[InlineData(2)] //[InlineData(1)] //[InlineData(0)] //[InlineData(-1)] public void Automaton_ShouldThrow_ExceptionOnSmallHeight(int height) { const int width = 7; var message = $"Height of automaton should be more than 3{Environment.NewLine}Parameter name: {nameof(Automaton.Size)}{Environment.NewLine}Actual value was {height}."; var cellLifeService = Mock.Of <ICellLifeService>(); IAutomaton automaton = null; var exception = Record.Exception(() => automaton = new Automaton(width, height, cellLifeService, Mock.Of <ILogger>())); // checks automaton.Should().BeNull(); exception.Should().NotBeNull(); exception.Message.Should().Be(message); }
public static bool Read(this IAutomaton @this, string input) { @this.Print(); var state = new HashSet <int>(@this.GetEpsilonClosure(@this.StartState)); foreach (var c in input) { state = new HashSet <int>(@this.Step(state, c)); if (!state.Any()) { return(false); } } return(@this.AcceptingStates.Intersect(state).Any()); }
/// <summary> /// Write the automaton in dgml format in the current directory and open the file in a new process. /// </summary> /// <param name="k">restiction on label length</param> /// <param name="fa">the automaton to write</param> /// <param name="name">the name of the output file, if filename does not end with .dgml then .dgml is added as suffix</param> /// <param name="describeS">custom viewer for S, default is null, if null then ToString is used</param> public static void ShowGraph <S>(int k, IAutomaton <S> fa, string name, Func <S, string> describeS = null) { //if (!__tried_to_load_VS) //{ // //only try to load VS automation object model one time // TryLoadVS(); // __tried_to_load_VS = true; //} //if (VS == null) //{ SaveGraph(k, fa, name, describeS); OpenFileInNewProcess(name + (name.EndsWith(".dgml") ? "" : ".dgml")); //} //else // ShowGraphInVS(k, fa, name, describeS); }
public void Automaton_ShouldThrow_ExceptionOnNullService() { const int width = 4; const int height = 7; ICellLifeService cellLifeService = null; //var message = $"Exception of type 'System.ArgumentNullException' was thrown.{Environment.NewLine}Parameter name: {nameof(cellLifeService)}"; var message = $"Value cannot be null.{Environment.NewLine}Parameter name: {nameof(cellLifeService)}"; IAutomaton automaton = null; var exception = Record.Exception(() => automaton = new Automaton(width, height, cellLifeService, Mock.Of <ILogger>())); // checks automaton.Should().BeNull(); exception.Should().NotBeNull(); exception.Message.Should().Be(message); }
static void ShowGraphInVS <S>(int k, IAutomaton <S> fa, string name, Func <S, string> describeS = null) { string filename = name + (name.EndsWith(".dgml") ? "" : ".dgml"); //Access the top-level VS automation object model EnvDTE.DTE dte = (EnvDTE.DTE)VS; #region Close the dgml file if it is open try { System.Collections.IEnumerator wins = dte.Windows.GetEnumerator(); while (wins.MoveNext() == true) { EnvDTE.Window w = wins.Current as EnvDTE.Window; if (filename.Equals(w.Caption)) { w.Close(EnvDTE.vsSaveChanges.vsSaveChangesNo); break; } } } catch { //the operation dte.Windows.GetEnumerator() //may sometimes cause COMException //Ignore this exception, //then the window with given filename may still be open //and VS may ask to save changes, instead of ignoring //when the file is subsequently changed on disk } #endregion SaveGraph(k, fa, name, describeS); #region Open the dgml file in VS try { var dir = System.Environment.CurrentDirectory; var fullfilename = dir + "/" + filename; dte.ExecuteCommand("File.OpenFile", dir + "/" + filename); } catch { OpenFileInNewProcess(filename); } #endregion }
/// <summary> /// Write the automaton in dgml format in the current directory and open the file in a new process. /// </summary> /// <param name="k">restiction on label length</param> /// <param name="fa">the automaton to write</param> /// <param name="name">the name of the output file, if filename does not end with .dgml then .dgml is added as suffix</param> /// <param name="describeS">custom viewer for S, default is null, if null then ToString is used</param> public static void ShowGraph <S>(int k, IAutomaton <S> fa, string name, Func <S, string> describeS = null) { #if NETFRAMEWORK if (!__tried_to_load_VS) { //only try to load VS automation object model one time TryLoadVS(); __tried_to_load_VS = true; } if (VS != null) { ShowGraphInVS(k, fa, name, describeS); return; } #else SaveGraph(k, fa, name, describeS); OpenFileInNewProcess(name + (name.EndsWith(".dgml") ? "" : ".dgml")); #endif }
private string GetNonFinalRuleInfo <S>(IAutomaton <S> aut, int source, int target, List <S> rules) { string lab = ""; string info = ""; for (int i = 0; i < rules.Count; i++) { lab += (lab == "" ? "" : ",\n ") + aut.DescribeLabel(rules[i]); } int lab_length = lab.Length; if (_maxDgmlTransitionLabelLength >= 0 && lab_length > _maxDgmlTransitionLabelLength) { info += $" FullLabel = \"{lab}\""; lab = string.Concat(lab.AsSpan(0, _maxDgmlTransitionLabelLength), ".."); } return($"<Link Source=\"{source}\" Target=\"{target}\" Label=\"{lab}\" Category=\"NonepsilonTransition\" {info}/>"); }
public Terminal Repeat(Range r) { IAutomaton seq = DFA.EmptyState.Instance; for (int i = 0; i < r.Start.Value; ++i) { seq = DFA.SeqState.Create(automaton, seq); } if (r.End.IsFromEnd) { seq = DFA.SeqState.Create(seq, StarState.Create(automaton)); } else { for (int i = r.Start.Value; i < r.End.Value; ++i) { seq = DFA.SeqState.Create(seq, DFA.OrState.Create(DFA.EmptyState.Instance, automaton)); } } return(new Terminal(seq)); }
public static void CopyTo(this IAutomaton @this, IAutomatonBuilder builder, out int oldNewStartState, out IEnumerable <int> oldNewAcceptingStates) { var stateMapping = new Dictionary <int, int>(); for (var state = 0; state < @this.StateCount; state++) { stateMapping.Add(state, builder.AddState()); } foreach (var kv in @this.TransitionsBySource) { var source = stateMapping[kv.Key]; var transition = kv.Value; foreach (var target in transition) { foreach (var x in target.Select(v => stateMapping[v])) { builder.AddTransition(source, target.Key, x); } } } oldNewStartState = stateMapping[@this.StartState]; oldNewAcceptingStates = @this.AcceptingStates.Select(s => stateMapping[s]).ToArray(); }
protected void Add(IAutomaton a) { _automata.Add(a); }
protected void Add(IAutomaton automaton) => OnlyDuringInit(() => _automata.Add(automaton));