string GetTokenFromRules(string token, ProductionRules pr, string notThis = "", bool isContradiction = false) { float rand = UnityEngine.Random.value; float tracker = 0; List <Pair> rules = pr.rules[token]; for (int i = 0; i < rules.Count; i++) { if (rules[i].rule == notThis) { continue; } if (isContradiction && prevContradictions.Contains(rules[i].rule)) { continue; } tracker += rules[i].probability; if (tracker >= rand) { return(rules[i].rule); } } if (rules[rules.Count - 1].rule == notThis) { return(rules[0].rule); } return(rules[rules.Count - 1].rule); }
/// <summary> /// Creates a new <see cref="Regex"/> instance based on the lexer's production rules. /// </summary> /// <returns>The <see cref="Regex"/> instance which was created.></returns> private static Regex CreateLexerRegex() { var pattern = String.Join("|", ProductionRules.Select(x => $"(?<{x.Key}>{x.Value})")); var regex = new Regex(pattern, RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.Multiline); return(regex); }
public void GenerateTraits(string type, Evidence e, Dictionary <string, string> evidencelist, bool isWitness = false, List <string> prevTraits = null) { ParseProductionRules("Evidence/" + type); if (type == "weapon") { Debug.Log(prodRules.rules.ContainsKey("material")); } e.details = GenerateNarrative("Evidence/" + type); List <string> dets = new List <string>(e.details.Keys); List <string> detVals = new List <string>(e.details.Values); for (int j = 0; j < dets.Count; j++) { if (!evidencelist.ContainsKey(dets[j])) { evidencelist.Add(dets[j], detVals[j]); } } if (isWitness) { List <string> oldtraits = new List <string>(); List <string> newtraits = new List <string>(); List <string> traittypes = new List <string>(); List <string> keyList = new List <string>(e.details.Keys); foreach (string trait in keyList) { if (prevTraits.Contains(e.details[trait])) { ProductionRules pr = prodRules; List <Pair> rules = pr.rules[trait]; for (int i = 0; i < rules.Count; i++) { if (!prevTraits.Contains(rules[i].rule)) { traittypes.Add(trait); oldtraits.Add(e.details[trait]); Debug.Log("must replace " + e.details[trait] + " with " + rules[i].rule); e.details[trait] = rules[i].rule; newtraits.Add(e.details[trait]); break; } } } prevTraits.Add(e.details[trait]); if (!evidencelist.ContainsKey(trait)) { evidencelist.Add(trait, e.details[trait]); } else { evidencelist[trait] = e.details[trait]; } } ReplaceTraits(oldtraits, newtraits, type, traittypes); } }
static void Main(string[] args) { StreamReader reader = File.OpenText(@"C:\Users\Marinela\source\repos\LFPC LAB\LLParsing\rules.txt"); string line; var productions = new ProductionRules(); while ((line = reader.ReadLine()) != null) { string[] rule = line.Split("->"); productions.Add(rule[0], rule[1]); } Console.WriteLine("Initial form of the grammar:"); Helper.Display(productions); Console.WriteLine("Eliminate left recursion:"); productions.RemoveLeftRecursion(productions); Helper.Display(productions); Console.WriteLine("Obtain FIRST:"); List <KeyValuePair <string, string> > first = Parser.GetFirst(productions); Helper.Display(first); Console.WriteLine("Obtain FOLLOW:"); List <KeyValuePair <string, string> > follow = Parser.GetFollow(productions); Helper.Display(follow); }
public void ReadFromFile(string filename) { string[] lines = System.IO.File.ReadAllLines("../../Input/" + filename); Nonterminals = new HashSet <string>(lines[0].Split(' ')); Terminals = new HashSet <string>(lines[1].Split(' ')); StartSymbol = lines[2]; foreach (var line in lines.Skip(3)) { string[] elements = line.Split('?'); string[] right = elements[1].Split(' '); var produRule = new ProductionRule() { Left = elements[0], Right = right.ToList() }; ProductionRules.Add(produRule, count++); } Console.WriteLine("Terminals:"); foreach (var t in Terminals) { Console.Write(t + " "); } Console.WriteLine("\nNonterminals"); foreach (var t in Nonterminals) { Console.Write(t + " "); } Console.WriteLine("\nProduction rules"); foreach (var rule in ProductionRules) { Console.Write(rule.Key.Left + " -> " + String.Join(" ", rule.Key.Right) + " (" + rule.Value + ")"); Console.WriteLine(); } }
public static ProductionRules GetFollow(ProductionRules rules) { ProductionRules first = GetFirst(rules); List <string> nonTerminals = GetNonterminals(rules); ProductionRules follow = new ProductionRules(); List <string> value = new List <string>(); for (int n = 0; n < nonTerminals.Count; ++n) { if (nonTerminals[n] == "S") { follow.Add(nonTerminals[n], "$"); } for (int item = 0; item < rules.Count; ++item) { value.AddRange(rules[item].Value.Select(d => d.ToString())); if (value.Contains(nonTerminals[n])) { for (int i = value.IndexOf(nonTerminals[n]); i < value.Count; i++) { try { if (Helper.IsLower(value[i + 1])) { follow.Add(nonTerminals[n], value[i + 1]); break; } if (Helper.IsUpper(value[i + 1])) { for (int f = 0; f < first.Count; ++f) { if (first[f].Key == value[i + 1] && first[f].Value != "*") { follow.Add(nonTerminals[n], value[i + 1]); } } } } catch (ArgumentOutOfRangeException) { var length = follow.Count; for (int f = 0; f < length; ++f) { if (follow[f].Key == rules[item].Key && value[i] != rules[item].Key) { follow.Add(nonTerminals[n], follow[f].Value); } } } } } value.Clear(); } } return(follow); }
public static bool AllCovered(ProductionRules rules, ProductionRules first) { List <string> nonRules = GetNonterminals(rules); List <string> nonFirst = GetNonterminals(first); bool allCovered = true; if (nonRules.Count > nonFirst.Count) { allCovered = false; } return(allCovered); }
public static List <string> GetNonterminals(ProductionRules rules) { List <string> nonTerm = new List <string>(); for (int item = 0; item < rules.Count; ++item) { nonTerm.Add(rules[item].Key); } List <string> distinctNames = nonTerm.Distinct().ToList(); return(distinctNames); }
public void OrderProductionRules() { Dictionary <ProductionRule, int> orderDict = new Dictionary <ProductionRule, int>(); Queue <ProductionRule> q = new Queue <ProductionRule>(); int num = 0; foreach (NonTerminal initialNonTerminal in InitialNonTerminals) { foreach (ProductionRule productionRule in ProductionRules.Where(r => r.LeftHandNonTerminal == initialNonTerminal)) { if (!q.Contains(productionRule) && !orderDict.ContainsKey(productionRule)) { q.Enqueue(productionRule); orderDict[productionRule] = num++; } } } while (q.Count != 0) { ProductionRule takenRule = q.Dequeue(); foreach (ProductionRuleToken productionRuleToken in takenRule.RightHandSide.GetTokens()) { if (productionRuleToken is NonTerminalToken) { foreach (ProductionRule productionRule in ProductionRules.Where(r => r.LeftHandNonTerminal == ((NonTerminalToken)productionRuleToken).NonTerminal)) { if (!q.Contains(productionRule) && !orderDict.ContainsKey(productionRule)) { q.Enqueue(productionRule); orderDict[productionRule] = num++; } } } } } foreach (ProductionRule productionRule in ProductionRules) { if (!orderDict.ContainsKey(productionRule)) { q.Enqueue(productionRule); orderDict[productionRule] = num++; } } productionRules.Sort(delegate(ProductionRule r1, ProductionRule r2) { return(orderDict[r1].CompareTo(orderDict[r2])); }); }
public static ProductionRules GetFirst(ProductionRules rules) { ProductionRules first = new ProductionRules(); List <string> value = new List <string>(); for (int item = 0; item < rules.Count; ++item) { value.AddRange(rules[item].Value.Select(d => d.ToString())); if (Helper.IsLower(value[0])) { first.Add(rules[item].Key, value[0]); } value.Clear(); } do { for (int item = 0; item < rules.Count; ++item) { value.AddRange(rules[item].Value.Select(d => d.ToString())); if (Helper.IsUpper(value[0]) && value[0] != "*") { for (int j = 0; j < first.Count; ++j) { if (first[j].Key.Contains(value[0]) && first[j].Value != "*") { first.Add(rules[item].Key, first[j].Value); } } } value.Clear(); } }while (!AllCovered(rules, first)); while (rules.Count != first.Count) { Helper.GetDistinct(first); } Helper.GetDistinct(first); return(first); }
public void GenerateTestimony(string name, string narrative, Dictionary <string, string> tokens, int contracount) { ProductionRules pr = prodRules; Dictionary <string, string> savedTokens = new Dictionary <string, string>(); TextAsset file = Resources.Load("Textfiles/Grammar/Axioms/Testimony/" + name) as TextAsset; string ax = file.text; string[] axiom = ax.Split('\n'); string output = ""; string token = ""; string result = ""; string truth = ""; List <int> contradictions = new List <int>(); for (int i = 0; i < contracount; i++) { int cont = UnityEngine.Random.Range(3, axiom.Length); while (contradictions.Contains(cont)) { cont = UnityEngine.Random.Range(3, axiom.Length); } contradictions.Add(cont); } for (int i = 0; i < axiom.Length; i++) { char[] chars = axiom[i].ToCharArray(); if (contradictions.Contains(i)) { output += "lie;"; } else if (i >= 3) { output += "truth;"; } for (int c = 0; c < chars.Length; c++) { if (chars[c] == '<') { output += '@'; c++; token = ""; while (chars[c] != '>') { token += chars[c]; c++; } Debug.Log(token); truth = tokens[token]; if (contradictions.Contains(i)) { result = GetTokenFromRules(token, pr, tokens[token], true); } else { result = truth; } output += result; output += '@'; savedTokens.Add(token, result); } else { output += chars[c]; } } if (contradictions.Contains(i)) { output += ";" + truth + ";" + result; prevContradictions.Add(result); } output += '\n'; } output = output.Substring(0, output.Length - 1); Debug.Log(output); TextAsset outputasset = new TextAsset(output); if (GeneratedAssets.ContainsKey(name)) { GeneratedAssets[name] = outputasset; } else { GeneratedAssets.Add(name, outputasset); } AddTraitsFromNarrative(tokens, name); return; }
public Dictionary <string, string> GenerateNarrative(string name) { string[] path = name.Split('/'); string truename = path[path.Length - 1]; ProductionRules pr = prodRules; Debug.Log(name); Dictionary <string, string> savedTokens = new Dictionary <string, string>(); TextAsset file = Resources.Load("Textfiles/Grammar/Axioms/" + name) as TextAsset; string ax = file.text; string[] axiom = ax.Split('\n'); string output = ""; string token = ""; string result = ""; for (int i = 0; i < axiom.Length; i++) { char[] chars = axiom[i].ToCharArray(); for (int c = 0; c < chars.Length; c++) { if (chars[c] == '<') { output += '@'; c++; token = ""; while (chars[c] != '>') { token += chars[c]; c++; } result = GetTokenFromRules(token, pr); output += result; output += '@'; savedTokens.Add(token, result); } else { output += chars[c]; } } output += '\n'; } Debug.Log(output); TextAsset outputasset = new TextAsset(output); GeneratedAssets.Add(truename, outputasset); return(savedTokens); }
// Method that will create the different nodes in the graphs and will organize them using the production rules public void GenerateMission(int minTaskNumber, int maxTaskNumber, int minOrganizeTaskTries, int maxOrganizeTaskTries, float probabiltyApplyOrganizationRule) { // Randomly choose the number task nodes int numberTaskNodes = Random.Range(minTaskNumber, maxTaskNumber); // Set the number of total nodes in the graph based on the number of task nodes plus the entance and goal nodes totalNodes = numberTaskNodes + 2; // Randomly choose the number of times the algorithm will try to apply the reorganize tasks production rules int numberOrganizeTaskTries = Random.Range(minOrganizeTaskTries, maxOrganizeTaskTries); // The graph always start with the start mission production rule ProductionRules.StartMission((StartNode)rootNode, this); // The first node to the right of the root of the graph is going to be always a task node TaskNode currentTaskNode = (TaskNode)rootNode.getConnection(Direction.Right); // The node to the right of the first task node is going to be always the goal node GoalNode goalNode = (GoalNode)currentTaskNode.getConnection(Direction.Right); // The first step to create the mission is to add all the tasks one by one for (int i = 0; i < numberTaskNodes; i++) { ProductionRules.AddTask(currentTaskNode, goalNode); currentTaskNode = (TaskNode)goalNode.getConnection(Direction.Left); } // The next and final step is to reorganize the tasks position starting from the right of the root node, at this stage the root is always going to be an entrance node and no rules can be applied to it AlphabetNode currentNode = rootNode.getConnection(Direction.Right); while (numberOrganizeTaskTries > 0) { // Decide whether to try apply rule from current node or go to the next one if (currentNode is TaskNode && !currentNode.isTerminal() && Random.Range(0.0f, 1.0f) < probabiltyApplyOrganizationRule) { // Get number of nodes from the current that are also non terminal task nodes towards the right AlphabetNode nextRightNode = currentNode.getConnection(Direction.Right); List <AlphabetNode> connections = new List <AlphabetNode>(); // The biggest number of task nodes taken by a production rule is six for (int i = 0; i < 6; i++) { if (nextRightNode != null && nextRightNode is TaskNode && !nextRightNode.isTerminal()) { connections.Add(nextRightNode); nextRightNode = nextRightNode.getConnection(Direction.Right); } } // Apply production rules based on the number of right task connections from current node, when multiple rules can be applied, all of them have the same probability of being picked switch (connections.Count) { case 2: // Only one rule can be applied ProductionRules.ReorganizeThreeTasks((TaskNode)currentNode, (TaskNode)connections[0], (TaskNode)connections[1]); break; case 3: // Two rules can be applied if (Random.Range(0.0f, 1.0f) > 0.5f) { ProductionRules.ReorganizeThreeTasks((TaskNode)currentNode, (TaskNode)connections[0], (TaskNode)connections[1]); } else { ProductionRules.ReorganizeFourTasks((TaskNode)currentNode, (TaskNode)connections[0], (TaskNode)connections[1], (TaskNode)connections[2]); } break; case 4: // Three rules can be applied float random = Random.Range(0.0f, 1.0f); if (random < (1.0f / 3.0f)) { ProductionRules.ReorganizeThreeTasks((TaskNode)currentNode, (TaskNode)connections[0], (TaskNode)connections[1]); } else if (random > (2.0f / 3.0f)) { ProductionRules.ReorganizeFourTasks((TaskNode)currentNode, (TaskNode)connections[0], (TaskNode)connections[1], (TaskNode)connections[2]); } else { ProductionRules.ReorganizeFiveTasks((TaskNode)currentNode, (TaskNode)connections[0], (TaskNode)connections[1], (TaskNode)connections[2], (TaskNode)connections[3]); } break; case 5: // Four rules can be applied random = Random.Range(0.0f, 1.0f); if (random < 0.25f) { ProductionRules.ReorganizeThreeTasks((TaskNode)currentNode, (TaskNode)connections[0], (TaskNode)connections[1]); } else if (random > 0.25f && random < 0.5f) { ProductionRules.ReorganizeFourTasks((TaskNode)currentNode, (TaskNode)connections[0], (TaskNode)connections[1], (TaskNode)connections[2]); } else if (random > 0.75f) { ProductionRules.ReorganizeFiveTasks((TaskNode)currentNode, (TaskNode)connections[0], (TaskNode)connections[1], (TaskNode)connections[2], (TaskNode)connections[3]); } else { ProductionRules.ReorganizeSixTasks((TaskNode)currentNode, (TaskNode)connections[0], (TaskNode)connections[1], (TaskNode)connections[2], (TaskNode)connections[3], (TaskNode)connections[4]); } break; } } // Get next node, try right first and down second AlphabetNode previousCurrent = currentNode; currentNode = currentNode.getConnection(Direction.Right); if (currentNode == null) { currentNode = previousCurrent.getConnection(Direction.Down); } // If the goal node is reached, try to apply the productions rules from the beginnig if (currentNode is GoalNode || currentNode == null) { currentNode = rootNode; } // Decrease tries numberOrganizeTaskTries--; } }